text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as React from 'react'; import Scaler from './Scaler'; export type imageAttr = 'width' | 'height'; import dataURLtoBlob from './canvasToBlob.polyfills'; import { debounce, downScaleImage, applyTransform, getLocale } from './utils'; function isImage(file: File) { return file.type && /^image\//g.test(file.type); } export interface ImageState { width: number; height: number; left: number; top: number; [x: string]: number; }; let startX = 0; let startY = 0; let Δleft = 0; let Δtop = 0; let left = 0; let top = 0; let dragging = false; function limit(value: number, limitArray: number[]): number { const min = Math.min(limitArray[0], limitArray[1]); const max = Math.max(limitArray[0], limitArray[1]); if (value < min) { return min; } if (value > max) { return max; } return value; } export interface IDialogProps { title: any; defaultProps: any; footer: any; visible: boolean; width: number; onCancel: (args?: any) => any; onOk?: (args?: any) => any; } export interface ICropperProps { file: File; size: number[]; onChange: (args: any) => void; prefixCls?: string; circle?: boolean; spin?: React.ComponentElement<any, any>; renderModal?: (args?: any) => React.ComponentElement<IDialogProps, any>; locale?: String; thumbnailSizes?: number[][]; resizer?: (from: HTMLCanvasElement, to: HTMLCanvasElement) => Promise<HTMLCanvasElement>; } export default class Cropper extends React.Component<ICropperProps, any> { static defaultProps = { prefixCls: 'rc', size: [32, 32], circle: false, onChange: () => {}, locale: 'en-US', }; refNodes: { viewport?: HTMLElement, dragger?: HTMLElement, dragNotice?: HTMLElement, Canvas2x?: HTMLCanvasElement, Canvas1x?: HTMLCanvasElement, }; updateThumbnail = debounce(() => { const { image, width, height } = this.state; if (this.refNodes) { for (const item of [ 'Canvas2x', 'Canvas1x' ]) { if (this.refNodes[item]) { this.refNodes[item].getContext('2d').drawImage(image, left, top, width, height); } } } }, 100); constructor(props) { super(props); const { size } = props; let imageState; if (size[0] === size[1]) { imageState = { width: 320, height: 320, }; } else { imageState = { height: 320, width: 320 / size[1] * size[0], } as ImageState; } this.state = { image: null, viewport: [imageState.width, imageState.height], width: 320, height: 320, dragging: false, scaleRange: [1, 1], scale: 1, visible: false, }; this.refNodes = {}; } componentDidMount() { this.readFile(this.props.file); document.addEventListener('mouseup', this.dragEnd); document.addEventListener('mousemove', this.dragOver); } componentWillUnmount() { document.removeEventListener('mouseup', this.dragEnd); document.removeEventListener('mousemove', this.dragOver); } readFile = (file: File) => { const reader = new FileReader(); if (file && isImage(file)) { reader.readAsDataURL(file); } reader.onload = () => this.loadImage(reader); } loadImage = (reader: FileReader) => { // const reader = new FileReader(); const image = new Image(); // Although you can use images without CORS approval in your canvas, doing so taints the canvas. // Once a canvas has been tainted, you can no longer pull data back out of the canvas. // For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; // doing so will throw a security error. // This protects users from having private data exposed by using images // to pull information from remote web sites without permission. image.setAttribute('crossOrigin', 'anonymous'); image.onload = () => this.normalizeImage(image); image.src = reader.result; } scaleImage = (scale) => { if (scale === this.state.scale) { return; } const { width, height } = this.state.image; const imageState = { width: width * scale, height: height * scale, } as ImageState; this.setState({ scale, width: imageState.width, height: imageState.height, widthLimit: [this.state.viewport[0] - imageState.width, 0], heightLimit: [this.state.viewport[1] - imageState.height, 0], }); left = limit( (this.state.viewport[0] - imageState.width) / 2 + Δleft, [this.state.viewport[0] - imageState.width, 0], ); top = limit( (this.state.viewport[1] - imageState.height) / 2 + Δtop, [this.state.viewport[1] - imageState.height, 0], ); this.applyPositions(); } applyImageState = (imageState) => { this.setState({ width: imageState.width, height: imageState.height, widthLimit: [this.state.viewport[0] - imageState.width, 0], heightLimit: [this.state.viewport[1] - imageState.height, 0], }, this.updateThumbnail); left = (this.state.viewport[0] - imageState.width) / 2; top = (this.state.viewport[1] - imageState.height) / 2; this.applyPositions(); } // 初始化 Cropper,图片的尺寸会默认 fit 320 * 320 normalizeImage = (image) => { const { width, height } = image; const { viewport } = this.state; const widthProportional = width / viewport[0]; const heightProportional = height / viewport[1]; const ΔProportional = widthProportional / heightProportional; const IdpVar: imageAttr = ΔProportional > 1 ? 'height' : 'width'; // 自变量 const depVar: imageAttr = ΔProportional > 1 ? 'width' : 'height'; // 因变量 const scale = Number((viewport[Number(ΔProportional > 1)] / image[IdpVar]).toFixed(4)); // console.log('基准缩放属性:', IdpVar,':', image[IdpVar], 'px', // '缩放至:', viewport[Number(ΔProportional > 1)], 'px', // '缩放比例:', scale); // tslint:ignore const imageState = { [IdpVar]: viewport[Number(ΔProportional > 1)], [depVar]: viewport[Number(ΔProportional > 1)] / viewport[Number(ΔProportional > 1)] * image[depVar] * scale, } as ImageState; this.setState({ image, scale, scaleRange: [scale, 1.777], visible: true, }, () => this.applyImageState(imageState)); } applyPositions = () => { if (this.refNodes.viewport) { applyTransform(this.refNodes.viewport, `translate3d(${left}px,${top}px,0)`); } if (this.refNodes.dragger) { applyTransform(this.refNodes.dragger, `translate3d(${left}px,${top}px,0)`); } } onMouseDown = () => { this.setState({ dragging: true, }); } dragStart = (ev) => { dragging = true; startX = ev.clientX; startY = ev.clientY; } dragOver = (ev) => { if (dragging) { Δleft += (ev.clientX - startX); Δtop += (ev.clientY - startY); left = limit(left + (ev.clientX - startX), this.state.widthLimit); top = limit(top + (ev.clientY - startY), this.state.heightLimit); startX = ev.clientX; startY = ev.clientY; this.applyPositions(); this.updateThumbnail(); // 拖动后,不再提示可拖动 if (this.refNodes.dragNotice) { this.refNodes.dragNotice.style.display = 'none'; } } } dragEnd = () => { dragging = false; } handleCancel = () => { this.props.onChange(null); this.hideModal(); } handleOk = () => { const { image, width, height, scale, viewport } = this.state; const { resizer } = this.props; downScaleImage(image, scale, resizer).then(scaledImage => { const canvas = document.createElement('canvas'); canvas.style.width = `${viewport[0]}px`; canvas.style.height = `${viewport[1]}px`; canvas.setAttribute('width', viewport[0]); canvas.setAttribute('height', viewport[1]); const context = canvas.getContext('2d'); if (!context) { return; } if (!/image\/png/g.test(this.props.file.type)) { context.fillStyle = '#fff'; context.fillRect(0, 0, viewport[0], viewport[1]); } // if circle... if (this.props.circle) { context.save(); context.beginPath(); context.arc( viewport[0] / 2, viewport[1] / 2, Math.min(viewport[0] / 2, viewport[1] / 2), 0, Math.PI * 2, true, ); context.closePath(); context.clip(); } context.drawImage(scaledImage, left, top, width, height); if (this.props.circle) { context.beginPath(); context.arc(0, 0, 2, 0, Math.PI, true); context.closePath(); context.restore(); } if (canvas.toBlob) { canvas.toBlob( blob => { this.props.onChange(blob); this.hideModal(); }, this.props.file.type); } else { const dataUrl = canvas.toDataURL(this.props.file.type); this.props.onChange(dataURLtoBlob(dataUrl)); this.hideModal(); } }); } hideModal = () => { this.setState({ visible: false, }); document.body.style.overflow = ''; } getThumbnailSize = (index): number[] => { const { size, thumbnailSizes } = this.props; if (thumbnailSizes && thumbnailSizes.hasOwnProperty(index)) { return thumbnailSizes[index]; } if (index === 0) { return [ size[0] * 2, size[1] * 2]; } return [ size[0], size[1] ]; } applyRef(refName: string, ele: Element) { this.refNodes[refName] = ele; } render() { const { prefixCls, circle, spin, renderModal } = this.props; const { image, width, height, scale, scaleRange, viewport } = this.state; const style = { left: 0, top: 0 }; const draggerEvents = { onMouseDown: this.dragStart, }; const footer = [ <Scaler key="scaler" prefixCls={prefixCls} onChange={this.scaleImage} value={scale} min={scaleRange[0]} max={scaleRange[1]} />, <button className={`${prefixCls}-btn ${prefixCls}-btn-ghost`} key="back" type="ghost" onClick={this.handleCancel} > {getLocale('cancel', this.props.locale)} </button>, <button className={`${prefixCls}-btn ${prefixCls}-btn-primary`} key="submit" type="primary" onClick={this.handleOk} > {getLocale('submit', this.props.locale)} </button>, ]; const viewPortStyle = { width: viewport[0], height: viewport[1] }; const previewClassName = circle ? 'radius' : ''; const cropperElement = image ? (<div className={`${prefixCls}-cropper-wrapper`}> <div className={`${prefixCls}-cropper`}> <div className={`${prefixCls}-thumbnail`} style={viewPortStyle}> <div className="thumbnail-window" style={viewPortStyle}> <img src={image.src} ref={this.applyRef.bind(this, 'viewport')} width={width} height={height} style={style} /> </div> <img {...draggerEvents} ref={this.applyRef.bind(this, 'dragger')} src={image.src} width={width} height={height} style={style} className={`${prefixCls}-background`} draggable={false} /> {scale > scaleRange[0] ? <div className="candrag-notice-wrapper" ref="dragNotice"> <span className="candrag-notice">{getLocale('drag to crop', this.props.locale)}</span> </div> : null} </div> </div> <div className={`${prefixCls}-thumbnail-preview`}> <h4>{getLocale('preview', this.props.locale)}</h4> <div className="size-2x"> <canvas className={previewClassName} ref={this.applyRef.bind(this, 'Canvas2x')} width={viewport[0]} height={viewport[1]} style={{width: this.getThumbnailSize(0)[0], height: this.getThumbnailSize(0)[1]}} ></canvas> <p>2x: {`${this.getThumbnailSize(0)[0]}px * ${this.getThumbnailSize(0)[1]}px`}</p> </div> <div className="size-1x"> <canvas className={previewClassName} ref={this.applyRef.bind(this, 'Canvas1x')} width={viewport[0]} height={viewport[1]} style={{width: this.getThumbnailSize(1)[0], height: this.getThumbnailSize(1)[1]}} ></canvas> <p>1x: {`${this.getThumbnailSize(1)[0]}px * ${this.getThumbnailSize(1)[1]}px`}</p> </div> </div> </div>) : null; if (image) { return (<div> {spin} {renderModal ? React.cloneElement(renderModal(), { visible: this.state.visible, title: getLocale('edit picture', this.props.locale), width: 800, footer, onCancel: this.handleCancel, }, cropperElement) : <div>{cropperElement} {footer}</div> } </div>); } return <span> loading... </span>; } }
the_stack
"use strict"; import { TokenCredential } from "@azure/core-http"; import { TokenCredentialsBase } from "@azure/ms-rest-nodeauth"; import * as msRestNodeAuth from "@azure/ms-rest-nodeauth"; import * as identity from "@azure/identity"; import { SubscriptionClient } from "@azure/arm-subscriptions"; import * as fs from "fs-extra"; import * as path from "path"; import { AzureAccountProvider, ConfigFolderName, SubscriptionInfo } from "@microsoft/teamsfx-api"; import { NotSupportedProjectType, NotFoundSubscriptionId } from "../error"; import { login, LoginStatus } from "./common/login"; import { signedIn, signedOut, subscriptionInfoFile } from "./common/constant"; import { isWorkspaceSupported } from "../utils"; import CLILogProvider from "./log"; import { LogLevel as LLevel } from "@microsoft/teamsfx-api"; import * as os from "os"; import { AzureSpCrypto } from "./cacheAccess"; /** * Prepare for service principal login, not fully implemented */ export class AzureAccountManager extends login implements AzureAccountProvider { static tokenCredentialsBase: TokenCredentialsBase; static tokenCredential: TokenCredential; private static subscriptionId: string | undefined; private static instance: AzureAccountManager; private static clientId: string; private static secret: string; private static tenantId: string; private static subscriptionName: string | undefined; private static rootPath: string | undefined; /** * Gets instance * @returns instance */ public static getInstance(): AzureAccountManager { if (!AzureAccountManager.instance) { AzureAccountManager.instance = new AzureAccountManager(); } return AzureAccountManager.instance; } public async init(clientId: string, secret: string, tenantId: string): Promise<void> { AzureAccountManager.clientId = clientId; if (secret[0] === "~") { const expandPath = path.join(os.homedir(), secret.slice(1)); if (fs.pathExistsSync(expandPath)) { AzureAccountManager.secret = expandPath; } else { AzureAccountManager.secret = secret; } } else if (fs.pathExistsSync(secret)) { AzureAccountManager.secret = secret; } else { AzureAccountManager.secret = secret; } AzureAccountManager.tenantId = tenantId; try { await this.getAccountCredentialAsync(); await AzureSpCrypto.saveAzureSP(clientId, AzureAccountManager.secret, tenantId); } catch (error) { CLILogProvider.necessaryLog(LLevel.Info, JSON.stringify(error)); throw error; } return; } public async load(): Promise<boolean> { const data = await AzureSpCrypto.loadAzureSP(); if (data) { AzureAccountManager.clientId = data.clientId; AzureAccountManager.secret = data.secret; AzureAccountManager.tenantId = data.tenantId; } return false; } async getAccountCredentialAsync(): Promise<TokenCredentialsBase | undefined> { await this.load(); if (AzureAccountManager.tokenCredentialsBase == undefined) { let authres; if (await fs.pathExists(AzureAccountManager.secret)) { authres = await msRestNodeAuth.loginWithServicePrincipalCertificate( AzureAccountManager.clientId, AzureAccountManager.secret, AzureAccountManager.tenantId ); AzureAccountManager.tokenCredentialsBase = authres; } else { authres = await msRestNodeAuth.loginWithServicePrincipalSecretWithAuthResponse( AzureAccountManager.clientId, AzureAccountManager.secret, AzureAccountManager.tenantId ); AzureAccountManager.tokenCredentialsBase = authres.credentials; } } return new Promise((resolve) => { resolve(AzureAccountManager.tokenCredentialsBase); }); } async getIdentityCredentialAsync(): Promise<TokenCredential | undefined> { await this.load(); if (AzureAccountManager.tokenCredential == undefined) { const identityCredential = new identity.ClientSecretCredential( AzureAccountManager.tenantId, AzureAccountManager.clientId, AzureAccountManager.secret ); const credentialChain = new identity.ChainedTokenCredential(identityCredential); AzureAccountManager.tokenCredential = credentialChain; } return new Promise((resolve) => { resolve(AzureAccountManager.tokenCredential); }); } /** * singnout from Azure */ async signout(): Promise<boolean> { return new Promise(async (resolve) => { await AzureSpCrypto.clearAzureSP(); resolve(true); }); } async getSubscriptionList(azureToken: TokenCredentialsBase): Promise<AzureSubscription[]> { await this.load(); const client = new SubscriptionClient(azureToken); const subscriptions = await listAll(client.subscriptions, client.subscriptions.list()); const subs: Partial<AzureSubscription>[] = subscriptions.map((sub) => { return { displayName: sub.displayName, subscriptionId: sub.subscriptionId }; }); const filteredSubs = subs.filter( (sub) => sub.displayName !== undefined && sub.subscriptionId !== undefined ); return filteredSubs.map((sub) => { return { displayName: sub.displayName!, subscriptionId: sub.subscriptionId! }; }); } async getStatus(): Promise<LoginStatus> { await this.load(); if ( AzureAccountManager.clientId && AzureAccountManager.secret && AzureAccountManager.tenantId ) { return { status: signedIn, }; } return { status: signedOut, }; } getJsonObject(showDialog?: boolean): Promise<Record<string, unknown> | undefined> { throw new Error("Method not implemented."); } async listSubscriptions(): Promise<SubscriptionInfo[]> { const credential = await this.getAccountCredentialAsync(); if (credential) { const client = new SubscriptionClient(credential); let answers: SubscriptionInfo[] = []; if (AzureAccountManager.tenantId) { let credential; if (await fs.pathExists(AzureAccountManager.secret)) { const authres = await msRestNodeAuth.loginWithServicePrincipalCertificate( AzureAccountManager.clientId, AzureAccountManager.secret, AzureAccountManager.tenantId ); credential = authres; } else { const authres = await msRestNodeAuth.loginWithServicePrincipalSecretWithAuthResponse( AzureAccountManager.clientId, AzureAccountManager.secret, AzureAccountManager.tenantId ); credential = authres.credentials; } const client = new SubscriptionClient(credential); const subscriptions = await listAll(client.subscriptions, client.subscriptions.list()); const filteredsubs = subscriptions.filter( (sub) => !!sub.displayName && !!sub.subscriptionId ); answers = answers.concat( filteredsubs.map((sub) => { return { subscriptionName: sub.displayName!, subscriptionId: sub.subscriptionId!, tenantId: AzureAccountManager.tenantId!, }; }) ); } return answers; } return []; } async setSubscription(subscriptionId: string): Promise<void> { const list = await this.listSubscriptions(); for (let i = 0; i < list.length; ++i) { const item = list[i]; if (item.subscriptionId === subscriptionId) { await this.saveSubscription({ subscriptionId: item.subscriptionId, subscriptionName: item.subscriptionName, tenantId: item.tenantId, }); AzureAccountManager.tenantId = item.tenantId; AzureAccountManager.subscriptionId = item.subscriptionId; AzureAccountManager.subscriptionName = item.subscriptionName; return; } } throw NotFoundSubscriptionId(); } async saveSubscription(subscriptionInfo: SubscriptionInfo): Promise<void> { const subscriptionFilePath = await this.getSubscriptionInfoPath(); if (!subscriptionFilePath) { return; } else { await fs.writeFile(subscriptionFilePath, JSON.stringify(subscriptionInfo, null, 4)); } } async getSubscriptionInfoPath(): Promise<string | undefined> { if (AzureAccountManager.rootPath) { if (isWorkspaceSupported(AzureAccountManager.rootPath)) { const subscriptionFile = path.join( AzureAccountManager.rootPath, `.${ConfigFolderName}`, subscriptionInfoFile ); return subscriptionFile; } else { return undefined; } } else { return undefined; } } getAccountInfo(): Record<string, string> | undefined { return {}; } async getSelectedSubscription(): Promise<SubscriptionInfo | undefined> { await this.readSubscription(); if (AzureAccountManager.subscriptionId) { const selectedSub: SubscriptionInfo = { subscriptionId: AzureAccountManager.subscriptionId, tenantId: AzureAccountManager.tenantId!, subscriptionName: AzureAccountManager.subscriptionName ?? "", }; return selectedSub; } else { return undefined; } } public setRootPath(rootPath: string): void { AzureAccountManager.rootPath = rootPath; } async readSubscription(): Promise<SubscriptionInfo | undefined> { const subscriptionFIlePath = await this.getSubscriptionInfoPath(); if (subscriptionFIlePath === undefined) { return undefined; } if (!fs.existsSync(subscriptionFIlePath)) { return undefined; } const content = (await fs.readFile(subscriptionFIlePath)).toString(); if (content.length == 0) { return undefined; } const subscriptionJson = JSON.parse(content); AzureAccountManager.subscriptionId = subscriptionJson.subscriptionId; AzureAccountManager.subscriptionName = subscriptionJson.subscriptionName; return { subscriptionId: subscriptionJson.subscriptionId, tenantId: subscriptionJson.tenantId, subscriptionName: subscriptionJson.subscriptionName, }; } } interface PartialList<T> extends Array<T> { nextLink?: string; } // Copied from https://github.com/microsoft/vscode-azure-account/blob/2b3c1a8e81e237580465cc9a1f4da5caa34644a6/sample/src/extension.ts // to list all subscriptions async function listAll<T>( client: { listNext(nextPageLink: string): Promise<PartialList<T>> }, first: Promise<PartialList<T>> ): Promise<T[]> { const all: T[] = []; for ( let list = await first; list.length || list.nextLink; list = list.nextLink ? await client.listNext(list.nextLink) : [] ) { all.push(...list); } return all; } export type AzureSubscription = { displayName: string; subscriptionId: string; }; export default AzureAccountManager.getInstance();
the_stack
import { CellRenderer } from './cellrenderer'; import { GraphicsContext } from './graphicscontext'; /** * A cell renderer which renders data values as text. */ export class TextRenderer extends CellRenderer { /** * Construct a new text renderer. * * @param options - The options for initializing the renderer. */ constructor(options: TextRenderer.IOptions = {}) { super(); this.font = options.font || '12px sans-serif'; this.textColor = options.textColor || '#000000'; this.backgroundColor = options.backgroundColor || ''; this.verticalAlignment = options.verticalAlignment || 'center'; this.horizontalAlignment = options.horizontalAlignment || 'left'; this.format = options.format || TextRenderer.formatGeneric(); } /** * The CSS shorthand font for drawing the text. */ readonly font: CellRenderer.ConfigOption<string>; /** * The CSS color for drawing the text. */ readonly textColor: CellRenderer.ConfigOption<string>; /** * The CSS color for the cell background. */ readonly backgroundColor: CellRenderer.ConfigOption<string>; /** * The vertical alignment for the cell text. */ readonly verticalAlignment: CellRenderer.ConfigOption<TextRenderer.VerticalAlignment>; /** * The horizontal alignment for the cell text. */ readonly horizontalAlignment: CellRenderer.ConfigOption<TextRenderer.HorizontalAlignment>; /** * The format function for the cell value. */ readonly format: TextRenderer.FormatFunc; /** * Paint the content for a cell. * * @param gc - The graphics context to use for drawing. * * @param config - The configuration data for the cell. */ paint(gc: GraphicsContext, config: CellRenderer.CellConfig): void { this.drawBackground(gc, config); this.drawText(gc, config); } /** * Draw the background for the cell. * * @param gc - The graphics context to use for drawing. * * @param config - The configuration data for the cell. */ drawBackground(gc: GraphicsContext, config: CellRenderer.CellConfig): void { // Resolve the background color for the cell. let color = CellRenderer.resolveOption(this.backgroundColor, config); // Bail if there is no background color to draw. if (!color) { return; } // Fill the cell with the background color. gc.fillStyle = color; gc.fillRect(config.x, config.y, config.width, config.height); } /** * Draw the text for the cell. * * @param gc - The graphics context to use for drawing. * * @param config - The configuration data for the cell. */ drawText(gc: GraphicsContext, config: CellRenderer.CellConfig): void { // Resolve the font for the cell. let font = CellRenderer.resolveOption(this.font, config); // Bail if there is no font to draw. if (!font) { return; } // Resolve the text color for the cell. let color = CellRenderer.resolveOption(this.textColor, config); // Bail if there is no text color to draw. if (!color) { return; } // Format the cell value to text. let format = this.format; let text = format(config); // Bail if there is no text to draw. if (!text) { return; } // Resolve the vertical and horizontal alignment. let vAlign = CellRenderer.resolveOption(this.verticalAlignment, config); let hAlign = CellRenderer.resolveOption(this.horizontalAlignment, config); // Compute the padded text box height for the specified alignment. let boxHeight = config.height - (vAlign === 'center' ? 1 : 2); // Bail if the text box has no effective size. if (boxHeight <= 0) { return; } // Compute the text height for the gc font. let textHeight = TextRenderer.measureFontHeight(font); // Set up the text position variables. let textX: number; let textY: number; // Compute the Y position for the text. switch (vAlign) { case 'top': textY = config.y + 2 + textHeight; break; case 'center': textY = config.y + config.height / 2 + textHeight / 2; break; case 'bottom': textY = config.y + config.height - 2; break; default: throw 'unreachable'; } // Compute the X position for the text. switch (hAlign) { case 'left': textX = config.x + 2; break; case 'center': textX = config.x + config.width / 2; break; case 'right': textX = config.x + config.width - 3; break; default: throw 'unreachable'; } // Clip the cell if the text is taller than the text box height. if (textHeight > boxHeight) { gc.beginPath(); gc.rect(config.x, config.y, config.width, config.height - 1); gc.clip(); } // Set the gc state. gc.font = font; gc.fillStyle = color; gc.textAlign = hAlign; gc.textBaseline = 'bottom'; // Draw the text for the cell. gc.fillText(text, textX, textY); } } /** * The namespace for the `TextRenderer` class statics. */ export namespace TextRenderer { /** * A type alias for the supported vertical alignment modes. */ export type VerticalAlignment = 'top' | 'center' | 'bottom'; /** * A type alias for the supported horizontal alignment modes. */ export type HorizontalAlignment = 'left' | 'center' | 'right'; /** * An options object for initializing a text renderer. */ export interface IOptions { /** * The font for drawing the cell text. * * The default is `'12px sans-serif'`. */ font?: CellRenderer.ConfigOption<string>; /** * The color for the drawing the cell text. * * The default `'#000000'`. */ textColor?: CellRenderer.ConfigOption<string>; /** * The background color for the cells. * * The default is `''`. */ backgroundColor?: CellRenderer.ConfigOption<string>; /** * The vertical alignment for the cell text. * * The default is `'center'`. */ verticalAlignment?: CellRenderer.ConfigOption<VerticalAlignment>; /** * The horizontal alignment for the cell text. * * The default is `'left'`. */ horizontalAlignment?: CellRenderer.ConfigOption<HorizontalAlignment>; /** * The format function for the renderer. * * The default is `TextRenderer.formatGeneric()`. */ format?: FormatFunc; } /** * A type alias for a format function. */ export type FormatFunc = CellRenderer.ConfigFunc<string>; /** * Create a generic text format function. * * @param options - The options for creating the format function. * * @returns A new generic text format function. * * #### Notes * This formatter uses the builtin `String()` to coerce any value * to a string. */ export function formatGeneric(options: formatGeneric.IOptions = {}): FormatFunc { let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } return String(value); }; } /** * The namespace for the `formatGeneric` function statics. */ export namespace formatGeneric { /** * The options for creating a generic format function. */ export interface IOptions { /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create a fixed decimal format function. * * @param options - The options for creating the format function. * * @returns A new fixed decimal format function. * * #### Notes * This formatter uses the builtin `Number()` and `toFixed()` to * coerce values. * * The `formatIntlNumber()` formatter is more flexible, but slower. */ export function formatFixed(options: formatFixed.IOptions = {}): FormatFunc { let digits = options.digits; let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } return Number(value).toFixed(digits); }; } /** * The namespace for the `formatFixed` function statics. */ export namespace formatFixed { /** * The options for creating a fixed format function. */ export interface IOptions { /** * The number of digits to include after the decimal point. * * The default is determined by the user agent. */ digits?: number; /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create a significant figure format function. * * @param options - The options for creating the format function. * * @returns A new significant figure format function. * * #### Notes * This formatter uses the builtin `Number()` and `toPrecision()` * to coerce values. * * The `formatIntlNumber()` formatter is more flexible, but slower. */ export function formatPrecision(options: formatPrecision.IOptions = {}): FormatFunc { let digits = options.digits; let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } return Number(value).toPrecision(digits); }; } /** * The namespace for the `formatPrecision` function statics. */ export namespace formatPrecision { /** * The options for creating a precision format function. */ export interface IOptions { /** * The number of significant figures to include in the value. * * The default is determined by the user agent. */ digits?: number; /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create a scientific notation format function. * * @param options - The options for creating the format function. * * @returns A new scientific notation format function. * * #### Notes * This formatter uses the builtin `Number()` and `toExponential()` * to coerce values. * * The `formatIntlNumber()` formatter is more flexible, but slower. */ export function formatExponential(options: formatExponential.IOptions = {}): FormatFunc { let digits = options.digits; let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } return Number(value).toExponential(digits); }; } /** * The namespace for the `formatExponential` function statics. */ export namespace formatExponential { /** * The options for creating an exponential format function. */ export interface IOptions { /** * The number of digits to include after the decimal point. * * The default is determined by the user agent. */ digits?: number; /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create an international number format function. * * @param options - The options for creating the format function. * * @returns A new international number format function. * * #### Notes * This formatter uses the builtin `Intl.NumberFormat` object to * coerce values. * * This is the most flexible (but slowest) number formatter. */ export function formatIntlNumber(options: formatIntlNumber.IOptions = {}): FormatFunc { let missing = options.missing || ''; let nft = new Intl.NumberFormat(options.locales, options.options); return ({ value }) => { if (value === null || value === undefined) { return missing; } return nft.format(value); }; } /** * The namespace for the `formatIntlNumber` function statics. */ export namespace formatIntlNumber { /** * The options for creating an intl number format function. */ export interface IOptions { /** * The locales to pass to the `Intl.NumberFormat` constructor. * * The default is determined by the user agent. */ locales?: string | string[]; /** * The options to pass to the `Intl.NumberFormat` constructor. * * The default is determined by the user agent. */ options?: Intl.NumberFormatOptions; /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create a date format function. * * @param options - The options for creating the format function. * * @returns A new date format function. * * #### Notes * This formatter uses `Date.toDateString()` to format the values. * * If a value is not a `Date` object, `new Date(value)` is used to * coerce the value to a date. * * The `formatIntlDateTime()` formatter is more flexible, but slower. */ export function formatDate(options: formatDate.IOptions = {}): FormatFunc { let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } if (value instanceof Date) { return value.toDateString(); } return (new Date(value)).toDateString(); }; } /** * The namespace for the `formatDate` function statics. */ export namespace formatDate { /** * The options for creating a date format function. */ export interface IOptions { /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create a time format function. * * @param options - The options for creating the format function. * * @returns A new time format function. * * #### Notes * This formatter uses `Date.toTimeString()` to format the values. * * If a value is not a `Date` object, `new Date(value)` is used to * coerce the value to a date. * * The `formatIntlDateTime()` formatter is more flexible, but slower. */ export function formatTime(options: formatTime.IOptions = {}): FormatFunc { let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } if (value instanceof Date) { return value.toTimeString(); } return (new Date(value)).toTimeString(); }; } /** * The namespace for the `formatTime` function statics. */ export namespace formatTime { /** * The options for creating a time format function. */ export interface IOptions { /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create an ISO datetime format function. * * @param options - The options for creating the format function. * * @returns A new ISO datetime format function. * * #### Notes * This formatter uses `Date.toISOString()` to format the values. * * If a value is not a `Date` object, `new Date(value)` is used to * coerce the value to a date. * * The `formatIntlDateTime()` formatter is more flexible, but slower. */ export function formatISODateTime(options: formatISODateTime.IOptions = {}): FormatFunc { let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } if (value instanceof Date) { return value.toISOString(); } return (new Date(value)).toISOString(); }; } /** * The namespace for the `formatISODateTime` function statics. */ export namespace formatISODateTime { /** * The options for creating an ISO datetime format function. */ export interface IOptions { /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create a UTC datetime format function. * * @param options - The options for creating the format function. * * @returns A new UTC datetime format function. * * #### Notes * This formatter uses `Date.toUTCString()` to format the values. * * If a value is not a `Date` object, `new Date(value)` is used to * coerce the value to a date. * * The `formatIntlDateTime()` formatter is more flexible, but slower. */ export function formatUTCDateTime(options: formatUTCDateTime.IOptions = {}): FormatFunc { let missing = options.missing || ''; return ({ value }) => { if (value === null || value === undefined) { return missing; } if (value instanceof Date) { return value.toUTCString(); } return (new Date(value)).toUTCString(); }; } /** * The namespace for the `formatUTCDateTime` function statics. */ export namespace formatUTCDateTime { /** * The options for creating a UTC datetime format function. */ export interface IOptions { /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Create an international datetime format function. * * @param options - The options for creating the format function. * * @returns A new international datetime format function. * * #### Notes * This formatter uses the builtin `Intl.DateTimeFormat` object to * coerce values. * * This is the most flexible (but slowest) datetime formatter. */ export function formatIntlDateTime(options: formatIntlDateTime.IOptions = {}): FormatFunc { let missing = options.missing || ''; let dtf = new Intl.DateTimeFormat(options.locales, options.options); return ({ value }) => { if (value === null || value === undefined) { return missing; } return dtf.format(value); }; } /** * The namespace for the `formatIntlDateTime` function statics. */ export namespace formatIntlDateTime { /** * The options for creating an intl datetime format function. */ export interface IOptions { /** * The locales to pass to the `Intl.DateTimeFormat` constructor. * * The default is determined by the user agent. */ locales?: string | string[]; /** * The options to pass to the `Intl.DateTimeFormat` constructor. * * The default is determined by the user agent. */ options?: Intl.DateTimeFormatOptions; /** * The text to use for a `null` or `undefined` data value. * * The default is `''`. */ missing?: string; } } /** * Measure the height of a font. * * @param font - The CSS font string of interest. * * @returns The height of the font bounding box. * * #### Notes * This function uses a temporary DOM node to measure the text box * height for the specified font. The first call for a given font * will incur a DOM reflow, but the return value is cached, so any * subsequent call for the same font will return the cached value. */ export function measureFontHeight(font: string): number { // Look up the cached font height. let height = Private.fontHeightCache[font]; // Return the cached font height if it exists. if (height !== undefined) { return height; } // Normalize the font. Private.fontMeasurementGC.font = font; let normFont = Private.fontMeasurementGC.font; // Set the font on the measurement node. Private.fontMeasurementNode.style.font = normFont; // Add the measurement node to the document. document.body.appendChild(Private.fontMeasurementNode); // Measure the node height. height = Private.fontMeasurementNode.offsetHeight; // Remove the measurement node from the document. document.body.removeChild(Private.fontMeasurementNode); // Cache the measured height for the font and norm font. Private.fontHeightCache[font] = height; Private.fontHeightCache[normFont] = height; // Return the measured height. return height; } } /** * The namespace for the module implementation details. */ namespace Private { /** * A cache of measured font heights. */ export const fontHeightCache: { [font: string]: number } = Object.create(null); /** * The DOM node used for font height measurement. */ export const fontMeasurementNode = (() => { let node = document.createElement('div'); node.style.position = 'absolute'; node.style.top = '-99999px'; node.style.left = '-99999px'; node.style.visibility = 'hidden'; node.textContent = 'M'; return node; })(); /** * The GC used for font measurement. */ export const fontMeasurementGC = (() => { let canvas = document.createElement('canvas'); canvas.width = 0; canvas.height = 0; return canvas.getContext('2d')!; })(); }
the_stack
import { IRawThemeSetting } from 'vscode-textmate'; import { Autowired, Injectable } from '@opensumi/di'; import { URI, localize, parseWithComments, ILogger, IReporterService, REPORT_NAME, isString, CharCode, isBoolean, } from '@opensumi/ide-core-browser'; import { IFileServiceClient } from '@opensumi/ide-file-service/lib/common'; import * as monaco from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api'; import { Color } from '../common/color'; import { editorBackground, editorForeground } from '../common/color-tokens/editor'; import { parse as parsePList } from '../common/plistParser'; import { createMatchers, ISemanticTokenRegistry, ITextMateThemingRule, Matcher, MatcherWithPriority, nameMatcher, noMatch, parseClassifierString, ProbeScope, SemanticTokenRule, TextMateThemingRuleDefinitions, TokenStyle, TokenStyleDefinition, TokenStyleDefinitions, TokenStyleValue, } from '../common/semantic-tokens-registry'; import { ITokenThemeRule, IColors, BuiltinTheme, ITokenColorizationRule, IColorMap, getThemeType, IThemeData, ColorScheme, ISemanticTokenColorizationSetting, } from '../common/theme.service'; import { convertSettings } from '../common/themeCompatibility'; function getScopeMatcher(rule: ITextMateThemingRule): Matcher<ProbeScope> { const ruleScope = rule.scope; if (!ruleScope || !rule.settings) { return noMatch; } const matchers: MatcherWithPriority<ProbeScope>[] = []; if (Array.isArray(ruleScope)) { for (const rs of ruleScope) { createMatchers(rs, nameMatcher, matchers); } } else { createMatchers(ruleScope, nameMatcher, matchers); } if (matchers.length === 0) { return noMatch; } return (scope: ProbeScope) => { let max = matchers[0].matcher(scope); for (let i = 1; i < matchers.length; i++) { max = Math.max(max, matchers[i].matcher(scope)); } return max; }; } function isSemanticTokenColorizationSetting(style: any): style is ISemanticTokenColorizationSetting { return ( style && (isString(style.foreground) || isString(style.fontStyle) || isBoolean(style.italic) || isBoolean(style.underline) || isBoolean(style.bold)) ); } @Injectable({ multiple: true }) export class ThemeData implements IThemeData { id: string; name: string; themeSettings: IRawThemeSetting[] = []; colors: IColors = {}; encodedTokensColors: string[] = []; rules: ITokenThemeRule[] = []; base: BuiltinTheme = 'vs-dark'; inherit = false; colorMap: IColorMap = {}; private hasDefaultTokens = false; private customSettings: IRawThemeSetting[] = []; private semanticHighlighting?: boolean; private themeTokenScopeMatchers: Matcher<ProbeScope>[] | undefined; private tokenColorIndex: TokenColorIndex | undefined = undefined; // created on demand private semanticTokenRules: SemanticTokenRule[] = []; @Autowired(IFileServiceClient) private fileServiceClient: IFileServiceClient; @Autowired(ILogger) private readonly logger: ILogger; @Autowired(IReporterService) private reporter: IReporterService; @Autowired(ISemanticTokenRegistry) protected readonly semanticTokenRegistry: ISemanticTokenRegistry; public initializeFromData(data) { this.id = data.id; this.name = data.name; this.colors = data.colors; this.encodedTokensColors = data.encodedTokensColors; this.themeSettings = data.themeSettings; this.rules = data.rules; this.base = data.base; this.inherit = data.inherit; } get type(): ColorScheme { switch (this.base) { case 'vs': return ColorScheme.LIGHT; case 'hc-black': return ColorScheme.HIGH_CONTRAST; default: return ColorScheme.DARK; } } public async initializeThemeData(id: string, name: string, base: string, themeLocation: URI) { this.id = id; this.name = name; this.base = base as BuiltinTheme; await this.loadColorTheme(themeLocation, this.themeSettings, this.colorMap); // eslint-disable-next-line guard-for-in for (const key in this.colorMap) { this.colors[key] = Color.Format.CSS.formatHexA(this.colorMap[key]); } } public loadCustomTokens(customSettings: ITokenColorizationRule[]) { this.rules = []; // const affectedScopes: string[] = customSettings.map((setting) => setting.scope).filter((t) => !!t); this.doInitTokenRules(); for (const setting of customSettings) { this.transform(setting, (rule) => { const existIndex = this.rules.findIndex((item) => item.token === rule.token); if (existIndex > -1) { this.rules.splice(existIndex, 1, rule); } else { this.rules.push(rule); } }); } this.customSettings = customSettings; } public get settings() { return this.themeSettings.concat(this.customSettings); } public get tokenColors(): IRawThemeSetting[] { const result: IRawThemeSetting[] = []; const foreground = this.colorMap[editorForeground]; const background = this.colorMap[editorBackground]; result.push({ settings: { foreground: normalizeColor(foreground), background: normalizeColor(background), }, }); let hasDefaultTokens = false; function addRule(rule: ITextMateThemingRule) { if (rule.scope && rule.settings) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } result.push({ scope: rule.scope, settings: { foreground: normalizeColor(rule.settings.foreground), background: normalizeColor(rule.settings.background), fontStyle: rule.settings.fontStyle, }, }); } } this.settings.map(addRule); if (!hasDefaultTokens) { defaultThemeColors[this.type].forEach(addRule); } return result; } // transform settings & init rules protected doInitTokenRules() { for (const setting of this.themeSettings) { this.transform(setting, (rule) => this.rules.push(rule)); } if (!this.hasDefaultTokens) { defaultThemeColors[getThemeType(this.base)].forEach((setting) => { this.transform(setting, (rule) => this.rules.push(rule)); }); } } private safeParseJSON(content) { let json; try { json = parseWithComments(content); return json; } catch (error) { return this.logger.error('主题文件解析出错!', content); } } private readSemanticTokenRule( selectorString: string, settings: ISemanticTokenColorizationSetting | string | boolean | undefined, ): SemanticTokenRule | undefined { const selector = this.semanticTokenRegistry.parseTokenSelector(selectorString); let style: TokenStyle | undefined; if (typeof settings === 'string') { style = TokenStyle.fromSettings(settings, undefined); } else if (isSemanticTokenColorizationSetting(settings)) { style = TokenStyle.fromSettings( settings.foreground, settings.fontStyle, settings.bold, settings.underline, settings.italic, ); } if (style) { return { selector, style }; } return undefined; } private async loadColorTheme( themeLocation: URI, resultRules: ITokenColorizationRule[], resultColors: IColorMap, ): Promise<any> { const timer = this.reporter.time(REPORT_NAME.THEME_LOAD); const ret = await this.fileServiceClient.resolveContent(themeLocation.toString()); const themeContent = ret.content; timer.timeEnd(themeLocation.toString()); const themeLocationPath = themeLocation.path.toString(); if (/\.json$/.test(themeLocationPath)) { const theme = this.safeParseJSON(themeContent); let includeCompletes: Promise<any> = Promise.resolve(null); if (theme.include) { this.inherit = true; // http 的不作支持 const includePath = themeLocation.path.dir.join(theme.include.replace(/^\.\//, '')); const includeLocation = themeLocation.withPath(includePath); includeCompletes = this.loadColorTheme(includeLocation, resultRules, resultColors); } await includeCompletes; // settings if (Array.isArray(theme.settings)) { convertSettings(theme.settings, resultRules, resultColors); return null; } // semanticHighlighting enable/disabled this.semanticHighlighting = theme.semanticHighlighting; // semanticTokenColors const semanticTokenColors = theme.semanticTokenColors; if (semanticTokenColors && typeof semanticTokenColors === 'object') { // eslint-disable-next-line guard-for-in for (const key in semanticTokenColors) { try { const rule = this.readSemanticTokenRule(key, semanticTokenColors[key]); if (rule) { this.semanticTokenRules.push(rule); } } catch (err) { // ignore error } } } // colors const colors = theme.colors; if (colors) { if (typeof colors !== 'object') { return Promise.reject( new Error( localize( 'error.invalidformat.colors', "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themeLocation.toString(), ), ), ); } // new JSON color themes format // eslint-disable-next-line guard-for-in for (const colorId in colors) { const colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } // tokenColors const tokenColors = theme.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { const tokenPath = themeLocation.path.dir.join(tokenColors.replace(/^\.\//, '')); const tokenLocation = themeLocation.withPath(tokenPath); // tmTheme return this.loadSyntaxTokens(tokenLocation); } else { return Promise.reject( new Error( localize( 'error.invalidformat.tokenColors', "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themeLocation.toString(), ), ), ); } } return null; } else { return this.loadSyntaxTokens(themeLocation); } } private async loadSyntaxTokens(themeLocation: URI): Promise<ITokenColorizationRule[]> { const ret = await this.fileServiceClient.resolveContent(themeLocation.toString()); try { const theme = parsePList(ret.content); const settings = theme.settings; if (!Array.isArray(settings)) { return Promise.reject( new Error( localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."), ), ); } convertSettings(settings, this.themeSettings, this.colorMap); return Promise.resolve(settings); } catch (e) { return Promise.reject(new Error(localize('error.cannotparse', 'Problems parsing tmTheme file: {0}', e.message))); } } // 将 ITokenColorizationRule 转化为 ITokenThemeRule protected transform(tokenColor: ITokenColorizationRule, acceptor: (rule: monaco.editor.ITokenThemeRule) => void) { if (tokenColor.scope && tokenColor.settings && tokenColor.scope === 'token.info-token') { this.hasDefaultTokens = true; } if (typeof tokenColor.scope === 'undefined') { tokenColor.scope = ['']; } else if (typeof tokenColor.scope === 'string') { // tokenColor.scope = tokenColor.scope.split(',').map((scope: string) => scope.trim()); // ? tokenColor.scope = [tokenColor.scope]; } for (const scope of tokenColor.scope) { // Converting numbers into a format that monaco understands const settings = Object.keys(tokenColor.settings).reduce((previous: { [key: string]: string }, current) => { let value: string = tokenColor.settings[current]; if (current !== 'foreground' && current !== 'background' && current !== 'fontStyle') { delete tokenColor.settings[current]; return previous; } if (current !== 'fontStyle' && typeof value === 'string') { if (value.indexOf('#') === -1) { // 兼容 white、red 类型色值 const color = Color[value]; if (color) { value = Color.Format.CSS.formatHex(color); tokenColor.settings[current] = value; } else { // 去掉主题瞎写的值 delete tokenColor.settings[current]; return previous; } } else { const color = Color.fromHex(value); value = Color.Format.CSS.formatHex(color); // 主题只会识别 Hex 的色值 tokenColor.settings[current] = value; } } previous[current] = value; return previous; }, {}); acceptor({ ...settings, token: scope, }); } } public getTokenColorIndex(): TokenColorIndex { // collect all colors that tokens can have if (!this.tokenColorIndex) { const index = new TokenColorIndex(); for (const color of this.encodedTokensColors) { index.add(color); } this.tokenColors.forEach((rule) => { index.add(rule.settings.foreground); index.add(rule.settings.background); }); this.semanticTokenRules.forEach((r) => index.add(r.style.foreground)); this.semanticTokenRegistry.getTokenStylingDefaultRules().forEach((r) => { const defaultColor = r.defaults[this.type]; if (defaultColor && typeof defaultColor === 'object') { index.add(defaultColor.foreground); } }); this.tokenColorIndex = index; } return this.tokenColorIndex; } public getTokenStyle( type: string, modifiers: string[], language: string, useDefault = true, definitions: TokenStyleDefinitions = {}, ): TokenStyle | undefined { const result: any = { foreground: undefined, bold: undefined, underline: undefined, italic: undefined, }; const score = { foreground: -1, bold: -1, underline: -1, italic: -1, }; let hasUndefinedStyleProperty = false; // eslint-disable-next-line guard-for-in for (const k in score) { const key = k as keyof TokenStyle; if (score[key] === -1) { hasUndefinedStyleProperty = true; } else { score[key] = Number.MAX_VALUE; // set it to the max, so it won't be replaced by a default } } function _processStyle(matchScore: number, style: TokenStyle, definition: TokenStyleDefinition) { if (style.foreground && score.foreground <= matchScore) { score.foreground = matchScore; result.foreground = style.foreground; definitions.foreground = definition; } for (const p of ['bold', 'underline', 'italic']) { const property = p as keyof TokenStyle; const info = style[property]; if (info !== undefined) { if (score[property] <= matchScore) { score[property] = matchScore; result[property] = info; definitions[property] = definition; } } } } function _processSemanticTokenRule(rule: SemanticTokenRule) { const matchScore = rule.selector.match(type, modifiers, language); if (matchScore >= 0) { _processStyle(matchScore, rule.style, rule); } } this.semanticTokenRules.forEach(_processSemanticTokenRule); if (hasUndefinedStyleProperty) { for (const rule of this.semanticTokenRegistry.getTokenStylingDefaultRules()) { const matchScore = rule.selector.match(type, modifiers, language); if (matchScore >= 0) { let style: TokenStyle | undefined; if (rule.defaults.scopesToProbe) { style = this.resolveScopes(rule.defaults.scopesToProbe); if (style) { _processStyle(matchScore, style, rule.defaults.scopesToProbe); } } if (!style && useDefault !== false) { const tokenStyleValue = rule.defaults[this.type]; style = this.resolveTokenStyleValue(tokenStyleValue); if (style) { _processStyle(matchScore, style, tokenStyleValue!); } } } } } return TokenStyle.fromData(result); } /** * @param tokenStyleValue Resolve a tokenStyleValue in the context of a theme */ public resolveTokenStyleValue(tokenStyleValue: TokenStyleValue | undefined): TokenStyle | undefined { if (tokenStyleValue === undefined) { return undefined; } else if (typeof tokenStyleValue === 'string') { const { type, modifiers, language } = parseClassifierString(tokenStyleValue, ''); return this.getTokenStyle(type, modifiers, language); } else if (typeof tokenStyleValue === 'object') { return tokenStyleValue; } return undefined; } public resolveScopes(scopes: ProbeScope[], definitions?: TextMateThemingRuleDefinitions): TokenStyle | undefined { if (!this.themeTokenScopeMatchers) { this.themeTokenScopeMatchers = this.themeSettings.map(getScopeMatcher); } for (const scope of scopes) { let foreground: string | undefined; let fontStyle: string | undefined; let foregroundScore = -1; let fontStyleScore = -1; let fontStyleThemingRule: ITextMateThemingRule | undefined; let foregroundThemingRule: ITextMateThemingRule | undefined; function findTokenStyleForScopeInScopes( scopeMatchers: Matcher<ProbeScope>[], themingRules: ITextMateThemingRule[], ) { for (let i = 0; i < scopeMatchers.length; i++) { const score = scopeMatchers[i](scope); if (score >= 0) { const themingRule = themingRules[i]; const settings = themingRules[i].settings; if (score >= foregroundScore && settings.foreground) { foreground = settings.foreground; foregroundScore = score; foregroundThemingRule = themingRule; } if (score >= fontStyleScore && isString(settings.fontStyle)) { fontStyle = settings.fontStyle; fontStyleScore = score; fontStyleThemingRule = themingRule; } } } } findTokenStyleForScopeInScopes(this.themeTokenScopeMatchers, this.themeSettings); if (foreground !== undefined || fontStyle !== undefined) { if (definitions) { definitions.foreground = foregroundThemingRule; definitions.bold = definitions.italic = definitions.underline = fontStyleThemingRule; definitions.scope = scope; } return TokenStyle.fromSettings(foreground, fontStyle); } } return undefined; } } function normalizeColor(color: string | Color | undefined | null): string | undefined { if (!color) { return undefined; } if (typeof color !== 'string') { color = Color.Format.CSS.formatHexA(color, true); } const len = color.length; if (color.charCodeAt(0) !== CharCode.Hash || (len !== 4 && len !== 5 && len !== 7 && len !== 9)) { return undefined; } const result = [CharCode.Hash]; for (let i = 1; i < len; i++) { const upper = hexUpper(color.charCodeAt(i)); if (!upper) { return undefined; } result.push(upper); if (len === 4 || len === 5) { result.push(upper); } } if (result.length === 9 && result[7] === CharCode.F && result[8] === CharCode.F) { result.length = 7; } return String.fromCharCode(...result); } function hexUpper(charCode: CharCode): number { if ( (charCode >= CharCode.Digit0 && charCode <= CharCode.Digit9) || (charCode >= CharCode.A && charCode <= CharCode.F) ) { return charCode; } else if (charCode >= CharCode.a && charCode <= CharCode.f) { return charCode - CharCode.a + CharCode.A; } return 0; } class TokenColorIndex { private _lastColorId: number; private _id2color: string[]; private _color2id: { [color: string]: number }; constructor() { this._lastColorId = 0; this._id2color = []; this._color2id = Object.create(null); } public add(color: string | Color | undefined): number { color = normalizeColor(color); if (color === undefined) { return 0; } let value = this._color2id[color]; if (value) { return value; } value = ++this._lastColorId; this._color2id[color] = value; this._id2color[value] = color; return value; } public get(color: string | Color | undefined): number { color = normalizeColor(color); if (color === undefined) { return 0; } const value = this._color2id[color]; if (value) { return value; } return 0; } public asArray(): string[] { return this._id2color.slice(0); } } const defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { light: [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } }, ], dark: [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } }, ], hc: [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } }, ], };
the_stack
import { ExpressionValueType } from "@abstractions/z80-compiler-service"; import { CompareBinPragma, Expression, IdentifierNode, NodePosition, Statement, Z80AssemblyLine, } from "./assembler-tree-nodes"; import { ErrorCodes } from "./assembler-errors"; /** * Represents the value of an evaluated expression */ export interface IExpressionValue { /** * Gets the type of the expression */ readonly type: ExpressionValueType; /** * Checks if the value of this expression is valid */ readonly isValid: boolean; /** * Checks if the value of this expression is not evaluated */ readonly isNonEvaluated: boolean; /** * Gets the value of this instance */ readonly value: number; /** * Returns the value as a long integer */ asLong(): number; /** * Returns the value as a real number */ asReal(): number; /** * Returns the value as a string */ asString(): string; /** * Returns the value as a Boolean */ asBool(): boolean; /** * Returns the value as a 16-bit unsigned integer */ asWord(): number; /** * Returns the value as an 8-bit unsigned integer */ asByte(): number; } /** * Map of symbols */ export type SymbolValueMap = Record<string, IExpressionValue>; /** * Objects implementing this interface have usage information */ export interface IHasUsageInfo { /** * Signs if the object has been used */ isUsed: boolean; } /** * Information about a symbol's value */ export interface IValueInfo { /** * The value of the symbol */ value: IExpressionValue; /** * Symbol usage information */ usageInfo: IHasUsageInfo; } /** * Represents the context in which an expression is evaluated */ export interface IEvaluationContext { /** * Gets the source line the evaluation context is bound to */ getSourceLine(): Z80AssemblyLine; /** * Sets the source line the evaluation context is bound to * @param sourceLine Source line information */ setSourceLine(sourceLine: Z80AssemblyLine): void; /** * Gets the current assembly address */ getCurrentAddress(): number; /** * Gets the value of the specified symbol * @param symbol Symbol name * @param startFromGlobal Should resolution start from global scope? */ getSymbolValue(symbol: string, startFromGlobal?: boolean): IValueInfo | null; /** * Gets the current loop counter value */ getLoopCounterValue(): IExpressionValue; /** * Evaluates the value if the specified expression node * @param expr Expression to evaluate * @param context: Evaluation context */ doEvalExpression(expr: Expression): IExpressionValue; /** * Reports an error during evaluation * @param code Error code * @param node Error position * @param parameters Optional error parameters */ reportEvaluationError( code: ErrorCodes, node: NodePosition, ...parameters: any[] ): void; } /** * A single segment of the code compilation */ export interface IBinarySegment { /** * The bank of the segment */ bank?: number; /** * Start offset used for banks */ bankOffset: number; /** * Maximum code length of this segment */ maxCodeLength: number; /** * Start address of the compiled block */ startAddress: number; /** * Optional displacement of this segment */ displacement?: number; /** * The current assembly address when the .disp pragma was used */ dispPragmaOffset?: number; /** * Intel hex start address of this segment */ xorgValue?: number; /** * Emitted Z80 binary code */ emittedCode: number[]; /** * Signs if segment overflow has been detected */ overflowDetected: boolean; /** * Shows the offset of the instruction being compiled */ currentInstructionOffset?: number; /** * The current code generation offset */ readonly currentOffset: number; /** * Emits the specified byte to the segment * @param data Byte to emit * @returns Null, if byte emitted; otherwise, error message */ emitByte(data: number): ErrorCodes | null; } /** * Describes a source file item */ export interface ISourceFileItem { /** * The name of the source file */ readonly filename: string; /** * Optional parent item */ parent?: ISourceFileItem; /** * Included files */ readonly includes: ISourceFileItem[]; /** * Adds the specified item to the "includes" list * @param childItem Included source file item * @returns True, if including the child item is OK; * False, if the inclusion would create a circular reference, * or the child is already is in the list */ include(childItem: ISourceFileItem): boolean; /** * Checks if this item already contains the specified child item in * its "includes" list * @param childItem Child item to check * @returns True, if this item contains the child item; otherwise, false */ containsInIncludeList(childItem: ISourceFileItem): boolean; } /** * Represents a file line in the compiled assembler output */ export interface IFileLine { fileIndex: number; line: number; } /** * This type represents a source map */ export type SourceMap = Record<number, IFileLine>; /** * Represents a compilation error */ export interface IAssemblerErrorInfo { readonly errorCode: ErrorCodes; readonly fileName: string; readonly line: number; readonly startPosition: number; readonly endPosition: number | null; readonly message: string; readonly isWarning?: boolean; } /** * Represents an item in the output list */ export interface IListFileItem { fileIndex: number; address: number; segmentIndex: number; codeStartIndex: number; codeLength: number; lineNumber: number; sourceText: string; } /** * This enum defines the types of assembly symbols */ export enum SymbolType { None, Label, Var, } /** * This class represents an assembly symbol */ export interface IAssemblySymbolInfo extends IHasUsageInfo { readonly name: string; readonly type: SymbolType; value: IExpressionValue; /** * Tests if this symbol is a local symbol within a module. */ readonly isModuleLocal: boolean; /** * Tests if this symbol is a short-term symbol. */ readonly isShortTerm: boolean; /** * Signs if the object has been used */ isUsed: boolean; } /** * Type of the fixup */ export enum FixupType { Jr, Bit8, Bit16, Bit16Be, Equ, Ent, Xent, Struct, FieldBit8, FieldBit16, } /** * Defines a section of assembly lines */ export type DefinitionSection = { readonly firstLine: number; readonly lastLine: number; }; /** * Represents the definition of a macro */ export interface IMacroDefinition { readonly macroName: string; readonly argNames: IdentifierNode[]; readonly endLabel: string | null; readonly section: DefinitionSection; } /** * Defines a field of a structure */ export interface IFieldDefinition extends IHasUsageInfo { readonly offset: number; isUsed: boolean; } /** * Represents a struct */ export interface IStructDefinition { readonly structName: string; /** * Struct definition section */ readonly section: DefinitionSection; /** * The fields of the structure */ readonly fields: Record<string, IFieldDefinition>; /** * The size of the structure */ size: number; /** * Adds a new field to the structure * @param fieldName Field name * @param definition Field definition */ addField(fieldName: string, definition: IFieldDefinition): void; /** * Tests if the structure contains a field * @param fieldName Name of the field to check * @returns True, if the struct contains the field; otherwise, false. */ containsField(fieldName: string): boolean; /** * Gets the specified field definition * @param name field name * @returns The field information, if found; otherwise, undefined. */ getField(fieldName: string): IFieldDefinition | undefined; } /** * Represents the definition of an IF statement */ export class IfDefinition { /** * The entire if section */ fullSection: DefinitionSection; /** * List of IF sections */ ifSections: IfSection[] = []; /** * Optional ELSE section */ elseSection?: IfSection; } /** * Represents a section of an IF definition */ export class IfSection { constructor( public readonly ifStatement: Statement, firstLine: number, lastLine: number ) { this.section = { firstLine, lastLine }; } /** * Section boundaries */ section: DefinitionSection; } /** * Represents a struct */ export class StructDefinition implements IStructDefinition { constructor( public readonly structName: string, macroDefLine: number, macroEndLine: number, private caseSensitive: boolean ) { this.section = { firstLine: macroDefLine, lastLine: macroEndLine }; } /** * Struct definition section */ readonly section: DefinitionSection; /** * The fields of the structure */ readonly fields: { [key: string]: IFieldDefinition } = {}; /** * The size of the structure */ size: number; /** * Adds a new field to the structure * @param fieldName Field name * @param definition Field definition */ addField(fieldName: string, definition: IFieldDefinition): void { if (!this.caseSensitive) { fieldName = fieldName.toLowerCase(); } this.fields[fieldName] = definition; } /** * Tests if the structure contains a field * @param fieldName Name of the field to check * @returns True, if the struct contains the field; otherwise, false. */ containsField(fieldName: string): boolean { if (!this.caseSensitive) { fieldName = fieldName.toLowerCase(); } return !!this.fields[fieldName]; } /** * Gets the specified field definition * @param name field name * @returns The field information, if found; otherwise, undefined. */ getField(fieldName: string): IFieldDefinition | undefined { if (!this.caseSensitive) { fieldName = fieldName.toLowerCase(); } return this.fields[fieldName]; } } /** * Information about binary comparison */ export class BinaryComparisonInfo { constructor( public readonly comparePragma: CompareBinPragma, public readonly segment: IBinarySegment, public readonly segmentLength: number ) {} }
the_stack
import { AfterViewInit, Component, DoCheck, EventEmitter, Input, OnInit, Output, TemplateRef, ViewChild, ViewEncapsulation } from '@angular/core'; import { DragulaService } from 'ng2-dragula'; import { DatatableComponent } from '@swimlane/ngx-datatable'; import { NgxDataTableConfig } from './ngx-datatable-config'; import { SortEvent } from '../../sort/sort-event'; import { TableConfig } from './table-config'; import { TableBase } from '../table-base'; import { TableEvent } from '../table-event'; import { clone, cloneDeep, defaults, isEqual } from 'lodash'; /** * Table component. * * In order to use drag and drop, please include the following CSS file from ng2-dragula. For example: * <code>import 'dragula/dist/dragula.css';</code> * * For ngx-datatable options, see: https://swimlane.gitbooks.io/ngx-datatable/ * * Note: The underlying ngx-datatable uses ContentChildren to retrieve DataTableColumnDirective (ngx-datatable-column) * tags. As a result of wrapping ngx-datatable, these objects are no longer direct descendents and ContentChildren * cannot retrieve them. A fix to ContentChildren may be in the works... * * Instead of using ngx-datatable-column, table cells may be defined using templates, provided as the * columns cellTemplate property. For example: * * <code> * this.columns = [{ * cellTemplate: this.nameTemplate, * prop: 'name', * name: 'Name' * }] * </code> * * and * * <code> * &lt;ng-template #nameTemplate let-row="row"&gt; * &lt;span>{{row.name}}&lt;/span&gt; * &lt;/ng-template&gt; * </code> * * Usage: * <code><pre> * // Individual module import * import { TableModule } from 'patternfly-ng/table'; * // Or * import { TableModule } from 'patternfly-ng'; * * // NGX Bootstrap * import { BsDropdownConfig, BsDropdownModule } from 'ngx-bootstrap/dropdown'; * // NGX Datatable * import { NgxDatatableModule } from '@swimlane/ngx-datatable'; * * &#64;NgModule({ * imports: [BsDropdownModule.forRoot(), NgxDatatableModule, TableModule,...], * providers: [BsDropdownConfig] * }) * export class AppModule(){} * </pre></code> * * Optional: * <code><pre> * import { NgxDataTableConfig, TableConfig, TableEvent } from 'patternfly-ng/table'; * </pre></code> */ @Component({ encapsulation: ViewEncapsulation.None, selector: 'pfng-table', templateUrl: './table.component.html' }) export class TableComponent extends TableBase implements AfterViewInit, DoCheck, OnInit { /** * An array of items to display for table columns */ @Input() columns: any[]; /** * The table config containing component properties */ @Input() config: TableConfig; /** * The ngx-datatable config containing component properties */ @Input() dataTableConfig: NgxDataTableConfig; /** * The name of the template used with expanding rows */ @Input() expandRowTemplate: TemplateRef<any>; /** * The name of the template used with group headers */ @Input() groupHeaderTemplate: TemplateRef<any>; /** * The ngx-datatable event emitted when a cell or row was focused via keyboard or mouse click */ @Input() rows: any[]; /** * The ngx-datatable event emitted when a cell or row was focused via keyboard or mouse click */ @Output('onActivate') onActivate = new EventEmitter(); /** * The ngx-datatable event emitted when a row detail row was toggled * * Not applicable with pfng-table useExpandRows */ @Output('onDetailToggle') onDetailToggle = new EventEmitter(); /** * The ngx-datatable event emitted when a row detail row was toggled * * Not applicable with pfng-table paginationConfig */ @Output('onPage') onPage = new EventEmitter(); /** * The ngx-datatable event emitted when columns are re-ordered */ @Output('onReorder') onReorder = new EventEmitter(); /** * The ngx-datatable event emitted when a column is resized */ @Output('onResize') onResize = new EventEmitter(); /** * The ngx-datatable event emitted when a cell or row was selected * * Not applicable with pfng-table showCheckbox */ @Output('onSelect') onSelect = new EventEmitter(); /** * The ngx-datatable event emitted when body was scrolled (e.g., when scrollbarV is true) */ @Output('onScroll') onScroll = new EventEmitter(); /** * The ngx-datatable event emitted when a column header is sorted */ @Output('onSort') onSort = new EventEmitter(); /** * The ngx-datatable event emitted when a context menu is invoked on the table */ @Output('onTableContextMenu') onTableContextMenu = new EventEmitter(); /** * The event emitted when a row has been dragged */ // @Output('onDrag') onDrag = new EventEmitter(); /** * The event emitted when a row has been dropped */ @Output('onDrop') onDrop = new EventEmitter(); @ViewChild('datatable') private _datatable: DatatableComponent; @ViewChild('selectCellTemplate') private selectCellTemplate: TemplateRef<any>; @ViewChild('selectHeadTemplate') private selectHeadTemplate: TemplateRef<any>; private _allRowsSelected: boolean = false; private _cols: any[]; private _selectedRows: any[]; private _showTable: boolean = true; private defaultConfig = { dragEnabled: false, hideClose: false, showCheckbox: false, styleClass: 'patternfly', useExpandRows: false } as TableConfig; private defaultDataTableConfig = { columnMode: 'force', cssClasses: { sortAscending: 'datatable-icon-up', sortDescending: 'datatable-icon-down', pagerLeftArrow: 'datatable-icon-left', pagerRightArrow: 'datatable-icon-right', pagerPrevious: 'datatable-icon-prev', pagerNext: 'datatable-icon-skip' }, externalPaging: false, externalSorting: false, headerHeight: 50, messages: { emptyMessage: 'No records found' }, offset: 0, reorderable: true, rowHeight: 'auto', rowIdentity: ((x: any) => x), scrollbarH: false, scrollbarV: false, sorts: [], sortType: 'multi' } as NgxDataTableConfig; private dragulaName = 'newBag'; private prevConfig: TableConfig; private prevDataTableConfig: NgxDataTableConfig; private prevRows: any[]; private rowsModel: any[]; /** * The default constructor */ constructor(private dragulaService: DragulaService) { super(); } // Initialization /** * Setup component configuration upon view initialization */ ngAfterViewInit(): void { // Reinitialize to include selection column cell/header templates this.setupSelectionCols(); } /** * Setup component configuration upon initialization */ ngOnInit(): void { this.setupConfig(); this.setupSelectionCols(); // Initialize here for selection column width this.setupDataTableConfig(); } /** * Check if the component config has changed */ ngDoCheck(): void { // Do a deep compare on config if (!isEqual(this.config, this.prevConfig)) { // Skip pagination and toolbar changes if (!(this.hasPaginationChanged() || this.hasToolbarChanged())) { this.setupSelectionCols(); } this.setupConfig(); } if (!isEqual(this.dataTableConfig, this.prevDataTableConfig)) { this.setupDataTableConfig(); } if (!isEqual(this.rows, this.prevRows)) { this.rowsModel = [...this.rows]; this.initSelectedRows(); this.initAllRowsSelected(); // Disable toolbar actions if (this.config.toolbarConfig !== undefined) { this.config.toolbarConfig.disabled = !this.hasData; } // ngx-datatable recommends you force change detection -- issue #337 if (this.prevRows === undefined || this.prevRows.length === 0) { setTimeout(() => { this.setupSelectionCols(); }, 10); } this.prevRows = clone(this.rows); // lodash has issues deep cloning templates } } /** * Set up default config */ protected setupConfig(): void { if (this.config !== undefined) { defaults(this.config, this.defaultConfig); } else { this.config = cloneDeep(this.defaultConfig); } // Disable toolbar actions if (this.config.toolbarConfig !== undefined && !this.hasData) { this.showTable = false; // Filter and sort don't fully disable without this timeout setTimeout(() => { this.config.toolbarConfig.disabled = !this.hasData; this.showTable = true; }, 10); } this.prevConfig = cloneDeep(this.config); } /** * Set up default ngx-datatable config */ protected setupDataTableConfig(): void { if (this.dataTableConfig !== undefined) { defaults(this.dataTableConfig, this.defaultDataTableConfig); } else { this.dataTableConfig = cloneDeep(this.defaultDataTableConfig); } this.prevDataTableConfig = cloneDeep(this.dataTableConfig); } /** * Set up selection columns */ protected setupSelectionCols(): void { let cellClass = ''; if (this.config.dragEnabled === true && (this.config.useExpandRows !== true && this.config.showCheckbox !== true)) { cellClass = 'pfng-table-dnd-only'; } // ngx-datatable requires width property to become visible let width = 0; if (this.config.showCheckbox === true && this.config.useExpandRows === true && this.config.dragEnabled === true) { width = 57; } else if (this.config.showCheckbox === true && this.config.useExpandRows === true) { width = 52; } else if (this.config.showCheckbox === true && this.config.dragEnabled === true) { width = 36; } else if (this.config.useExpandRows === true && this.config.dragEnabled === true) { width = 32; } else if (this.config.showCheckbox === true) { width = 34; } else if (this.config.useExpandRows === true) { width = 30; } else if (this.config.dragEnabled === true) { width = 10; } this._cols = []; if (width > 0) { this._cols.push({ canAutoResize: false, cellClass: 'pfng-table-select ' + cellClass, cellTemplate: this.selectCellTemplate, headerClass: 'pfng-table-select ' + cellClass, headerTemplate: this.selectHeadTemplate, resizeable: false, sortable: false, width: width }); } this.columns.forEach((col) => { this._cols.push(col); }); } // Accessors /** * Returns a flag indicating whether all visible rows are selected * * @returns {boolean} True if all visible rows are selected */ get allRowsSelected(): boolean { return (this.rows !== undefined && this.rows.length > 0) ? this._allRowsSelected : false; } /** * Sets a flag indicating whether all visible rows are selected * * @param {boolean} selected True if all visible rows are selected */ set allRowsSelected(selected: boolean) { this._allRowsSelected = selected; if (this.rows !== undefined) { for (let i = 0; i < this.rows.length; i++) { this.rows[i].selected = (selected === true) ? true : false; } } } /** * Returns the columns used by the ngx-datatable component * * @returns {any[]} The ngx-datatable columns */ protected get cols(): any[] { return this._cols; } /** * Returns the underlying ngx-datatable component * * @returns {DatatableComponent} */ get datatable(): DatatableComponent { return this._datatable; } /** * Get the flag indicating table has data, including filtered rows * * @returns {boolean} True is the table has data */ get hasData(): boolean { let hasRows = (this.rows !== undefined && this.rows.length > 0); let hasFilter = false; if (this.config.appliedFilters !== undefined) { hasFilter = (this.config.appliedFilters.length > 0); } else if (this.config.toolbarConfig !== undefined && this.config.toolbarConfig.filterConfig !== undefined && this.config.toolbarConfig.filterConfig.appliedFilters !== undefined) { hasFilter = (this.config.toolbarConfig.filterConfig.appliedFilters.length > 0); } return hasRows || hasFilter; } /** * Returns the currently selected rows * * @returns {any[]} The selected rows */ get selectedRows(): any[] { return (this.dataTableConfig.selected !== undefined && this.config.showCheckbox !== true) ? this.dataTableConfig.selected : this._selectedRows; } /** * Sets the currently selected rows * * @param {any[]} selectedRows The selected rows */ set selectedRows(selectedRows: any[]) { if (selectedRows !== undefined) { this._selectedRows = selectedRows; if (this.config.toolbarConfig !== undefined && this.config.toolbarConfig.filterConfig !== undefined) { this.config.toolbarConfig.filterConfig.selectedCount = this._selectedRows.length; } } } /** * Returns flag indicating table is visible * * @returns {boolean} True if table is visible */ protected get showTable(): boolean { return this._showTable; } /** * Set the flag indicating table is visible * * @param {boolean} visible True if table is visible */ protected set showTable(visible: boolean) { this._showTable = visible; } // Private /** * Helper to generate ngx-datatable activate event */ private handleActivate($event: any): void { this.onActivate.emit($event); } /** * Helper to generate ngx-datatable detailToggle event */ private handleDetailToggle($event: any): void { this.onDetailToggle.emit($event); } // Todo: Not implemented yet private handleDragulaDrag($event: any[]): void { // this.onDrag.emit($event); } /** * Helper to generate dragula drop event * * @param {any[]} $event */ private handleDragulaDrop($event: any[]): void { // ngx-datatable recommends you force change detection this.showTable = false; this.rows = [...$event]; setTimeout(() => { this.onDrop.emit($event); this.rowsModel = [...this.rows]; this.showTable = true; }, 10); } /** * Helper to generate ngx-datatable page event */ private handlePage($event: any): void { this.onPage.emit($event); } /** * Helper to generate ngx-datatable reorder event */ private handleReorder($event: any): void { this.onReorder.emit($event); // Save new order for drag and drop changes let newCols = this.cols.slice(); newCols.splice($event.prevValue, 1); newCols.splice($event.newValue, 0, $event.column); this._cols = newCols; } /** * Helper to generate ngx-datatable resize event */ private handleResize($event: any): void { this.onResize.emit($event); } /** * Helper to generate ngx-datatable scroll event */ private handleScroll($event: any): void { this.onScroll.emit($event); } /** * Helper to generate ngx-datatable select event */ private handleSelect($event: any): void { this.onSelect.emit($event); } /** * Helper to generate ngx-datatable sort event */ private handleSort($event: any): void { this.onSort.emit($event); } /** * Helper to generate ngx-datatable tableContextmenu event */ private handleTableContextMenu($event: any): void { this.onTableContextMenu.emit($event); } /** * Helper to test if pagination config has changed * * @returns {boolean} True if pagination config has changed */ private hasPaginationChanged(): boolean { let change = (this.config.paginationConfig !== undefined && this.prevConfig.paginationConfig !== undefined && !isEqual(this.config.paginationConfig, this.prevConfig.paginationConfig)); return change; } /** * Helper to test if toolbar config has changed * * @returns {boolean} True if toolbar config has changed */ private hasToolbarChanged(): boolean { let change = (this.config.toolbarConfig !== undefined && this.prevConfig.toolbarConfig !== undefined && !isEqual(this.config.toolbarConfig, this.prevConfig.toolbarConfig)); return change; } /** * Helper to initialize de/select all control */ private initAllRowsSelected(): void { this._allRowsSelected = (this.selectedRows !== undefined && this.selectedRows.length === this.rows.length); } /** * Helper to initialize selected rows */ private initSelectedRows(): void { let selected = []; if (this.rows !== undefined) { for (let i = 0; i < this.rows.length; i++) { if (this.rows[i].selected) { selected.push(this.rows[i]); } } } this.selectedRows = selected; } /** * Helper to generate selection change event * * @param row The selected row */ private selectionChange(row: any): void { this.initSelectedRows(); this.initAllRowsSelected(); this.onSelectionChange.emit({ row: row, selectedRows: this.selectedRows } as TableEvent); } /** * Helper to generate selection change event when all rows are selected */ private selectionsChange(): void { this.selectedRows = (this.allRowsSelected === true) ? this.rows : []; this.onSelectionChange.emit({ selectedRows: this.selectedRows } as TableEvent); } /** * Helper to expand group * * @param group The group to expand */ private toggleExpandGroup(group: any): void { this.datatable.groupHeader.toggleExpandGroup(group); } /** * Helper to expand row * * @param row The row to expand */ private toggleExpandRow(row: any): void { if (this.datatable.rowDetail !== undefined) { this.datatable.rowDetail.toggleExpandRow(row); } } }
the_stack
import * as ts from "typescript"; import * as fs from "fs"; import * as path from "path"; import { unexpectedValue } from "../utils/unexpectedValue"; import * as codeUtils from "../utils/codeUtils"; import {CommentsParser} from '../utils/commentsParser'; export class LegacyPolymerComponentParser { public constructor(private readonly rootDir: string, private readonly htmlFiles: Set<string>) { } public async parse(jsFile: string): Promise<ParsedPolymerComponent | null> { const sourceFile: ts.SourceFile = this.parseJsFile(jsFile); const legacyComponent = this.tryParseLegacyComponent(sourceFile); if (legacyComponent) { return legacyComponent; } return null; } private parseJsFile(jsFile: string): ts.SourceFile { return ts.createSourceFile(jsFile, fs.readFileSync(path.resolve(this.rootDir, jsFile)).toString(), ts.ScriptTarget.ES2015, true); } private tryParseLegacyComponent(sourceFile: ts.SourceFile): ParsedPolymerComponent | null { const polymerFuncCalls: ts.CallExpression[] = []; function addPolymerFuncCall(node: ts.Node) { if(node.kind === ts.SyntaxKind.CallExpression) { const callExpression: ts.CallExpression = node as ts.CallExpression; if(callExpression.expression.kind === ts.SyntaxKind.Identifier) { const identifier = callExpression.expression as ts.Identifier; if(identifier.text === "Polymer") { polymerFuncCalls.push(callExpression); } } } ts.forEachChild(node, addPolymerFuncCall); } addPolymerFuncCall(sourceFile); if (polymerFuncCalls.length === 0) { return null; } if (polymerFuncCalls.length > 1) { throw new Error("Each .js file must contain only one Polymer component"); } const parsedPath = path.parse(sourceFile.fileName); const htmlFullPath = path.format({ dir: parsedPath.dir, name: parsedPath.name, ext: ".html" }); if (!this.htmlFiles.has(htmlFullPath)) { throw new Error("Legacy .js component dosn't have associated .html file"); } const polymerFuncCall = polymerFuncCalls[0]; if(polymerFuncCall.arguments.length !== 1) { throw new Error("The Polymer function must be called with exactly one parameter"); } const argument = polymerFuncCall.arguments[0]; if(argument.kind !== ts.SyntaxKind.ObjectLiteralExpression) { throw new Error("The parameter for Polymer function must be ObjectLiteralExpression (i.e. '{...}')"); } const infoArg = argument as ts.ObjectLiteralExpression; return { jsFile: sourceFile.fileName, htmlFile: htmlFullPath, parsedFile: sourceFile, polymerFuncCallExpr: polymerFuncCalls[0], componentSettings: this.parseLegacyComponentSettings(infoArg), }; } private parseLegacyComponentSettings(info: ts.ObjectLiteralExpression): LegacyPolymerComponentSettings { const props: Map<string, ts.ObjectLiteralElementLike> = new Map(); for(const property of info.properties) { const name = property.name; if (name === undefined) { throw new Error("Property name is not defined"); } switch(name.kind) { case ts.SyntaxKind.Identifier: case ts.SyntaxKind.StringLiteral: if (props.has(name.text)) { throw new Error(`Property ${name.text} appears more than once`); } props.set(name.text, property); break; case ts.SyntaxKind.ComputedPropertyName: continue; default: unexpectedValue(ts.SyntaxKind[name.kind]); } } if(props.has("_noAccessors")) { throw new Error("_noAccessors is not supported"); } const legacyLifecycleMethods: LegacyLifecycleMethods = new Map(); for(const name of LegacyLifecycleMethodsArray) { const methodDecl = this.getLegacyMethodDeclaration(props, name); if(methodDecl) { legacyLifecycleMethods.set(name, methodDecl); } } const ordinaryMethods: OrdinaryMethods = new Map(); const ordinaryShorthandProperties: OrdinaryShorthandProperties = new Map(); const ordinaryGetAccessors: OrdinaryGetAccessors = new Map(); const ordinaryPropertyAssignments: OrdinaryPropertyAssignments = new Map(); for(const [name, val] of props) { if(RESERVED_NAMES.hasOwnProperty(name)) continue; switch(val.kind) { case ts.SyntaxKind.MethodDeclaration: ordinaryMethods.set(name, val as ts.MethodDeclaration); break; case ts.SyntaxKind.ShorthandPropertyAssignment: ordinaryShorthandProperties.set(name, val as ts.ShorthandPropertyAssignment); break; case ts.SyntaxKind.GetAccessor: ordinaryGetAccessors.set(name, val as ts.GetAccessorDeclaration); break; case ts.SyntaxKind.PropertyAssignment: ordinaryPropertyAssignments.set(name, val as ts.PropertyAssignment); break; default: throw new Error(`Unsupported element kind: ${ts.SyntaxKind[val.kind]}`); } //ordinaryMethods.set(name, tsUtils.assertNodeKind(val, ts.SyntaxKind.MethodDeclaration) as ts.MethodDeclaration); } const eventsComments: string[] = this.getEventsComments(info.getFullText()); return { reservedDeclarations: { is: this.getStringLiteralValueWithComments(this.getLegacyPropertyInitializer(props, "is")), _legacyUndefinedCheck: this.getBooleanLiteralValueWithComments(this.getLegacyPropertyInitializer(props, "_legacyUndefinedCheck")), properties: this.getObjectLiteralExpressionWithComments(this.getLegacyPropertyInitializer(props, "properties")), behaviors: this.getArrayLiteralExpressionWithComments(this.getLegacyPropertyInitializer(props, "behaviors")), observers: this.getArrayLiteralExpressionWithComments(this.getLegacyPropertyInitializer(props, "observers")), listeners: this.getObjectLiteralExpressionWithComments(this.getLegacyPropertyInitializer(props, "listeners")), hostAttributes: this.getObjectLiteralExpressionWithComments(this.getLegacyPropertyInitializer(props, "hostAttributes")), keyBindings: this.getObjectLiteralExpressionWithComments(this.getLegacyPropertyInitializer(props, "keyBindings")), }, eventsComments: eventsComments, lifecycleMethods: legacyLifecycleMethods, ordinaryMethods: ordinaryMethods, ordinaryShorthandProperties: ordinaryShorthandProperties, ordinaryGetAccessors: ordinaryGetAccessors, ordinaryPropertyAssignments: ordinaryPropertyAssignments, }; } private convertLegacyProeprtyInitializer<T>(initializer: LegacyPropertyInitializer | undefined, converter: (exp: ts.Expression) => T): DataWithComments<T> | undefined { if(!initializer) { return undefined; } return { data: converter(initializer.data), leadingComments: initializer.leadingComments, } } private getObjectLiteralExpressionWithComments(initializer: LegacyPropertyInitializer | undefined): DataWithComments<ts.ObjectLiteralExpression> | undefined { return this.convertLegacyProeprtyInitializer(initializer, expr => codeUtils.getObjectLiteralExpression(expr)); } private getStringLiteralValueWithComments(initializer: LegacyPropertyInitializer | undefined): DataWithComments<string> | undefined { return this.convertLegacyProeprtyInitializer(initializer, expr => codeUtils.getStringLiteralValue(expr)); } private getBooleanLiteralValueWithComments(initializer: LegacyPropertyInitializer | undefined): DataWithComments<boolean> | undefined { return this.convertLegacyProeprtyInitializer(initializer, expr => codeUtils.getBooleanLiteralValue(expr)); } private getArrayLiteralExpressionWithComments(initializer: LegacyPropertyInitializer | undefined): DataWithComments<ts.ArrayLiteralExpression> | undefined { return this.convertLegacyProeprtyInitializer(initializer, expr => codeUtils.getArrayLiteralExpression(expr)); } private getLegacyPropertyInitializer(props: Map<String, ts.ObjectLiteralElementLike>, propName: string): LegacyPropertyInitializer | undefined { const property = props.get(propName); if (!property) { return undefined; } const assignment = codeUtils.getPropertyAssignment(property); if (!assignment) { return undefined; } const comments: string[] = codeUtils.getLeadingComments(property) .filter(c => !this.isEventComment(c)); return { data: assignment.initializer, leadingComments: comments, }; } private isEventComment(comment: string): boolean { return comment.indexOf('@event') >= 0; } private getEventsComments(polymerComponentSource: string): string[] { return CommentsParser.collectAllComments(polymerComponentSource) .filter(c => this.isEventComment(c)); } private getLegacyMethodDeclaration(props: Map<String, ts.ObjectLiteralElementLike>, propName: string): ts.MethodDeclaration | undefined { const property = props.get(propName); if (!property) { return undefined; } return codeUtils.assertNodeKind(property, ts.SyntaxKind.MethodDeclaration) as ts.MethodDeclaration; } } export type ParsedPolymerComponent = LegacyPolymerComponent; export interface LegacyPolymerComponent { jsFile: string; htmlFile: string; parsedFile: ts.SourceFile; polymerFuncCallExpr: ts.CallExpression; componentSettings: LegacyPolymerComponentSettings; } export interface LegacyReservedDeclarations { is?: DataWithComments<string>; _legacyUndefinedCheck?: DataWithComments<boolean>; properties?: DataWithComments<ts.ObjectLiteralExpression>; behaviors?: DataWithComments<ts.ArrayLiteralExpression>, observers? :DataWithComments<ts.ArrayLiteralExpression>, listeners? :DataWithComments<ts.ObjectLiteralExpression>, hostAttributes?: DataWithComments<ts.ObjectLiteralExpression>, keyBindings?: DataWithComments<ts.ObjectLiteralExpression>, } export const LegacyLifecycleMethodsArray = <const>["beforeRegister", "registered", "created", "ready", "attached" , "detached", "attributeChanged"]; export type LegacyLifecycleMethodName = typeof LegacyLifecycleMethodsArray[number]; export type LegacyLifecycleMethods = Map<LegacyLifecycleMethodName, ts.MethodDeclaration>; export type OrdinaryMethods = Map<string, ts.MethodDeclaration>; export type OrdinaryShorthandProperties = Map<string, ts.ShorthandPropertyAssignment>; export type OrdinaryGetAccessors = Map<string, ts.GetAccessorDeclaration>; export type OrdinaryPropertyAssignments = Map<string, ts.PropertyAssignment>; export type ReservedName = LegacyLifecycleMethodName | keyof LegacyReservedDeclarations; export const RESERVED_NAMES: {[x in ReservedName]: boolean} = { attached: true, detached: true, ready: true, created: true, beforeRegister: true, registered: true, attributeChanged: true, is: true, _legacyUndefinedCheck: true, properties: true, behaviors: true, observers: true, listeners: true, hostAttributes: true, keyBindings: true, }; export interface LegacyPolymerComponentSettings { reservedDeclarations: LegacyReservedDeclarations; lifecycleMethods: LegacyLifecycleMethods, ordinaryMethods: OrdinaryMethods, ordinaryShorthandProperties: OrdinaryShorthandProperties, ordinaryGetAccessors: OrdinaryGetAccessors, ordinaryPropertyAssignments: OrdinaryPropertyAssignments, eventsComments: string[]; } export interface DataWithComments<T> { data: T; leadingComments: string[]; } type LegacyPropertyInitializer = DataWithComments<ts.Expression>;
the_stack
import _ = require('lodash'); import { Duplex } from 'stream'; import DuplexPair = require('native-duplexpair'); import { TypedError } from 'typed-error'; import * as CrossFetch from 'cross-fetch'; import * as WebSocket from 'isomorphic-ws'; import connectWebSocketStream = require('@httptoolkit/websocket-stream'); import { SubscriptionClient } from '@httptoolkit/subscriptions-transport-ws'; import { print } from 'graphql'; import { DEFAULT_ADMIN_SERVER_PORT } from "../types"; import { MaybePromise, RequireProps } from '../util/type-utils'; import { isNode } from '../util/util'; import { isErrorLike } from '../util/error'; import { getDeferred } from '../util/promise'; import { introspectionQuery } from './schema-introspection'; import { MockttpPluginOptions } from '../admin/mockttp-admin-plugin'; import { AdminPlugin, PluginClientResponsesMap, PluginStartParamsMap } from '../admin/admin-plugin-types'; import { SchemaIntrospector } from './schema-introspection'; import { AdminQuery, getSingleSelectedFieldName } from './admin-query'; import { MockttpOptions } from '../mockttp'; const { fetch, Headers } = isNode || typeof globalThis.fetch === 'undefined' ? CrossFetch : globalThis; export class ConnectionError extends TypedError { } // The Response type requires lib.dom. We include an empty placeholder here to // avoid the types breaking if you don't have that available. Once day TS will // fix this: https://github.com/microsoft/TypeScript/issues/31894 declare global { interface Response {} } export class RequestError extends TypedError { constructor( message: string, public response: Response ) { super(message); } } export class GraphQLError extends RequestError { constructor( response: Response, public errors: Array<{ message: string }> ) { super( errors.length === 0 ? `GraphQL request failed with ${response.status} response` : errors.length === 1 ? `GraphQL request failed with: ${errors[0].message}` : // >1 `GraphQL request failed, with errors:\n${errors.map((e) => e.message).join('\n')}`, response ); } } export interface AdminClientOptions { /** * The full URL to use to connect to a Mockttp admin server when using a * remote (or local but browser) client. * * When using a local server, this option is ignored. */ adminServerUrl?: string; /** * Options to include on all client requests. */ requestOptions?: { headers?: { [key: string]: string }; }; } const mergeClientOptions = ( options: RequestInit | undefined, defaultOptions: AdminClientOptions['requestOptions'] ) => { if (!defaultOptions) return options; if (!options) return defaultOptions; if (defaultOptions.headers) { if (!options.headers) { options.headers = defaultOptions.headers; } else if (options.headers instanceof Headers) { _.forEach(defaultOptions.headers, (value, key) => { (options.headers as Headers).append(key, value); }); } else if (_.isObject(options.headers)) { Object.assign(options.headers, defaultOptions.headers); } } return options; }; async function requestFromAdminServer<T>(serverUrl: string, path: string, options?: RequestInit): Promise<T> { const url = `${serverUrl}${path}`; let response; try { response = await fetch(url, options); } catch (e) { if (isErrorLike(e) && e.code === 'ECONNREFUSED') { throw new ConnectionError(`Failed to connect to admin server at ${serverUrl}`); } else throw e; } if (response.status >= 400) { let body = await response.text(); let jsonBody: { error?: string } | null = null; try { jsonBody = JSON.parse(body); } catch (e) { } if (jsonBody && jsonBody.error) { throw new RequestError( jsonBody.error, response ); } else { throw new RequestError( `Request to ${url} failed, with status ${response.status} and response body: ${body}`, response ); } } else { return response.json(); } } /** * Reset a remote admin server, shutting down all Mockttp servers controlled by that * admin server. This is equivalent to calling `client.stop()` for all remote * clients of the target server. * * This can be useful in some rare cases, where a client might fail to reliably tear down * its own server, e.g. in Cypress testing. In this case, it's useful to reset the * admin server completely remotely without needing access to any previous client * instances, to ensure all servers from previous test runs have been shut down. * * After this is called, behaviour of any previously connected clients is undefined, and * it's likely that they may throw errors or experience other undefined behaviour. Ensure * that `client.stop()` has been called on all active clients before calling this method. */ export async function resetAdminServer(options: AdminClientOptions = {}): Promise<void> { const serverUrl = options.adminServerUrl || `http://localhost:${DEFAULT_ADMIN_SERVER_PORT}`; await requestFromAdminServer(serverUrl, '/reset', { ...options.requestOptions, method: 'POST' }); } /** * A bare admin server client. This is not intended for general use, but can be useful when * building admin server plugins to mock non-HTTP protocols and other advanced use cases. * * For normal usage of Mockttp, you should use `Mockttp.getRemote()` instead, to get a Mockttp * remote client, which wraps this class with the full Mockttp API for mocking HTTP. */ export class AdminClient<Plugins extends { [key: string]: AdminPlugin<any, any> }> { private adminClientOptions: RequireProps<AdminClientOptions, 'adminServerUrl'>; private adminSessionBaseUrl: string | undefined; private adminServerStream: Duplex | undefined; private subscriptionClient: SubscriptionClient | undefined; // Metadata from the last start() call, if the server is currently connected: private adminServerSchema: SchemaIntrospector | undefined; private adminServerMetadata: PluginClientResponsesMap<Plugins> | undefined; private debug: boolean = false; // True if server is entirely initialized, false if it's entirely shut down, or a promise // that resolves to one or the other if it's currently changing state. private running: MaybePromise<boolean> = false; constructor(options: AdminClientOptions = {}) { this.adminClientOptions = _.defaults(options, { adminServerUrl: `http://localhost:${DEFAULT_ADMIN_SERVER_PORT}` }); } private attachStreamWebsocket(adminSessionBaseUrl: string, targetStream: Duplex): Duplex { const adminSessionBaseWSUrl = adminSessionBaseUrl.replace(/^http/, 'ws'); const wsStream = connectWebSocketStream(`${adminSessionBaseWSUrl}/stream`, { headers: this.adminClientOptions?.requestOptions?.headers // Only used in Node.js (via WS) }); let streamConnected = false; wsStream.on('connect', () => { streamConnected = true; targetStream.pipe(wsStream); wsStream.pipe(targetStream, { end: false }); }); // We ignore errors, but websocket closure eventually results in reconnect or shutdown wsStream.on('error', (e) => { if (this.debug) console.warn('Admin client stream error', e); }); // When the websocket closes (after connect, either close frame, error, or socket shutdown): wsStream.on('ws-close', async (closeEvent) => { targetStream.unpipe(wsStream); const serverShutdown = closeEvent.code === 1000; if (serverShutdown) { // Clean shutdown implies the server is gone, and we need to shutdown & cleanup. this.stop(); } else if (streamConnected && (await this.running) === true) { console.warn('Admin client stream unexpectedly disconnected', closeEvent); // Unclean shutdown means something has gone wrong somewhere. Try to reconnect. const newStream = this.attachStreamWebsocket(adminSessionBaseUrl, targetStream); new Promise((resolve, reject) => { newStream.once('connect', resolve); newStream.once('error', reject); }).then(() => { // On a successful connect, business resumes as normal. console.warn('Admin client stream reconnected'); }).catch((err) => { // On a failed reconnect, we just shut down completely. console.warn('Admin client stream reconnection failed, shutting down', err); this.stop(); }); } // If never connected successfully, we do nothing. }); return wsStream; } private openStreamToMockServer(adminSessionBaseUrl: string): Promise<Duplex> { // To allow reconnects, we need to not end the client stream when an individual web socket ends. // To make that work, we return a separate stream, which isn't directly connected to the websocket // and doesn't receive WS 'end' events, and then we can swap the WS inputs accordingly. const { socket1: wsTarget, socket2: exposedStream } = new DuplexPair(); const wsStream = this.attachStreamWebsocket(adminSessionBaseUrl, wsTarget); wsTarget.on('error', (e) => exposedStream.emit('error', e)); // These receive a lot of listeners! One channel per matcher, handler & completion checker, // and each adds listeners for data/error/finish/etc. That's OK, it's not generally a leak, // but maybe 100 would be a bit suspicious (unless you have 30+ active rules). exposedStream.setMaxListeners(100); return new Promise((resolve, reject) => { wsStream.once('connect', () => resolve(exposedStream)); wsStream.once('error', reject); }); } private prepareSubscriptionClientToAdminServer(adminSessionBaseUrl: string) { const adminSessionBaseWSUrl = adminSessionBaseUrl.replace(/^http/, 'ws'); const subscriptionUrl = `${adminSessionBaseWSUrl}/subscription`; this.subscriptionClient = new SubscriptionClient(subscriptionUrl, { lazy: true, // Doesn't actually connect until you use subscriptions reconnect: true, reconnectionAttempts: 8, wsOptionArguments: [this.adminClientOptions.requestOptions] }, WebSocket); this.subscriptionClient.onError((e) => { if (this.debug) console.error("Subscription error", e) }); this.subscriptionClient.onReconnecting(() => console.warn('Reconnecting Mockttp subscription client') ); } private async requestFromMockServer(path: string, options?: RequestInit): Promise<Response> { // Must check for session URL, not this.running, or we can't send the /stop request during shutdown! if (!this.adminSessionBaseUrl) throw new Error('Not connected to mock server'); let url = this.adminSessionBaseUrl + path; let response = await fetch(url, mergeClientOptions(options, this.adminClientOptions.requestOptions)); if (response.status >= 400) { if (this.debug) console.error(`Remote client server request failed with status ${response.status}`); throw new RequestError( `Request to ${url} failed, with status ${response.status}`, response ); } else { return response; } } private async queryMockServer<T>(query: string, variables?: {}): Promise<T> { try { const response = (await this.requestFromMockServer('/', { method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ query, variables }) })); const { data, errors }: { data?: T, errors?: Error[] } = await response.json(); if (errors && errors.length) { throw new GraphQLError(response, errors); } else { return data as T; } } catch (e) { if (this.debug) console.error(`Remote client query error: ${e}`); if (!(e instanceof RequestError)) throw e; let graphQLErrors: Error[] | undefined = undefined; try { graphQLErrors = (await e.response.json()).errors; } catch (e2) {} if (graphQLErrors) { throw new GraphQLError(e.response, graphQLErrors); } else { throw e; } } } async start( pluginStartParams: PluginStartParamsMap<Plugins> ): Promise<PluginClientResponsesMap<Plugins>> { if (this.adminSessionBaseUrl || await this.running) throw new Error('Server is already started'); if (this.debug) console.log(`Starting remote mock server`); const startPromise = getDeferred<boolean>(); this.running = startPromise.then((result) => { this.running = result; return result; }); try { const supportOldServers = 'http' in pluginStartParams; const portConfig = supportOldServers ? (pluginStartParams['http'] as MockttpPluginOptions).port : undefined; const path = portConfig ? `/start?port=${JSON.stringify(portConfig)}` : '/start'; const adminServerResponse = await requestFromAdminServer< | { port: number, mockRoot: string } // Backward compat for old servers | { id: string, pluginData: PluginClientResponsesMap<Plugins> } // New plugin-aware servers >( this.adminClientOptions.adminServerUrl, path, mergeClientOptions({ method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ plugins: pluginStartParams, // Include all the Mockttp params at the root too, for backward compat with old admin servers: ...(pluginStartParams.http?.options as MockttpOptions | undefined) }) }, this.adminClientOptions.requestOptions) ); // Backward compat for old servers const isPluginAwareServer = 'id' in adminServerResponse; const sessionId = isPluginAwareServer ? adminServerResponse.id : adminServerResponse.port.toString(); const adminSessionBaseUrl = `${this.adminClientOptions.adminServerUrl}/${ isPluginAwareServer ? 'session' : 'server' }/${sessionId}` // Also open a stream connection, for 2-way communication we might need later. this.adminServerStream = await this.openStreamToMockServer(adminSessionBaseUrl); // Create a subscription client, preconfigured & ready to connect if on() is called later: this.prepareSubscriptionClientToAdminServer(adminSessionBaseUrl); // We don't persist the id or resolve the start promise until everything is set up this.adminSessionBaseUrl = adminSessionBaseUrl; // Load the schema on server start, so we can check for feature support this.adminServerSchema = new SchemaIntrospector( (await this.queryMockServer<any>(introspectionQuery)).__schema ); if (this.debug) console.log('Started remote mock server'); const serverMetadata = this.adminServerMetadata = // Set field before we resolve the promise 'pluginData' in adminServerResponse ? adminServerResponse.pluginData : { // Backward compat - convert old always-HTTP data into per-plugin format: http: adminServerResponse } as unknown as PluginClientResponsesMap<Plugins>; startPromise.resolve(true); return serverMetadata; } catch (e) { startPromise.resolve(false); throw e; } } isRunning() { return this.running === true; } get metadata() { if (!this.isRunning()) throw new Error("Metadata is not available until the mock server is started"); return this.adminServerMetadata!; } get schema() { if (!this.isRunning()) throw new Error("Admin schema is not available until the mock server is started"); return this.adminServerSchema!; } get adminStream() { if (!this.isRunning()) throw new Error("Admin stream is not available until the mock server is started"); return this.adminServerStream!; } // Call when either we want the server to stop, or it appears that the server has already stopped, // and we just want to ensure that's happened and clean everything up. async stop(): Promise<void> { if (await this.running === false) return; // If stopped or stopping, do nothing. const stopPromise = getDeferred<boolean>(); this.running = stopPromise.then((result) => { this.running = result; return result; }); try { if (this.debug) console.log('Stopping remote mock server'); try { this.subscriptionClient?.close(); } catch (e) { console.log(e); } this.subscriptionClient = undefined; try { this.adminServerStream?.end(); } catch (e) { console.log(e); } this.adminServerStream = undefined; await this.requestServerStop(); } finally { // The client is always stopped (and so restartable) once stopping completes, in all // cases, since it can always be started again to reset it. The promise is just here // so that we successfully handle (and always wait for) parallel stops. stopPromise.resolve(false); } } private requestServerStop() { return this.requestFromMockServer('/stop', { method: 'POST' }).catch((e) => { if (e instanceof RequestError && e.response.status === 404) { // 404 means it doesn't exist, generally because it was already stopped // by some other parallel shutdown process. return; } else { throw e; } }).then(() => { this.adminSessionBaseUrl = undefined; this.adminServerSchema = undefined; this.adminServerMetadata = undefined; }); } public enableDebug = async (): Promise<void> => { return (await this.queryMockServer<void>( `mutation EnableDebug { enableDebug }` )); } public reset = async (): Promise<void> => { return (await this.queryMockServer<void>( `mutation Reset { reset }` )); } public async sendQuery<Response, Result = Response>(query: AdminQuery<Response, Result>): Promise<Result> { return (await this.sendQueries(query))[0]; } public async sendQueries<Queries extends Array<AdminQuery<any>>>( ...queries: [...Queries] ): Promise<{ [n in keyof Queries]: Queries[n] extends AdminQuery<any, infer R> ? R : never }> { const results = queries.map<Promise<Array<unknown>>>( async ({ query, variables, transformResponse }) => { const result = await this.queryMockServer(print(query), variables); return transformResponse ? transformResponse(result, { adminClient: this }) : result; } ); return Promise.all(results) as Promise<{ [n in keyof Queries]: Queries[n] extends AdminQuery<any, infer R> ? R : never }>; } public async subscribe<Response, Result = Response>( query: AdminQuery<Response, Result>, callback: (data: Result) => void ): Promise<void> { if (await this.running === false) throw new Error('Not connected to mock server'); const fieldName = getSingleSelectedFieldName(query); if (!this.schema!.typeHasField('Subscription', fieldName)) { console.warn(`Remote client cannot subscribe to unrecognized event: ${fieldName}`); return Promise.resolve(); } // This isn't 100% correct (you can be WS-connected, but still negotiating some GQL // setup) but it's good enough for our purposes (knowing-ish if the connection worked). let isConnected = !!this.subscriptionClient!.client; this.subscriptionClient!.request(query).subscribe({ next: async (value) => { if (value.data) { const response = (<any> value.data)[fieldName]; const result = query.transformResponse ? await query.transformResponse(response, { adminClient: this }) : response as Result; callback(result); } else if (value.errors) { console.error('Error in subscription', value.errors); } }, error: (e) => this.debug && console.warn('Error in remote subscription:', e) }); return new Promise((resolve, reject) => { if (isConnected) resolve(); else { this.subscriptionClient!.onConnected(resolve); this.subscriptionClient!.onDisconnected(reject); this.subscriptionClient!.onError(reject); } }); } /** * List the names of the rule parameters defined by the admin server. This can be * used in some advanced use cases to confirm that the parameters a client wishes to * reference are available. * * Only defined for remote clients. */ public async getRuleParameterKeys() { if (await this.running === false) { throw new Error('Cannot query rule parameters before the server is started'); } if (!this.schema!.queryTypeDefined('ruleParameterKeys')) { // If this endpoint isn't supported, that's because parameters aren't supported // at all, so we can safely report that immediately. return []; } let result = await this.queryMockServer<{ ruleParameterKeys: string[] }>( `query GetRuleParameterNames { ruleParameterKeys }` ); return result.ruleParameterKeys; } }
the_stack
import assert from "assert"; import * as vscode from "vscode"; import * as sinon from "sinon"; import { TextEditor } from "vscode"; import { EmacsEmulator } from "../../emulator"; import { assertCursorsEqual, assertTextEqual, cleanUpWorkspace, setEmptyCursors, setupWorkspace } from "./utils"; suite("Prefix argument (Universal argument: C-u)", () => { let activeTextEditor: TextEditor; let emulator: EmacsEmulator; setup(() => { sinon.spy(vscode.commands, "executeCommand"); }); teardown(() => { sinon.restore(); }); const assertPrefixArgumentContext = (expected: number | undefined) => { assert( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore vscode.commands.executeCommand.calledWithExactly("setContext", "emacs-mcx.prefixArgument", expected), `Assertion failed that emacs-mcx.prefixArgument context has been set to ${expected}` ); }; const assertAcceptingArgumentContext = (expected: boolean) => { assert( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore vscode.commands.executeCommand.calledWithExactly("setContext", "emacs-mcx.acceptingArgument", expected), `Assertion failed that emacs-mcx.acceptingArgument context has been set to ${expected}` ); }; const resetExecuteCommandSpy = () => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore vscode.commands.executeCommand.resetHistory(); }; suite("repeating single character", () => { setup(async () => { activeTextEditor = await setupWorkspace(); emulator = new EmacsEmulator(activeTextEditor); }); teardown(cleanUpWorkspace); test("repeating charactor input for the given argument", async () => { resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(true); assertPrefixArgumentContext(4); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(2); assertPrefixArgumentContext(2); resetExecuteCommandSpy(); await emulator.typeChar("a"); assertTextEqual(activeTextEditor, "aa"); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); test("repeating charactor input for the given argument 0", async () => { resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(true); assertPrefixArgumentContext(4); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(0); assertPrefixArgumentContext(0); resetExecuteCommandSpy(); await emulator.typeChar("a"); assertTextEqual(activeTextEditor, ""); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); test("repeating charactor input for the given argument prefixed by 0", async () => { resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(true); assertPrefixArgumentContext(4); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(0); assertPrefixArgumentContext(0); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(2); assertPrefixArgumentContext(2); await emulator.typeChar("a"); assertTextEqual(activeTextEditor, "aa"); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); test("repeating charactor input for the given argument with multiple digits", async () => { resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(true); assertPrefixArgumentContext(4); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(1); assertPrefixArgumentContext(1); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(2); assertPrefixArgumentContext(12); resetExecuteCommandSpy(); await emulator.typeChar("a"); assertTextEqual(activeTextEditor, "aaaaaaaaaaaa"); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); test("repeating charactor input with default argument (4)", async () => { resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(true); assertPrefixArgumentContext(4); resetExecuteCommandSpy(); await emulator.typeChar("a"); assertTextEqual(activeTextEditor, "aaaa"); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); [2, 3].forEach((times) => { test(`repeating charactor input with ${times} C-u`, async () => { resetExecuteCommandSpy(); for (let i = 0; i < times; ++i) { await emulator.universalArgument(); } assertAcceptingArgumentContext(true); assertPrefixArgumentContext(4 ** times); resetExecuteCommandSpy(); await emulator.typeChar("a"); assertTextEqual(activeTextEditor, "a".repeat(4 ** times)); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); }); test("c-u stops prefix argument input", async () => { resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(true); assertPrefixArgumentContext(4); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(1); assertPrefixArgumentContext(1); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(2); assertPrefixArgumentContext(12); resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(false); await emulator.typeChar("3"); assertTextEqual(activeTextEditor, "333333333333"); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); test("numerical input cancels previous repeated c-u", async () => { resetExecuteCommandSpy(); await emulator.universalArgument(); assertAcceptingArgumentContext(true); await emulator.universalArgument(); resetExecuteCommandSpy(); await emulator.universalArgument(); assertPrefixArgumentContext(64); resetExecuteCommandSpy(); await emulator.universalArgumentDigit(3); assertPrefixArgumentContext(3); resetExecuteCommandSpy(); await emulator.typeChar("a"); assertTextEqual(activeTextEditor, "aaa"); assertAcceptingArgumentContext(false); assertPrefixArgumentContext(undefined); }); }); suite("repeating EmacsEmulator's command (cursorMove (forwardChar)) with prefix command", () => { setup(async () => { activeTextEditor = await setupWorkspace("abcdefghijklmnopqrst\nabcdefghijklmnopqrst"); emulator = new EmacsEmulator(activeTextEditor); }); teardown(cleanUpWorkspace); test("repeating cursorMove for the given argument", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); await emulator.universalArgumentDigit(3); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 3]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 4]); // The command normaly worked since it has exited from universal argument mode. }); test("repeating cursorMove for the given argument 0", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); await emulator.universalArgumentDigit(0); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 0]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 1]); // The command normaly worked since it has exited from universal argument mode. }); test("repeating cursorMove for the given argument prefixed by 0", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); await emulator.universalArgumentDigit(0); await emulator.universalArgumentDigit(3); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 3]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 4]); // The command normaly worked since it has exited from universal argument mode. }); test("repeating cursorMove for the given argument with multiple digits", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); await emulator.universalArgumentDigit(1); await emulator.universalArgumentDigit(2); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 12]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 13]); // The command normaly worked since it has exited from universal argument mode. }); test("repeating cursorMove for the default argument (4)", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 4]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 5]); // The command normaly worked since it has exited from universal argument mode. }); test("repeating charactor input with double C-u", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); emulator.universalArgument(); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 16]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 17]); // The command normaly worked since it has exited from universal argument mode. }); test("c-u stops prefix argument input", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); assertAcceptingArgumentContext(true); await emulator.universalArgumentDigit(1); await emulator.universalArgumentDigit(2); emulator.universalArgument(); assertAcceptingArgumentContext(false); resetExecuteCommandSpy(); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 12]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 13]); // The command normaly worked since it has exited from universal argument mode. }); test("numerical input cancels previous repeated c-u", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); emulator.universalArgument(); emulator.universalArgument(); await emulator.universalArgumentDigit(3); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 3]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 4]); // The command normaly worked since it has exited from universal argument mode. }); test("multicursor with given argument", async () => { setEmptyCursors(activeTextEditor, [0, 0], [1, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); await emulator.universalArgumentDigit(3); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 3], [1, 3]); assertPrefixArgumentContext(undefined); await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [0, 4], [1, 4]); // The command normaly worked since it has exited from universal argument mode. }); }); suite("with forwardChar in multi-line text", () => { setup(async () => { activeTextEditor = await setupWorkspace("aaa\n".repeat(8)); emulator = new EmacsEmulator(activeTextEditor); }); teardown(cleanUpWorkspace); test("cursor moves over lines", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); emulator.universalArgument(); // C-u * 2 makes 16 character movements await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [4, 0]); }); test("cursor moves at most to the end of the text", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); emulator.universalArgument(); emulator.universalArgument(); // C-u * 3 makes 64 character movements await emulator.runCommand("forwardChar"); assertCursorsEqual(activeTextEditor, [8, 0]); }); }); suite("with backwardChar in multi-line text", () => { setup(async () => { activeTextEditor = await setupWorkspace("aaa\n".repeat(8)); emulator = new EmacsEmulator(activeTextEditor); }); teardown(cleanUpWorkspace); test("cursor moves over lines", async () => { setEmptyCursors(activeTextEditor, [8, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); emulator.universalArgument(); // C-u * 2 makes 16 character movements await emulator.runCommand("backwardChar"); assertCursorsEqual(activeTextEditor, [4, 0]); }); test("cursor moves at most to the beginning of the text", async () => { setEmptyCursors(activeTextEditor, [0, 0]); resetExecuteCommandSpy(); emulator.universalArgument(); emulator.universalArgument(); emulator.universalArgument(); // C-u * 3 makes 64 character movements await emulator.runCommand("backwardChar"); assertCursorsEqual(activeTextEditor, [0, 0]); }); }); });
the_stack
import * as sprequest from 'sp-request'; import { ISPRequest, HTTPError } from 'sp-request'; import * as url from 'url'; import { IAuthOptions } from 'sp-request'; import { ICoreOptions, IFileContentOptions, CheckinType, IFileMetaData } from './SPSaveOptions'; import { UrlHelper } from './../utils/UrlHelper'; import { FoldersCreator } from './../utils/FoldersCreator'; import { ILogger } from './../utils/ILogger'; import { ConsoleLogger } from './../utils/ConsoleLogger'; import { defer, IDeferred } from './../utils/Defer'; export class FileSaver { private static saveConfilctCode = '-2130246326'; private static cobaltCode = '-1597308888'; private static directoryNotFoundCode = '-2147024893'; private static fileDoesNotExistOnpremCode = '-2146232832'; private static fileDoesNotExistOnlineCode = '-2130575338'; private static reUploadTimeout = 1500; private static maxAttempts = 3; private sprequest: ISPRequest; private uploadFileRestUrl: string; private getFileRestUrl: string; private checkoutFileRestUrl: string; private checkinFileRestUrl: string; private updateMetaDataRestUrl: string; private path: string; private foldersCreator: FoldersCreator; private logger: ILogger; private coreOptions: ICoreOptions; private file: IFileContentOptions; constructor(coreOptions: ICoreOptions, credentialOptions: IAuthOptions, fileOptions: IFileContentOptions) { this.sprequest = sprequest.create(credentialOptions); this.file = Object.assign<any, IFileContentOptions>({}, fileOptions); this.coreOptions = Object.assign<any, ICoreOptions>({}, coreOptions); this.coreOptions = Object.assign<any, ICoreOptions>({ checkin: false, checkinType: CheckinType.minor, checkinMessage: 'Checked in by spsave' }, this.coreOptions); this.coreOptions.siteUrl = UrlHelper.removeTrailingSlash(this.coreOptions.siteUrl); this.file.folder = UrlHelper.trimSlashes(this.file.folder); this.path = UrlHelper.removeTrailingSlash(url.parse(this.coreOptions.siteUrl).path); this.foldersCreator = new FoldersCreator(this.sprequest, this.file.folder, this.coreOptions.siteUrl); this.logger = new ConsoleLogger(); this.buildRestUrls(); } public save(): Promise<any> { const deferred: IDeferred<any> = defer<any>(); if (typeof this.file.fileContent === 'string' && Buffer.byteLength(<string>this.file.fileContent) === 0) { this.skipUpload(deferred); } else if (this.file.fileContent.length === 0) { this.skipUpload(deferred); } else { this.saveFile(deferred); } return deferred.promise; } /* saves file in a folder. If save conflict or cobalt error is thrown, tries to reupload file `maxAttempts` times */ private saveFile(requestDeferred: IDeferred<any>, attempts = 1): void { if (attempts > FileSaver.maxAttempts) { const message = `File '${this.file.fileName}' probably is not uploaded: too many errors. Upload process interrupted.`; this.logger.error(message); requestDeferred.reject(new Error(message)); return; } /* checkout file (only if option checkin provided) */ const checkoutResult: Promise<boolean> = this.checkoutFile(); const uploadResult: Promise<any> = checkoutResult .then(() => { /* upload file to folder */ return this.sprequest.requestDigest(this.coreOptions.siteUrl); }) .then(digest => { return this.sprequest.post(this.uploadFileRestUrl, { headers: { 'X-RequestDigest': digest }, body: this.file.fileContent, responseType: typeof this.file.fileContent === 'string' ? 'text' : 'buffer' }); }); Promise.all([checkoutResult, uploadResult]) .then(result => { return this.updateMetaData(result); }) .then(result => { const fileExists: boolean = result[0]; const data: any = result[1]; /* checkin file if checkin options presented */ if (this.coreOptions.checkin && fileExists) { return this.checkinFile(); /* if this is the first upload and we need to checkin the file, explicitly trigger checkin by uploading once again */ } else if (this.coreOptions.checkin && !fileExists) { this.saveFile(requestDeferred, attempts + 1); return null; } else { this.logger.success(this.file.fileName + ` successfully uploaded to '${this.coreOptions.siteUrl}/${this.file.folder}'`); } requestDeferred.resolve(JSON.parse(data.body)); return null; }).then(data => { if (!data) { return; } if (requestDeferred.isPending()) { this.logger.success(this.file.fileName + ` successfully uploaded to '${this.coreOptions.siteUrl}/${this.file.folder}' and checked in.` + ` Checkin type: ${CheckinType[this.coreOptions.checkinType]}`); requestDeferred.resolve(data.body); } }) .catch((err: HTTPError) => { if (err && (err.response?.statusCode === 500 || err.response?.statusCode === 409)) { /* save conflict or cobalt error */ this.tryReUpload(err, requestDeferred, attempts); return; } /* folder doesn't exist, create and reupload */ if (err && err.response?.statusCode === 404 && err.response?.body && err.response?.body.toString().indexOf(FileSaver.directoryNotFoundCode) !== -1) { this.foldersCreator.createFoldersHierarchy() .then(() => { this.saveFile(requestDeferred, attempts + 1); return null; }) .catch(folderError => { requestDeferred.reject(folderError); }); return; } requestDeferred.reject(err); }); } private skipUpload(deferred: IDeferred<any>): void { this.logger.warning(`File '${this.file.fileName}': skipping, file content is empty.`); deferred.resolve(true); } private updateMetaData(data: any): Promise<any> { return new Promise<any>((resolve, reject) => { if (!this.coreOptions.filesMetaData || this.coreOptions.filesMetaData.length === 0) { resolve(data); return; } const fileMetaData: IFileMetaData = this.coreOptions.filesMetaData.filter(fileData => { return fileData.fileName === this.file.fileName; })[0]; if (!fileMetaData || fileMetaData.updated) { resolve(data); return; } this.sprequest.requestDigest(this.coreOptions.siteUrl) .then(digest => { return this.sprequest.post(this.updateMetaDataRestUrl, { headers: { 'X-RequestDigest': digest, 'IF-MATCH': '*', 'X-HTTP-Method': 'MERGE' }, body: fileMetaData.metadata }); }) .then(() => { fileMetaData.updated = true; resolve(data); return null; }) .catch(reject); }); } /* checkins files */ private checkinFile(): Promise<any> { if (this.coreOptions.checkinType && this.coreOptions.checkinType == CheckinType.nocheckin) { return Promise.resolve(true); } return new Promise<any>((resolve, reject) => { this.sprequest.requestDigest(this.coreOptions.siteUrl) .then(digest => { return this.sprequest.post(this.checkinFileRestUrl, { headers: { 'X-RequestDigest': digest } }); }) .then(data => { resolve(data); return null; }) .catch(reject); }); } /* tries to checkout file. returns true if file exists or false if doesn't */ private checkoutFile(): Promise<boolean> { const promise: Promise<any> = new Promise<any>((resolve, reject) => { /* if checkin option isn't provided, just resolve to true and return */ if (!this.coreOptions.checkin) { resolve(true); return undefined; } this.getFileByUrl() .then(data => { /* if already checked out, resolve to true */ if (data.body.d.CheckOutType === 0) { resolve(true); return null; } /* not checked out yet, so checkout */ return this.sprequest.requestDigest(this.coreOptions.siteUrl) .then(digest => { return this.sprequest.post(this.checkoutFileRestUrl, { headers: { 'X-RequestDigest': digest } }) .then(() => { this.logger.info(`${this.file.fileName} checked out.`); resolve(true); return null; }); }); }, err => { /* file doesn't exist message code, resolve with false */ if (err.response.body.error.code.indexOf(FileSaver.fileDoesNotExistOnpremCode) !== -1 || err.response.body.error.code.indexOf(FileSaver.fileDoesNotExistOnlineCode) !== -1) { resolve(false); return null; } reject(err); return null; }) .catch(reject); }); return promise; } private getFileByUrl(): Promise<any> { return this.sprequest.get(this.getFileRestUrl); } /* check if error is save conflict or cobalt error and tries to reupload the file, otherwise reject deferred */ private tryReUpload(exception: any, deferred: IDeferred<any>, attempts: number): void { let errorData: any; try { errorData = JSON.parse(exception.error); } catch (e) { deferred.reject(exception); return; } const reUpload: () => void = (): void => { setTimeout(() => { this.saveFile(deferred, attempts + 1); }, FileSaver.reUploadTimeout); }; if (errorData.error) { if (errorData.error.code && errorData.error.code.indexOf(FileSaver.saveConfilctCode) === 0) { this.logger.warning(`Save conflict detected for file '${this.file.fileName}'. Trying to re-upload...`); reUpload(); } else if (errorData.error.code && errorData.error.code.indexOf(FileSaver.cobaltCode) === 0) { this.logger.warning(`Cobalt error detected for file '${this.file.fileName}'. Trying to re-upload...`); reUpload(); } else { this.logger.error(errorData.error); deferred.reject(exception); } } else { deferred.reject(exception); } } private buildRestUrls(): void { const fileServerRelativeUrl = `${this.path}/${this.file.folder}/${this.file.fileName}`; this.uploadFileRestUrl = this.coreOptions.siteUrl + '/_api/web/GetFolderByServerRelativeUrl(@FolderName)/Files/add(url=@FileName,overwrite=true)' + `?@FolderName='${encodeURIComponent(this.file.folder)}'&@FileName='${encodeURIComponent(this.file.fileName)}'`; this.getFileRestUrl = this.coreOptions.siteUrl + '/_api/web/GetFileByServerRelativeUrl(@FileUrl)' + `?@FileUrl='${encodeURIComponent(fileServerRelativeUrl)}'`; this.checkoutFileRestUrl = this.coreOptions.siteUrl + '/_api/web/GetFileByServerRelativeUrl(@FileUrl)/CheckOut()' + `?@FileUrl='${encodeURIComponent(fileServerRelativeUrl)}'`; this.checkinFileRestUrl = this.coreOptions.siteUrl + '/_api/web/GetFileByServerRelativeUrl(@FileUrl)/CheckIn(comment=@Comment,checkintype=@Type)' + `?@FileUrl='${encodeURIComponent(fileServerRelativeUrl)}'&@Comment='${(this.coreOptions.checkinMessage)}'` + `&@Type='${this.coreOptions.checkinType}'`; this.updateMetaDataRestUrl = this.coreOptions.siteUrl + '/_api/web/GetFileByServerRelativeUrl(@FileUrl)/ListItemAllFields' + `?@FileUrl='${encodeURIComponent(fileServerRelativeUrl)}'`; } }
the_stack
import { ArrayType1D, BaseDataOptionType, SeriesInterface } from "../shared/types"; import NDframe from "./generic"; import Str from './strings'; import Dt from './datetime'; import { DataFrame } from "./frame"; /** * One-dimensional ndarray with axis labels. * The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. * Operations between DataFrame (+, -, /, , *) align values based on their associated index values– they need not be the same length. * @param data 2D Array, JSON, Tensor, Block of data. * @param options.index Array of numeric or string names for subseting array. If not specified, indexes are auto generated. * @param options.columns Array of column names. If not specified, column names are auto generated. * @param options.dtypes Array of data types for each the column. If not specified, dtypes are/is inferred. * @param options.config General configuration object for extending or setting NDframe behavior. */ export default class Series extends NDframe implements SeriesInterface { constructor(data?: any, options?: BaseDataOptionType); /** * Purely integer-location based indexing for selection by position. * ``.iloc`` is primarily integer position based (from ``0`` to * ``length-1`` of the axis), but may also be used with a boolean array. * * @param rows Array of row indexes * * Allowed inputs are in rows and columns params are: * * - An array of single integer, e.g. ``[5]``. * - A list or array of integers, e.g. ``[4, 3, 0]``. * - A slice array string with ints, e.g. ``["1:7"]``. * - A boolean array. * - A ``callable`` function with one argument (the calling Series or * DataFrame) and that returns valid output for indexing (one of the above). * This is useful in method chains, when you don't have a reference to the * calling object, but would like to base your selection on some value. * * ``.iloc`` will raise ``IndexError`` if a requested indexer is * out-of-bounds. */ iloc(rows: Array<string | number | boolean>): Series; /** * Access a group of rows by label(s) or a boolean array. * ``loc`` is primarily label based, but may also be used with a boolean array. * * @param rows Array of row indexes * * Allowed inputs are: * * - A single label, e.g. ``["5"]`` or ``['a']``, (note that ``5`` is interpreted as a * *label* of the index, and **never** as an integer position along the index). * * - A list or array of labels, e.g. ``['a', 'b', 'c']``. * * - A slice object with labels, e.g. ``["a:f"]``. Note that start and the stop are included * * - A boolean array of the same length as the axis being sliced, * e.g. ``[True, False, True]``. * * - A ``callable`` function with one argument (the calling Series or * DataFrame) and that returns valid output for indexing (one of the above) */ loc(rows: Array<string | number | boolean>): Series; /** * Returns the first n values in a Series * @param rows The number of rows to return */ head(rows?: number): Series; /** * Returns the last n values in a Series * @param rows The number of rows to return */ tail(rows?: number): Series; /** * Returns specified number of random rows in a Series * @param num The number of rows to return * @param options.seed An integer specifying the random seed that will be used to create the distribution. */ sample(num?: number, options?: { seed?: number; }): Promise<Series>; /** * Return Addition of series and other, element-wise (binary operator add). * Equivalent to series + other * @param other Series, Array of same length or scalar number to add * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ add(other: Series | Array<number> | number, options?: { inplace?: boolean; }): Series | void; /** * Returns the subtraction between a series and other, element-wise (binary operator subtraction). * Equivalent to series - other * @param other Number to subtract * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ sub(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; /** * Return Multiplication of series and other, element-wise (binary operator mul). * Equivalent to series * other * @param other Number to multiply with. * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ mul(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; /** * Return division of series and other, element-wise (binary operator div). * Equivalent to series / other * @param other Series or number to divide with. * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ div(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; /** * Return Exponential power of series and other, element-wise (binary operator pow). * Equivalent to series ** other * @param other Number to multiply with. * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ pow(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; /** * Return Modulo of series and other, element-wise (binary operator mod). * Equivalent to series % other * @param other Number to modulo with * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ mod(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; /** * Checks if the array value passed has a compatible dtype, removes NaN values, and if * boolean values are present, converts them to integer values. * */ private $checkAndCleanValues; /** * Returns the mean of elements in Series */ mean(): number; /** * Returns the median of elements in Series */ median(): number; /** * Returns the modal value of elements in Series */ mode(): any; /** * Returns the minimum value in a Series */ min(): number; /** * Returns the maximum value in a Series * @returns {Number} */ max(): number; /** * Return the sum of the values in a series. */ sum(): number; /** * Return number of non-null elements in a Series */ count(): number; /** * Return maximum of series and other. * @param other Series or number to check against */ maximum(other: Series | number | Array<number>): Series; /** * Return minimum of series and other. * @param other Series, Numbers to check against */ minimum(other: Series | number | Array<number>): Series; /** * Round each value in a Series to the specified number of decimals. * @param dp Number of Decimal places to round to * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ round(dp?: number, options?: { inplace?: boolean; }): Series | void; /** * Return sample standard deviation of elements in Series */ std(): number; /** * Return unbiased variance of elements in a Series. */ var(): number; /** * Return a boolean same-sized object indicating where elements are NaN. * NaN and undefined values gets mapped to true, and everything else gets mapped to false. */ isna(): Series; /** * Replace all NaN with a specified value * @param value The value to replace NaN with * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ fillna(options?: { value: number | string | boolean, inplace?: boolean; }): Series | void; /** * Sort a Series in ascending or descending order by some criterion. * @param options Method options * @param ascending Whether to return sorted values in ascending order or not. Defaults to true * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ sort_values(options?: { ascending?: boolean, inplace?: boolean; }): Series | void; /** * Makes a deep copy of a Series */ copy(): Series; /** * Generate descriptive statistics. * Descriptive statistics include those that summarize the central tendency, * dispersion and shape of a dataset’s distribution, excluding NaN values. */ describe(): Series; /** * Returns Series with the index reset. * This is useful when index is meaningless and needs to be reset to the default before another operation. */ reset_index(options?: { inplace?: boolean; }): Series | void; /** * Set the Series index (row labels) using an array of the same length. * @param index Array of new index values, * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ set_index(options?: { index: Array<number | string | (number | string)>, inplace?: boolean; }): Series | void; /** * map all the element in a column to a variable or function * @param callable callable can either be a funtion or an object * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ map(callable: any, options?: { inplace?: boolean; }): Series | void; /** * Applies a function to each element of a Series * @param callable Function to apply to each element of the series * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ apply(callable: any, options?: { inplace?: boolean; }): Series | void; /** * Returns a Series with only the unique value(s) in the original Series */ unique(): Series; /** * Return the number of unique elements in a Series */ nunique(): number; /** * Returns unique values and their counts in a Series */ value_counts(): Series; /** * Returns the absolute values in Series * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ abs(options?: { inplace?: boolean; }): Series | void; /** * Returns the cumulative sum over a Series */ cumsum(options?: { inplace?: boolean; }): Series | void; /** * Returns cumulative minimum over a Series */ cummin(options?: { inplace?: boolean; }): Series | void; /** * Returns cumulative maximum over a Series */ cummax(options?: { inplace?: boolean; }): Series | void; /** * Returns cumulative product over a Series */ cumprod(options?: { inplace?: boolean; }): Series | void; /** * perform cumulative operation on series data */ private cumOps; /** * Returns less than of series and other. Supports element wise operations * @param other Series or number to compare against */ lt(other: Series | number): Series; /** * Returns Greater than of series and other. Supports element wise operations * @param {other} Series, Scalar * @return {Series} */ gt(other: Series | number | Array<number>): Series; /** * Returns Less than or Equal to of series and other. Supports element wise operations * @param {other} Series, Scalar * @return {Series} */ le(other: Series | number | Array<number>): Series; /** * Returns Greater than or Equal to of series and other. Supports element wise operations * @param {other} Series, Scalar * @return {Series} */ ge(other: Series | number | Array<number>): Series; /** * Returns Not Equal to of series and other. Supports element wise operations * @param {other} Series, Scalar * @return {Series} */ ne(other: Series | number | Array<number>): Series; /** * Returns Equal to of series and other. Supports element wise operations * @param {other} Series, Scalar * @return {Series} */ eq(other: Series | number | Array<number>): Series; /** * Perform boolean operations on bool values * @param other Other Series or number to compare with * @param bOps Name of operation to perform [ne, ge, le, gt, lt, eq] */ private boolOps; /** * Replace all occurence of a value with a new value * @param oldValue The value you want to replace * @param newValue The new value you want to replace the old value with * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ replace(options?: { oldValue: string | number | boolean, newValue: string | number | boolean, inplace?: boolean; }): Series | void; /** * Drops all missing values (NaN) from a Series. * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ dropna(options?: { inplace?: boolean; }): Series | undefined; /** * Return the integer indices that would sort the Series. * @param ascending boolean true: will sort the Series in ascending order, false: will sort in descending order */ argsort(ascending?: boolean): Series; /** * Return int position of the largest value in the Series. */ argmax(): number; /** * Return int position of the smallest value in the Series. */ argmin(): number; /** * Remove duplicate values from a Series * @param keep "first" | "last", which dupliate value to keep. Defaults to "first". * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ drop_duplicates(options?: { keep?: "first" | "last"; inplace?: boolean; }): Series | void; /** * Cast Series to specified data type * @param dtype Data type to cast to. One of [float32, int32, string, boolean, undefined] * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ astype(dtype: "float32" | "int32" | "string" | "boolean" | "undefined", options?: { inplace?: boolean; }): Series | void; /** * Add a new value or values to the end of a Series * @param newValues Single value | Array | Series to append to the Series * @param index The new index value(s) to append to the Series. Must contain the same number of values as `newValues` * as they map `1 - 1`. * @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false */ append(newValue: string | number | boolean | Series | ArrayType1D, index: Array<number | string> | number | string, options?: { inplace?: boolean; }): Series | void; /** * Returns dtype of Series */ get dtype(): string; /** * Exposes numerous string methods to manipulate Series of type string */ get str(): Str; /** * Returns time class that exposes different date time method */ get dt(): Dt; /** * Prints Series to console as a grid of row and columns. */ toString(): string; /** * Returns the logical AND between Series and other. Supports element wise operations and broadcasting. * @param other Series, Scalar, Array of Scalars */ and(other: any): Series; /** * Returns the logical OR between Series and other. Supports element wise operations and broadcasting. * @param other Series, Scalar, Array of Scalars */ or(other: any): Series; /** * One-hot encode values in the Series. * @param options Options for the operation. The following options are available: * - `prefix`: Prefix to add to the new column. Defaults to unique labels. * - `prefixSeparator`: Separator to use for the prefix. Defaults to '_'. * @returns A DataFrame with the one-hot encoded columns. * @example * sf.get_dummies() * sf.get_dummies({prefix: 'cat' }) * sf.get_dummies({ prefix: 'cat', prefixSeparator: '-' }) */ get_dummies(options?: { columns?: string | Array<string>; prefix?: string | Array<string>; prefixSeparator?: string; }): DataFrame; }
the_stack
import * as babelCore from '@babel/core'; import { Scope } from '@babel/traverse'; // @ts-ignore import splitExportDeclaration from '@babel/helper-split-export-declaration'; import path from 'path'; import babelPluginMacros, { createMacro } from 'babel-plugin-macros'; import { StateMachine } from 'xstate'; import { rollup } from 'rollup'; import babelPlugin from '@rollup/plugin-babel'; import nodeResolvePlugin from '@rollup/plugin-node-resolve'; import Module from 'module'; const generateRandomId = (): string => Math.random() .toString(36) .substring(2); const generateUniqueId = (map: Record<string, any>): string => { const id = generateRandomId(); return Object.prototype.hasOwnProperty.call(map, id) ? generateUniqueId(map) : id; }; const compiledOutputs: Record<string, string> = Object.create(null); (Module as any)._extensions['.xstate.js'] = (module: any, filename: string) => { const [_match, id] = filename.match(/-(\w+)\.xstate\.js$/)!; module._compile(compiledOutputs[id], filename); }; type UsedImport = { localName: string; importedName: string; }; type ReferencePathsByImportName = Record< string, Array<babelCore.NodePath<babelCore.types.Node>> >; const cwd = process.cwd(); const extensions = ['.tsx', '.ts', '.jsx', '.js']; const getImports = ( { types: t }: typeof babelCore, path: babelCore.NodePath<babelCore.types.ImportDeclaration>, ): UsedImport[] => { return path.node.specifiers.map((specifier) => { if (t.isImportNamespaceSpecifier(specifier)) { throw new Error( 'Using a namespace import for `@xstate/import` is not supported.', ); } return { localName: specifier.local.name, importedName: specifier.type === 'ImportDefaultSpecifier' ? 'default' : specifier.local.name, }; }); }; const getReferencePathsByImportName = ( scope: Scope, imports: UsedImport[], ): ReferencePathsByImportName | undefined => { let shouldExit = false; let hasReferences = false; const referencePathsByImportName = imports.reduce( (byName, { importedName, localName }) => { let binding = scope.getBinding(localName); if (!binding) { shouldExit = true; return byName; } byName[importedName] = binding.referencePaths; hasReferences = hasReferences || Boolean(byName[importedName].length); return byName; }, {} as ReferencePathsByImportName, ); if (!hasReferences || shouldExit) { return; } return referencePathsByImportName; }; const getMachineId = ( importName: string, { types: t }: typeof babelCore, callExpression: babelCore.types.CallExpression, ) => { const { typeParameters } = callExpression; if ( !typeParameters || !typeParameters.params[2] || !t.isTSLiteralType(typeParameters.params[2]) || !t.isStringLiteral(typeParameters.params[2].literal) ) { console.log('You must pass three type arguments to your machine.'); console.log(); console.log('For instance:'); console.log( `const machine = ${importName}<Context, Event, 'aUniqueIdForYourMachine'>({})`, ); console.log(); throw new Error('You must pass three type arguments to your machine.'); } return typeParameters.params[2].literal.value; }; const insertExtractingExport = ( { types: t }: typeof babelCore, statementPath: babelCore.NodePath<babelCore.types.Statement>, { importName, index, machineId, machineIdentifier, }: { importName: string; index: number; machineId: string; machineIdentifier: string; }, ) => { statementPath.insertAfter( t.exportNamedDeclaration( t.variableDeclaration('var', [ t.variableDeclarator( t.identifier(`__xstate_${importName}_${index}`), t.objectExpression([ t.objectProperty(t.identifier('id'), t.stringLiteral(machineId)), t.objectProperty( t.identifier('machine'), t.identifier(machineIdentifier), ), ]), ), ]), ), ); }; const handleMachineFactoryCalls = ( importName: string, { references, babel }: babelPluginMacros.MacroParams, ) => { if (!references[importName]) { return; } const { types: t } = babel; references[importName].forEach((referencePath, index) => { const callExpressionPath = referencePath.parentPath; if (!t.isCallExpression(callExpressionPath.node)) { throw new Error(`\`${importName}\` can only be called.`); } const machineId = getMachineId(importName, babel, callExpressionPath.node); const callExpressionParentPath = callExpressionPath.parentPath; const callExpressionParentNode = callExpressionParentPath.node; switch (callExpressionParentNode.type) { case 'VariableDeclarator': { if (!t.isIdentifier(callExpressionParentNode.id)) { throw new Error( `Result of the \`${importName}\` call can only appear in the variable declaration.`, ); } const statementPath = callExpressionParentPath.getStatementParent(); if (!statementPath.parentPath.isProgram()) { throw new Error( `\`${importName}\` calls can only appear in top-level statements.`, ); } insertExtractingExport(babel, statementPath, { importName, index, machineId, machineIdentifier: callExpressionParentNode.id.name, }); break; } case 'ExportDefaultDeclaration': { splitExportDeclaration(callExpressionParentPath); insertExtractingExport( babel, callExpressionParentPath.getStatementParent(), { importName, index, machineId, machineIdentifier: ((callExpressionParentPath as babelCore.NodePath< babelCore.types.VariableDeclaration >).node.declarations[0].id as babelCore.types.Identifier).name, }, ); break; } default: { throw new Error( `\`${importName}\` calls can only appear in the variable declaration or as a default export.`, ); } } }); }; const macro = createMacro((params) => { handleMachineFactoryCalls('createMachine', params); handleMachineFactoryCalls('Machine', params); }); type ExtractedMachine = { id: string; machine: StateMachine<any, any, any>; }; const getCreatedExports = ( importName: string, exportsObj: Record<string, any>, ): ExtractedMachine[] => { const extracted: ExtractedMachine[] = []; let counter = 0; while (true) { const currentCandidate = exportsObj[`__xstate_${importName}_${counter++}`]; if (!currentCandidate) { return extracted; } extracted.push(currentCandidate); } }; export const extractMachines = async ( filePath: string, ): Promise<ExtractedMachine[]> => { const resolvedFilePath = path.resolve(cwd, filePath); const build = await rollup({ input: resolvedFilePath, external: (id) => !/^(\.|\/|\w:)/.test(id), plugins: [ nodeResolvePlugin({ extensions, }), babelPlugin({ babelHelpers: 'bundled', extensions, plugins: [ '@babel/plugin-transform-typescript', '@babel/plugin-proposal-optional-chaining', '@babel/plugin-proposal-nullish-coalescing-operator', (babel: typeof babelCore) => { return { name: 'xstate-codegen-machines-extractor', visitor: { ImportDeclaration( path: babelCore.NodePath<babelCore.types.ImportDeclaration>, state: babelCore.PluginPass, ) { if ( state.filename !== resolvedFilePath || path.node.source.value !== '@xstate/compiled' ) { return; } const imports = getImports(babel, path); const referencePathsByImportName = getReferencePathsByImportName( path.scope, imports, ); if (!referencePathsByImportName) { return; } /** * Other plugins that run before babel-plugin-macros might use path.replace, where a path is * put into its own replacement. Apparently babel does not update the scope after such * an operation. As a remedy, the whole scope is traversed again with an empty "Identifier" * visitor - this makes the problem go away. * * See: https://github.com/kentcdodds/import-all.macro/issues/7 */ state.file.scope.path.traverse({ Identifier() {}, }); macro({ path, references: referencePathsByImportName, state, babel, // hack to make this call accepted by babel-plugin-macros isBabelMacrosCall: true, }); }, }, }; }, ], }), ], }); const output = await build.generate({ format: 'cjs', exports: 'named', }); const chunk = output.output[0]; const { code } = chunk; // dance with those unique ids is not really needed, at least right now // loading CJS modules is synchronous // once we start to support loading ESM this won't hold true anymore let uniqueId = generateUniqueId(compiledOutputs); try { compiledOutputs[uniqueId] = code; const fakeFileName = path.join( path.dirname(resolvedFilePath), `${path .basename(resolvedFilePath) .replace(/\./g, '-')}-${uniqueId}.xstate.js`, ); const module = new Module(fakeFileName); (module as any).load(fakeFileName); return [ ...getCreatedExports('createMachine', module.exports), ...getCreatedExports('Machine', module.exports), ]; } finally { delete compiledOutputs[uniqueId]; } };
the_stack
import { RoughCanvas } from 'roughjs/bin/canvas' import { Options } from 'roughjs/bin/core' import rough from 'roughjs/bin/rough' import { RoughSVG } from 'roughjs/bin/svg' import { processRoot } from './processor' import { RenderMode } from './RenderMode' import { SvgTextures } from './SvgTextures' import { getDefsElement, RenderContext } from './utils' /** * Svg2Roughjs parses a given SVG and draws it with Rough.js * in a canvas. */ export class Svg2Roughjs { private $svg?: SVGSVGElement private width: number = 0 private height: number = 0 private canvas: HTMLCanvasElement | SVGSVGElement private $roughConfig: Options private rc: RoughCanvas | RoughSVG private $fontFamily: string | null private $randomize: boolean private $backgroundColor: string | null = null private $renderMode: RenderMode private ctx: CanvasRenderingContext2D | null = null private $pencilFilter: boolean = false private idElements: Record<string, SVGElement | string> = {} /** * The SVG that should be converted. * Changing this property triggers drawing of the SVG into * the canvas or container element with which Svg2Roughjs * was initialized. */ set svg(svg: SVGSVGElement) { if (this.$svg !== svg) { this.$svg = svg if (svg.hasAttribute('width')) { this.width = svg.width.baseVal.value } else if (svg.hasAttribute('viewBox')) { this.width = svg.viewBox.baseVal.width } else { this.width = 300 } if (svg.hasAttribute('height')) { this.height = svg.height.baseVal.value } else if (svg.hasAttribute('viewBox')) { this.height = svg.viewBox.baseVal.height } else { this.height = 150 } if (this.renderMode === RenderMode.CANVAS && this.ctx) { const canvas = this.canvas as HTMLCanvasElement canvas.width = this.width canvas.height = this.height } else { const svg = this.canvas as SVGSVGElement svg.setAttribute('width', this.width.toString()) svg.setAttribute('height', this.height.toString()) } // pre-process defs for subsequent references this.collectElementsWithID() this.redraw() } } get svg(): SVGSVGElement { return this.$svg as SVGSVGElement } /** * Rough.js config object that is provided to Rough.js for drawing * any SVG element. * Changing this property triggers a repaint. */ set roughConfig(config: Options) { this.$roughConfig = config if (this.renderMode === RenderMode.CANVAS && this.ctx) { this.rc = rough.canvas(this.canvas as HTMLCanvasElement, { options: this.roughConfig }) } else { this.rc = rough.svg(this.canvas as SVGSVGElement, { options: this.roughConfig }) } this.redraw() } get roughConfig(): Options { return this.$roughConfig } /** * Set a font-family for the rendering of text elements. * If set to `null`, then the font-family of the SVGTextElement is used. * By default, 'Comic Sans MS, cursive' is used. * Changing this property triggers a repaint. */ set fontFamily(fontFamily: string | null) { if (this.$fontFamily !== fontFamily) { this.$fontFamily = fontFamily this.redraw() } } get fontFamily(): string | null { return this.$fontFamily } /** * Whether to randomize Rough.js' fillWeight, hachureAngle and hachureGap. * Also randomizes the disableMultiStroke option of Rough.js. * By default true. * Changing this property triggers a repaint. */ set randomize(randomize: boolean) { this.$randomize = randomize this.redraw() } get randomize(): boolean { return this.$randomize } /** * Optional solid background color with which * the canvas should be initialized. * It is drawn on a transparent canvas by default. */ set backgroundColor(color: string | null) { this.$backgroundColor = color } get backgroundColor(): string | null { return this.$backgroundColor } /** * Changes the output format of the converted SVG. * Changing this property will replace the current output * element with either a new HTML canvas or new SVG element. */ set renderMode(mode: RenderMode) { if (this.$renderMode === mode) { return } this.$renderMode = mode const parent = this.canvas!.parentElement as HTMLElement parent.removeChild(this.canvas!) let target: HTMLCanvasElement | SVGSVGElement if (mode === RenderMode.CANVAS) { target = document.createElement('canvas') target.width = this.width target.height = this.height this.ctx = target.getContext('2d') } else { this.ctx = null target = document.createElementNS('http://www.w3.org/2000/svg', 'svg') target.setAttribute('xmlns', 'http://www.w3.org/2000/svg') target.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink') target.setAttribute('width', this.width.toString()) target.setAttribute('height', this.height.toString()) } parent!.appendChild(target) this.canvas = target if (mode === RenderMode.CANVAS) { this.rc = rough.canvas(this.canvas as HTMLCanvasElement, { options: this.roughConfig }) } else { this.rc = rough.svg(this.canvas as SVGSVGElement, { options: this.roughConfig }) } this.redraw() } get renderMode(): RenderMode { return this.$renderMode } /** * Whether to apply a pencil filter. * Only works for SVG render mode. */ set pencilFilter(value: boolean) { if (this.$pencilFilter !== value) { this.$pencilFilter = value this.redraw() } } get pencilFilter(): boolean { return this.$pencilFilter } /** * Creates a new context which contains the current state of the * Svg2Roughs instance for rendering. * @returns A new context. */ createRenderContext(): RenderContext { if (!this.$svg) { throw new Error('No source SVG set yet.') } const ctx: RenderContext = { rc: this.rc, roughConfig: this.roughConfig, renderMode: this.renderMode, fontFamily: this.fontFamily, pencilFilter: this.pencilFilter, randomize: this.randomize, idElements: this.idElements, sourceSvg: this.$svg, processElement: processRoot } if (this.renderMode === RenderMode.CANVAS && this.ctx) { ctx.targetCanvas = this.canvas as HTMLCanvasElement ctx.targetCanvasContext = this.ctx } else { ctx.targetSvg = this.canvas as SVGSVGElement } return ctx } /** * Creates a new instance of Svg2roughjs. * @param target Either a selector for the container to which a canvas should be added * or an `HTMLCanvasElement` or `SVGSVGElement` that should be used as output target. * @param renderMode Whether the output should be an SVG or drawn to an HTML canvas. * Defaults to SVG or CANVAS depending if the given target is of type `HTMLCanvasElement` or `SVGSVGElement`, * otherwise it defaults to SVG. * @param roughjsOptions Config object this passed to the Rough.js ctor and * also used while parsing the styles for `SVGElement`s. */ constructor( target: string | HTMLCanvasElement | SVGSVGElement, renderMode: RenderMode = RenderMode.SVG, roughjsOptions: Options = {} ) { if (!target) { throw new Error('No target provided') } if (target instanceof HTMLCanvasElement || target instanceof SVGSVGElement) { if (target.tagName === 'canvas' || target.tagName === 'svg') { this.canvas = target this.$renderMode = target.tagName === 'canvas' ? RenderMode.CANVAS : RenderMode.SVG } else { throw new Error('Target object is not of type HTMLCanvasElement or SVGSVGElement') } } else { // create a new HTMLCanvasElement or SVGSVGElement as child of the given element const container = document.querySelector(target) if (!container) { throw new Error(`No element found with ${target}`) } if (renderMode === RenderMode.CANVAS) { this.canvas = document.createElement('canvas') this.canvas.width = container.clientWidth this.canvas.height = container.clientHeight } else { this.canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg') this.canvas.setAttribute('xmlns', 'http://www.w3.org/2000/svg') this.canvas.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink') } this.$renderMode = renderMode container.appendChild(this.canvas) } this.$roughConfig = roughjsOptions // the Rough.js instance to draw the SVG elements if (this.renderMode === RenderMode.CANVAS) { const canvas = this.canvas as HTMLCanvasElement this.rc = rough.canvas(canvas, { options: this.roughConfig }) // canvas context for convenient access this.ctx = canvas.getContext('2d') } else { this.rc = rough.svg(this.canvas as SVGSVGElement, { options: this.roughConfig }) } // default font family this.$fontFamily = 'Comic Sans MS, cursive' // we randomize the visualization per element by default this.$randomize = true } /** * Triggers an entire redraw of the SVG which * processes the input element anew. */ redraw(): void { if (!this.svg) { return } // reset target element if (this.renderMode === RenderMode.CANVAS) { this.initializeCanvas(this.canvas as HTMLCanvasElement) } else { this.initializeSvg(this.canvas as SVGSVGElement) } const renderContext = this.createRenderContext() renderContext.processElement(renderContext, this.svg, null, this.width, this.height) } /** * Prepares the given canvas element depending on the set properties. */ private initializeCanvas(canvas: HTMLCanvasElement) { this.ctx = canvas.getContext('2d') if (this.ctx) { this.ctx.clearRect(0, 0, this.width, this.height) if (this.backgroundColor) { this.ctx.fillStyle = this.backgroundColor this.ctx.fillRect(0, 0, this.width, this.height) } // use round linecap to emphasize a ballpoint pen like drawing this.ctx.lineCap = 'round' } } /** * Prepares the given SVG element depending on the set properties. */ private initializeSvg(svgElement: SVGSVGElement) { // maybe canvas rendering was used before this.ctx = null // clear SVG element while (svgElement.firstChild) { svgElement.removeChild(svgElement.firstChild) } // apply backgroundColor let backgroundElement if (this.backgroundColor) { backgroundElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect') backgroundElement.width.baseVal.value = this.width backgroundElement.height.baseVal.value = this.height backgroundElement.setAttribute('fill', this.backgroundColor) svgElement.appendChild(backgroundElement) } // prepare filter effects if (this.pencilFilter) { const defs = getDefsElement(svgElement) defs.appendChild(SvgTextures.pencilTextureFilter) } // use round linecap to emphasize a ballpoint pen like drawing svgElement.setAttribute('stroke-linecap', 'round') } /** * Stores elements with IDs for later use. */ private collectElementsWithID() { this.idElements = {} const elementsWithID: SVGElement[] = Array.prototype.slice.apply( this.svg.querySelectorAll('*[id]') ) for (const elt of elementsWithID) { const id = elt.getAttribute('id') if (id) { this.idElements[id] = elt } } } }
the_stack
import * as T from '@babel/types' import template from '@babel/template' import generator, { GeneratorResult, GeneratorOptions } from '@babel/generator' import { parse, ParserOptions } from '@babel/parser' interface ParseOptions extends ParserOptions { isScriptSetup: boolean lang: string } export function toAST( code: string, options: Partial<ParseOptions> = {}, ): T.File { const { isScriptSetup = false, lang = 'js', ...config } = options const finalOptions = { sourceType: 'module' as const, ...config, errorRecovery: true, plugins: [ 'bigInt', 'nullishCoalescingOperator', 'optionalChaining', 'optionalCatchBinding', 'dynamicImport', 'logicalAssignment', ] as Required<ParserOptions>['plugins'], } if (options.plugins != null) finalOptions.plugins.push(...options.plugins) if (isScriptSetup) { finalOptions.plugins.push('topLevelAwait') } if (lang.startsWith('ts')) { finalOptions.plugins.push('typescript') } if (lang.endsWith('x')) { finalOptions.plugins.push('jsx') } finalOptions.plugins = Array.from(new Set(finalOptions.plugins)) return parse(code, finalOptions) as T.File } export function toCode( node: T.Node | T.Node[], options: GeneratorOptions = {}, ): GeneratorResult { const nodes = Array.isArray(node) ? node : [node] const statement = T.program( nodes .map((node) => T.toStatement(node)) .filter( (node): node is T.Statement => node !== false && T.isStatement(node), ), ) return generator(statement as any, { comments: true, ...options, }) } type Evictable<T extends (...args: any) => any> = T & { evict(...args: Parameters<T>): void } function memoize<F extends (...args: any) => any>( fn: F, getKey: (args: Parameters<F>) => object, ): Evictable<F> { const microcache = new WeakMap() const fnx = ((...args) => { const key = getKey(args) if (microcache.has(key)) return microcache.get(key) const value = fn(...args) microcache.set(key, value) return value }) as Evictable<F> fnx.evict = (...args) => microcache.delete(getKey(args)) return fnx } function memoizeByFirstArg<F extends (...args: any) => any>( fn: F, ): Evictable<F> { return memoize(fn, (args) => args[0]) } export interface CreateExportDeclarationOptions { exportName: string isScriptSetup: boolean shouldIncludeScriptSetup(id: string): boolean } export interface CreateExportDeclarationForScriptSetupOptions { defineComponent: string shouldIncludeBinding(id: string): boolean } /** * Create export statement from local components. */ export const createExportDeclarationForScriptSetup = memoizeByFirstArg( ( ast: T.File, options?: Partial<CreateExportDeclarationForScriptSetupOptions>, ): T.ExportDefaultDeclaration => { const config: CreateExportDeclarationForScriptSetupOptions = { defineComponent: 'VueDX.internal.defineSetupComponent', shouldIncludeBinding: () => true, ...options, } const createExpr = template( `${config.defineComponent}(%%props%%, %%emits%%, %%bindings%%, %%extra%%)`, ) const props = getExpressionOrReference(findDefinePropsStatement(ast)) const emits = getExpressionOrReference(findDefineEmitsStatement(ast)) const extra = getExpressionOrReference(null) const bindings = T.objectExpression( findScopeBindings(ast) .filter((id) => config.shouldIncludeBinding(id)) .map((id) => T.identifier(id)) .map((id) => T.objectProperty(id, id, false, true)), ) const statement = createExpr({ props, emits, bindings, extra }) if (Array.isArray(statement) || !T.isExpressionStatement(statement)) { throw new Error('Unexpected') } return T.exportDefaultDeclaration(statement.expression) }, ) export const findDefinePropsStatement = memoizeByFirstArg((ast: T.File) => { return findTopLevelCall( ast, findLocalName(ast, 'vue', 'defineProps') ?? 'defineProps', ) }) export const findDefineEmitsStatement = memoizeByFirstArg((ast: T.File) => { return findTopLevelCall( ast, findLocalName(ast, 'vue', 'defineEmits') ?? 'defineEmits', ) }) export const findDefineExposeStatement = memoizeByFirstArg((ast: T.File) => { return findTopLevelCall( ast, findLocalName(ast, 'vue', 'defineExpose') ?? 'defineExpose', ) }) /** * Create export statement from local components. */ export const createExportDeclarationForComponents = memoizeByFirstArg( ( ast: T.File, options?: Partial<CreateExportDeclarationOptions>, ): T.ExportNamedDeclaration => { return createExportDeclarationFor(ast, 'components', options) }, ) /** * Create export statement from local directives. */ export const createExportDeclarationForDirectives = memoizeByFirstArg( ( ast: T.File, options?: Partial<CreateExportDeclarationOptions>, ): T.ExportNamedDeclaration => { return createExportDeclarationFor(ast, 'directives', options) }, ) export const findScopeBindings = memoizeByFirstArg( (node: T.File | T.Program | T.BlockStatement): string[] => { const identifiers = new Set<string>() const statements = T.isFile(node) ? node.program.body : node.body const processIdentifier = (node: T.Identifier): void => { identifiers.add(node.name) } const processAssignmentPattern = (node: T.AssignmentPattern): void => { if (T.isIdentifier(node.left)) processIdentifier(node.left) else if (T.isObjectPattern(node.left)) processObjectPattern(node.left) else if (T.isArrayPattern(node.left)) processArrayPattern(node.left) } const processRestElement = (node: T.RestElement): void => { if (T.isIdentifier(node.argument)) processIdentifier(node.argument) } const processObjectPattern = (node: T.ObjectPattern): void => { node.properties.forEach((property) => { if (T.isRestElement(property)) { processRestElement(property) } else if (T.isObjectProperty(property)) { if (T.isIdentifier(property.value)) { processIdentifier(property.value) } else if (T.isAssignmentPattern(property.value)) { processAssignmentPattern(property.value) } else if (T.isRestElement(property.value)) { processRestElement(property.value) } else if (T.isArrayPattern(property.value)) { processArrayPattern(property.value) } else if (T.isObjectPattern(property.value)) { processObjectPattern(property.value) } } else { // - exaustive if branches // property } }) } const processArrayPattern = (node: T.ArrayPattern): void => { node.elements.forEach((element) => { if (T.isIdentifier(element)) { processIdentifier(element) } else if (T.isAssignmentPattern(element)) { processAssignmentPattern(element) } else if (T.isRestElement(element)) { processRestElement(element) } else if (T.isArrayPattern(element)) { processArrayPattern(element) } else if (T.isObjectPattern(element)) { processObjectPattern(element) } }) } statements.forEach((statement) => { if (T.isImportDeclaration(statement) && statement.importKind !== 'type') { statement.specifiers.forEach((specifier) => { identifiers.add(specifier.local.name) }) } else if ( T.isFunctionDeclaration(statement) || T.isTSDeclareFunction(statement) ) { if (statement.id != null) processIdentifier(statement.id) } else if (T.isVariableDeclaration(statement)) { statement.declarations.forEach((declaration) => { if (T.isIdentifier(declaration.id)) processIdentifier(declaration.id) else if (T.isObjectPattern(declaration.id)) { processObjectPattern(declaration.id) } else if (T.isArrayPattern(declaration.id)) { processArrayPattern(declaration.id) } }) } else if (T.isClassDeclaration(statement)) { processIdentifier(statement.id) } else if (T.isTSEnumDeclaration(statement)) { processIdentifier(statement.id) } }) return Array.from(identifiers) }, ) export const findComponentOptions = memoizeByFirstArg( (ast: T.File): T.ObjectExpression | null => { const node = ast.program.body.find( (node): node is T.ExportDefaultDeclaration => T.isExportDefaultDeclaration(node), ) if (node != null) { if (T.isObjectExpression(node.declaration)) { return node.declaration } else if (T.isCallExpression(node.declaration)) { if (node.declaration.arguments.length > 0) { const options = node.declaration.arguments[0] if (T.isObjectExpression(options)) { return options } } } } return null }, ) /** * Create export statement from local components. */ function createExportDeclarationFor( ast: T.File, kind: 'components' | 'directives', options?: Partial<CreateExportDeclarationOptions>, ): T.ExportNamedDeclaration { const config: CreateExportDeclarationOptions = { exportName: `__VueDX_${kind}`, isScriptSetup: false, shouldIncludeScriptSetup: () => true, ...options, } const RE = kind === 'components' ? /^[A-Z]/ : /^v[A-Z]/ const expr = config.isScriptSetup ? T.objectExpression( findScopeBindings(ast) .filter((id) => RE.test(id) && config.shouldIncludeScriptSetup(id)) .map((id) => T.identifier(id)) .map((id) => T.objectProperty(id, id, false, true)), ) : findComponentOption(ast, kind) ?? T.objectExpression([]) return T.exportNamedDeclaration( T.variableDeclaration('const', [ T.variableDeclarator(T.identifier(config.exportName), expr), ]), ) } function findComponentOption(ast: T.File, name: string): T.Expression | null { const target = findComponentOptions(ast) if (target == null) return null return findObjectProperty(target, name) } function findObjectProperty( node: T.ObjectExpression, propertyName: string, ): T.Expression | null { return ( (node.properties.find((property): property is T.ObjectProperty => { if (T.isObjectProperty(property)) { if (T.isStringLiteral(property.key)) { return property.key.value === propertyName } else if (T.isIdentifier(property.key)) { return property.key.name === propertyName } } return false })?.value as any) ?? null ) } /** * Find local name of imported identifier (or namespaced identifier). */ const findLocalName = ( ast: T.File, source: string, exportedName: string, ): string => { const RE = /[^a-z0-9$_].*$/i // Ignore unicode characters. const baseName = exportedName.replace(RE, '') const name = findLocalIdentifierName(ast, source, baseName) if (name == null) return exportedName return name + exportedName.substr(baseName.length) } /** * Find local identifier name of imported identifier. */ function findLocalIdentifierName( ast: T.File, source: string, exportedName: string, ): string | null { for (const statement of ast.program.body) { if (T.isImportDeclaration(statement)) { if (statement.source.value === source) { for (const specifier of statement.specifiers) { if (T.isImportSpecifier(specifier)) { const name = T.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value if (name === exportedName) { return specifier.local.name } } } } } } return null } function findTopLevelCall( ast: T.File, fn: string, ): T.Expression | T.VariableDeclarator | null { const isExpression = (exp: T.Expression): boolean => T.isCallExpression(exp) && T.isIdentifier(exp.callee) && exp.callee.name === fn for (const statement of ast.program.body) { if (T.isExpressionStatement(statement)) { if (isExpression(statement.expression)) { return statement.expression } } else if (T.isVariableDeclaration(statement)) { for (const declaration of statement.declarations) { if (declaration.init != null && isExpression(declaration.init)) { return declaration } } } } return null } function getExpressionOrReference( statement: T.Expression | T.VariableDeclarator | null, ): T.Expression | T.Identifier { if (T.isExpression(statement)) return statement else if (T.isVariableDeclarator(statement)) { if (T.isIdentifier(statement.id)) return statement.id else if (statement.init != null) return statement.init } return T.objectExpression([]) }
the_stack
import { CollectibleBase } from '@algomart/schemas' import { AccountInfo, accountInformation, calculateAppMinBalance, configureSignTxns, createClawbackNFTTransactions, createConfigureCustodialAccountTransactions, createDeployContractTransactions, createExportNFTTransactions, createImportNFTTransactions, createNewNFTsTransactions, decodeTransaction, decryptAccount, encryptAccount, generateAccount, makeStateConfig, NewNFT, pendingTransactionInformation, waitForConfirmation, WalletTransaction, } from '@algomart/shared/algorand' import { CollectibleModel } from '@algomart/shared/models' import algosdk from 'algosdk' import pino from 'pino' // 100_000 microAlgos = 0.1 ALGO export const DEFAULT_INITIAL_BALANCE = 100_000 export interface PublicAccount { address: string encryptedMnemonic: string transactionIds: string[] signedTransactions: Uint8Array[] } export interface AlgorandAdapterOptions { algodToken: string algodServer: string algodPort: number fundingMnemonic: string appSecret: string } export class AlgorandAdapter { logger: pino.Logger<unknown> fundingAccount: algosdk.Account algod: algosdk.Algodv2 constructor( private options: AlgorandAdapterOptions, logger: pino.Logger<unknown> ) { this.logger = logger.child({ context: this.constructor.name }) this.algod = new algosdk.Algodv2( { 'X-Algo-API-Token': options.algodToken }, options.algodServer, options.algodPort ) this.fundingAccount = algosdk.mnemonicToSecretKey(options.fundingMnemonic) this.logger.info('Using funding account %s', this.fundingAccount.addr) this.testConnection() } async testConnection() { try { const status = await this.algod.status().do() this.logger.info({ status }, 'Successfully connected to Algod') } catch (error) { this.logger.error(error, 'Failed to connect to Algod') } } async generateAccount(passphrase: string): Promise<PublicAccount> { const account = await generateAccount() const encryptedMnemonic = await encryptAccount( account, passphrase, this.options.appSecret ) return { address: account.addr, encryptedMnemonic, signedTransactions: [], transactionIds: [], } } async initialFundTransactions( encryptedMnemonic: string, passphrase: string, initialBalance = DEFAULT_INITIAL_BALANCE ) { const custodialAccount = await decryptAccount( encryptedMnemonic, passphrase, this.options.appSecret ) const result = await createConfigureCustodialAccountTransactions({ algod: this.algod, custodialAccount, fundingAccount: this.fundingAccount, initialFunds: initialBalance, }) return { transactionIds: result.txIDs, signedTransactions: result.signedTxns, } } /** * Submits one or more transactions to the network. Should only be used in a background task. * @param transaction The transaction(s) to be submitted * @returns The submitted transaction ID */ async submitTransaction(transaction: Uint8Array | Uint8Array[]) { try { return await this.algod.sendRawTransaction(transaction).do() } catch (error) { this.logger.error(error as Error) throw error } } async getAssetInfo(assetIndex: number) { const info = await this.algod .getAssetByID(assetIndex) .do() .catch(() => null) if (!info) { return null } return { address: info.index as number, creator: info.params.creator as string, unitName: info.params['unit-name'] as string, isFrozen: info['is-frozen'] as boolean, defaultFrozen: info.params['default-frozen'] as boolean, url: info.params.url as string, } } async getTransactionStatus(transactionId: string) { return pendingTransactionInformation(this.algod, transactionId) } async waitForConfirmation(transactionId: string, maxRounds = 5) { return waitForConfirmation(this.algod, transactionId, maxRounds) } async isValidPassphrase( encryptedMnemonic: string, passphrase: string ): Promise<boolean> { try { await decryptAccount( encryptedMnemonic, passphrase, this.options.appSecret ) // If we get here, the passphrase is valid return true } catch { // ignore error, passphrase is invalid return false } } async getAccountInfo(account: string): Promise<AccountInfo> { return accountInformation(this.algod, account) } async generateCreateAssetTransactions( collectibles: CollectibleModel[], templates: CollectibleBase[] ) { const templateLookup = new Map(templates.map((t) => [t.templateId, t])) const nfts: NewNFT[] = collectibles.map((collectible) => { const template = templateLookup.get(collectible.templateId) if (!template) { throw new Error(`Missing template ${collectible.templateId}`) } return { assetName: `${template.uniqueCode} ${collectible.edition}/${template.totalEditions}`, assetURL: `${collectible.assetUrl}#arc3`, assetMetadataHash: new Uint8Array( Buffer.from(collectible.assetMetadataHash, 'hex') ), edition: collectible.edition, totalEditions: template.totalEditions, unitName: template.uniqueCode, } }) const result = await createNewNFTsTransactions({ algod: this.algod, creatorAccount: this.fundingAccount, nfts, }) return { signedTransactions: result.signedTxns, transactionIds: result.txIDs, } } async generateClawbackTransactions(options: { assetIndex: number encryptedMnemonic: string passphrase: string fromAccountAddress?: string }) { const toAccount = await decryptAccount( options.encryptedMnemonic, options.passphrase, this.options.appSecret ) const result = await createClawbackNFTTransactions({ algod: this.algod, assetIndex: options.assetIndex, clawbackAccount: this.fundingAccount, currentOwnerAddress: options.fromAccountAddress || this.fundingAccount.addr, recipientAddress: toAccount.addr, fundingAccount: this.fundingAccount, recipientAccount: toAccount, }) return { transactionIds: result.txIDs, signedTransactions: result.signedTxns, } } async generateClawbackTransactionsFromUser(options: { assetIndex: number fromAccountAddress: string toAccountAddress: string }) { const result = await createClawbackNFTTransactions({ algod: this.algod, assetIndex: options.assetIndex, clawbackAccount: this.fundingAccount, currentOwnerAddress: options.fromAccountAddress, recipientAddress: options.toAccountAddress, skipOptIn: true, }) return { transactionIds: result.txIDs, signedTransactions: result.signedTxns, } } async createApplicationTransaction(options: { approvalProgram: string clearProgram: string appArgs: Uint8Array[] extraPages?: number numGlobalByteSlices?: number numGlobalInts?: number numLocalByteSlices?: number numLocalInts?: number accounts?: string[] foreignApps?: number[] foreignAssets?: number[] lease?: Uint8Array }) { const result = await createDeployContractTransactions({ algod: this.algod, approvalSource: options.approvalProgram, clearSource: options.clearProgram, contractName: 'unknown', creatorAccount: this.fundingAccount, globalState: makeStateConfig( options.numGlobalInts, options.numGlobalByteSlices ), localState: makeStateConfig( options.numLocalInts, options.numLocalByteSlices ), accounts: options.accounts, foreignApps: options.foreignApps, appArgs: options.appArgs, extraPages: options.extraPages, foreignAssets: options.foreignAssets, lease: options.lease, }) return { transactionIds: result.txIDs, signedTransactions: result.signedTxns, } } appMinBalance(options: { extraPages?: number numGlobalByteSlices?: number numGlobalInts?: number numLocalByteSlices?: number numLocalInts?: number }): { create: number; optIn: number } { return calculateAppMinBalance( makeStateConfig(options.numGlobalInts, options.numGlobalByteSlices), makeStateConfig(options.numLocalInts, options.numLocalByteSlices), options.extraPages ) } async generateExportTransactions(options: { assetIndex: number fromAccountAddress: string toAccountAddress: string }) { return await createExportNFTTransactions({ algod: this.algod, assetIndex: options.assetIndex, fromAddress: options.fromAccountAddress, fundingAddress: this.fundingAccount.addr, clawbackAddress: this.fundingAccount.addr, toAddress: options.toAccountAddress, }) } async signTransferTransactions(options: { passphrase: string encryptedMnemonic: string transactions: WalletTransaction[] }) { const fromAccount = await decryptAccount( options.encryptedMnemonic, options.passphrase, this.options.appSecret ) const signTxns = await configureSignTxns([fromAccount, this.fundingAccount]) const signedTransactions = await signTxns(options.transactions) return { transactionIds: await Promise.all( options.transactions.map(async (transaction) => (await decodeTransaction(transaction.txn)).txID() ) ), signedTransactions, } } async generateImportTransactions(options: { assetIndex: number toAccountAddress: string fromAccountAddress: string }): Promise<WalletTransaction[]> { return await createImportNFTTransactions({ algod: this.algod, assetIndex: options.assetIndex, fromAddress: options.fromAccountAddress, toAddress: options.toAccountAddress, fundingAddress: this.fundingAccount.addr, clawbackAddress: this.fundingAccount.addr, }) } }
the_stack
import { parsing } from "@algo-builder/web"; import { decodeAddress, encodeAddress, EncodedLogicSig, EncodedLogicSigAccount, EncodedMultisig, multisigAddress, MultisigMetadata, signBytes, verifyBytes } from "algosdk"; import * as murmurhash from 'murmurhash'; import * as tweet from "tweetnacl-ts"; import { RUNTIME_ERRORS } from "./errors/errors-list"; import { RuntimeError } from "./errors/runtime-errors"; import { compareArray } from "./lib/compare"; import { convertToString } from "./lib/parsing"; /** * Note: We cannot use algosdk LogicSig class here, * because algosdk.makeLogicSig() takes compiled bytes as a argument * and currently we don't calculate compiled bytes from TEAL program. * We are using raw TEAL code as program.(by converting string into bytes) */ export class LogicSig { logic: Uint8Array; args: Uint8Array[]; sig?: Uint8Array; msig?: EncodedMultisig; lsigAddress: string; tag: Buffer; constructor ( program: string, programArgs?: Array<Uint8Array | Buffer> | null ) { this.tag = Buffer.from("Program"); this.logic = parsing.stringToBytes(program); const seedBytes = parsing.uint64ToBigEndian(murmurhash.v3(program)); const extendedSeed = new Uint8Array(Number(seedBytes.length) + Number(24)); extendedSeed.set(seedBytes); const pair = tweet.sign_keyPair_fromSeed(extendedSeed); this.lsigAddress = encodeAddress(pair.publicKey); this.tag = Buffer.from('Program'); if ( programArgs && (!Array.isArray(programArgs) || !programArgs.every( (arg) => arg.constructor === Uint8Array || Buffer.isBuffer(arg) )) ) { throw new TypeError('Invalid arguments'); } let args: Uint8Array[]; if (programArgs != null) { args = programArgs.map((arg) => new Uint8Array(arg)); } else args = []; this.args = args; } /** * Creates signature (if no msig provided) or multi signature otherwise * @param secretKey sender's secret key * @param msig multisignature if it exists */ sign (secretKey: Uint8Array, msig?: MultisigMetadata): void { if (msig === undefined) { this.sig = this.signProgram(secretKey); } else { const subsigs = msig.addrs.map(addr => { return { pk: decodeAddress(addr).publicKey, s: new Uint8Array(0) }; }); this.msig = { v: msig.version, thr: msig.threshold, subsig: subsigs }; const [sig, index] = this.singleSignMultisig(secretKey, this.msig); this.msig.subsig[index].s = sig; } } /** * Sign Multisignature * @param secretKey Secret key to sign with * @param msig Multisignature */ singleSignMultisig (secretKey: Uint8Array, msig: EncodedMultisig): [Uint8Array, number] { let index = -1; const accountPk = tweet.sign_keyPair_fromSecretKey(secretKey).publicKey; for (let i = 0; i < msig.subsig.length; i++) { const pk = msig.subsig[i].pk; if (compareArray(pk, accountPk)) { index = i; break; } } if (index === -1) { throw new RuntimeError(RUNTIME_ERRORS.GENERAL.INVALID_SECRET_KEY, { secretkey: secretKey }); } const sig = this.signProgram(secretKey); return [sig, index]; } /** * Appends a signature to multi signature * @param {Uint8Array} secretKey Secret key to sign with */ appendToMultisig (secretKey: Uint8Array): void { if (this.msig === undefined) { throw new Error("no multisig present"); } const [sig, index] = this.singleSignMultisig(secretKey, this.msig); this.msig.subsig[index].s = sig; } /** * Performs signature verification * @param accAddr Sender's account address */ verify (accPk: Uint8Array): boolean { const accAddr = encodeAddress(accPk); if (!this.sig && !this.msig) { if (accAddr === this.lsigAddress) return true; return false; } if (this.sig) { return verifyBytes(this.logic, this.sig, accAddr); } if (this.msig) { return this.verifyMultisig(this.msig, accAddr); } return false; } /** * Verify multi-signature * @param msig Msig * @param accAddr Sender's account address */ verifyMultisig (msig: EncodedMultisig, accAddr: string): boolean { const version = msig.v; const threshold = msig.thr; const subsigs = msig.subsig; const addrs = subsigs.map( (subsig) => encodeAddress(subsig.pk) ); if (msig.subsig.length < threshold) { return false; } let multiSigaddr; try { const mparams = { version: version, threshold: threshold, addrs: addrs }; multiSigaddr = multisigAddress(mparams); } catch (e) { return false; } if (accAddr !== multiSigaddr) { return false; } let counter = 0; for (const subsig of subsigs) { if (!compareArray(subsig.s, new Uint8Array(0))) { counter += 1; } } if (counter < threshold) { return false; } let verifiedCounter = 0; for (const subsig of subsigs) { const subsigAddr = encodeAddress(subsig.pk); if (!compareArray(subsig.s, new Uint8Array(0)) && verifyBytes(this.logic, subsig.s as Uint8Array, subsigAddr )) { verifiedCounter += 1; } } if (verifiedCounter < threshold) { return false; } return true; } /** * Returns signed logic * @param secretKey: account's secret key */ signProgram (secretKey: Uint8Array): Uint8Array { return signBytes(this.logic, secretKey); } /** * Returns logic signature address */ address (): string { return this.lsigAddress; } /** * Returns program associated with logic signature */ program (): string { return convertToString(this.logic); } /** * Note: following functions are dummy functions * they are used only to match type with algosdk LogicSig * there is a possibility that we may use them in future. */ toByte (): Uint8Array { return this.logic; } fromByte (val: Uint8Array): LogicSig { return new LogicSig("DUMMY", []); } get_obj_for_encoding (): EncodedLogicSig { return { l: this.logic, arg: this.args, sig: this.sig, msig: this.msig }; } static from_obj_for_encoding (lsig: EncodedLogicSig): LogicSig { return new LogicSig("DUMMY", []); } } export class LogicSigAccount { lsig: LogicSig; sigkey?: Uint8Array; /** * Create a new LogicSigAccount. By default this will create an escrow * LogicSig account. Call `sign` or `signMultisig` on the newly created * LogicSigAccount to make it a delegated account. * * @param program - program in TEAL file * @param args - An optional array of arguments for the program. */ constructor ( program: string, programArgs?: Array<Uint8Array | Buffer> | null ) { this.lsig = new LogicSig(program, programArgs); this.sigkey = undefined; } /** * Note: following functions are dummy functions * they are used only to match type with algosdk LogicSigAccount * there is a possibility that we may use them in future. */ // eslint-disable-next-line camelcase get_obj_for_encoding (): EncodedLogicSigAccount { return { lsig: this.lsig.get_obj_for_encoding(), sigkey: this.sigkey }; } // eslint-disable-next-line camelcase static from_obj_for_encoding (encoded: EncodedLogicSigAccount): LogicSigAccount { const lsigAccount = new LogicSigAccount("DUMMY", encoded.lsig.arg); lsigAccount.lsig = LogicSig.from_obj_for_encoding(encoded.lsig); lsigAccount.sigkey = encoded.sigkey; return lsigAccount; } toByte (): Uint8Array { return this.lsig.toByte(); } static fromByte (encoded: ArrayLike<any>): LogicSigAccount { return new LogicSigAccount("DUMMY", []); } /** * Check if this LogicSigAccount has been delegated to another account with a * signature. * * Note this function only checks for the presence of a delegation signature. * To verify the delegation signature, use `verify`. */ isDelegated (): boolean { return !!(this.lsig.sig ?? this.lsig.msig); } /** * Verifies this LogicSig's program and signatures. * @returns true if and only if the LogicSig program and signatures are valid. */ verify (): boolean { const addr = this.address(); return this.lsig.verify(decodeAddress(addr).publicKey); } /** * Get the address of this LogicSigAccount. * * If the LogicSig is delegated to another account, this will return the * address of that account. * * If the LogicSig is not delegated to another account, this will return an * escrow address that is the hash of the LogicSig's program code. */ address (): string { if (this.lsig.sig && this.lsig.msig) { throw new Error( 'LogicSig has too many signatures. At most one of sig or msig may be present' ); } if (this.lsig.sig) { if (!this.sigkey) { throw new Error('Signing key for delegated account is missing'); } return encodeAddress(this.sigkey); } return this.lsig.address(); } /** * Turns this LogicSigAccount into a delegated LogicSig. This type of LogicSig * has the authority to sign transactions on behalf of another account, called * the delegating account. Use this function if the delegating account is a * multisig account. * * @param msig - The multisig delegating account * @param secretKey - The secret key of one of the members of the delegating * multisig account. Use `appendToMultisig` to add additional signatures * from other members. */ signMultisig (msig: MultisigMetadata, secretKey: Uint8Array): void { this.lsig.sign(secretKey, msig); } /** * Adds an additional signature from a member of the delegating multisig * account. * * @param secretKey - The secret key of one of the members of the delegating * multisig account. */ appendToMultisig (secretKey: Uint8Array): void { this.lsig.appendToMultisig(secretKey); } /** * Turns this LogicSigAccount into a delegated LogicSig. This type of LogicSig * has the authority to sign transactions on behalf of another account, called * the delegating account. If the delegating account is a multisig account, * use `signMultisig` instead. * * @param secretKey - The secret key of the delegating account. */ sign (secretKey: Uint8Array): void { this.lsig.sign(secretKey); this.sigkey = tweet.sign_keyPair_fromSecretKey(secretKey).publicKey; } }
the_stack
import { SystemInfo, Connector, ControllerScope, EngineApiOptions, EngineConnectorSettings, EngineProgramOptions, GlobalUserSettings, GlobalUserSettingsOptions, Machine, Program, ProgramExecutionResult, ProgramTestResult, TestResult, // Container, ContainerStats, ContainerImageMount, ContainerImagePortMapping, // ContainerImage, ContainerImageHistory, // Secret, Volume, SystemPruneReport, SystemResetReport, Pod, PodProcessReport, // ContainerStateList, ConnectOptions, ApplicationDescriptor, GenerateKubeOptions, FindProgramOptions, CreateMachineOptions, ContainerClientResponse, Network, ContainerAdapter, } from "./Types.container-app"; // module import { // Domain, // } from "./Types"; import { Native } from "./Native"; export const CONTAINER_GROUP_SEPARATOR = "_"; export interface FetchDomainOptions {} export interface FetchImageOptions { Id: string; withHistory?: boolean; withKube?: boolean; } export interface PushImageOptions { destination?: string; tlsVerify?: boolean; registryAuth?: string; } export interface FetchContainerOptions { Id: string; withLogs?: boolean; withStats?: boolean; withKube?: boolean; } export interface FetchVolumeOptions { Id: string; } export interface CreateContainerOptions { ImageId: string; Name?: string; // flags Start?: boolean; Mounts?: ContainerImageMount[]; PortMappings?: ContainerImagePortMapping[]; } export interface CreateVolumeOptions { Driver: string; Label: { [key: string]: string }; Labels: { [key: string]: string }; Name: string; Options: { [key: string]: string }; } export interface FetchSecretOptions { Id: string; // name or id } export interface CreateSecretOptions { driver?: string; name: string; Secret: string; } export interface FetchPodOptions { Id: string; withProcesses?: boolean; withKube?: boolean; withLogs?: boolean | { Tail: number }; } export interface CreatePodOptions { Name: string; Start?: boolean; } export interface InvocationOptions<T = unknown> { method: string; params?: T; } export type CreateNetworkOptions = Partial<Network>; export const coerceContainer = (container: Container) => { if (container.ImageName) { container.Image = container.ImageName; } container.Logs = container.Logs || []; container.Ports = container.Ports || []; if (!container.Computed) { container.Computed = {} as any; } if (typeof container.State === "object") { container.Computed.DecodedState = container.State.Status as ContainerStateList; } else { container.Computed.DecodedState = container.State as ContainerStateList; } const containerName = `${container.Names?.[0] || container.Name}`; if (containerName) { container.Computed.Name = containerName; // Compute group name (name prefix) const [groupName, ...containerNameInGroupParts] = containerName.split(CONTAINER_GROUP_SEPARATOR) const containerNameInGroup = containerNameInGroupParts.join(CONTAINER_GROUP_SEPARATOR); container.Computed.Group = groupName; container.Computed.NameInGroup = containerNameInGroup; } return container; }; export const coerceImage = (image: ContainerImage) => { let info = ""; let tag = ""; let name = ""; let registry = ""; const nameSource = image.Names || image.NamesHistory; const parts = (nameSource ? nameSource[0] || "" : "").split(":"); [info, tag] = parts; let paths = []; [registry, ...paths] = info.split("/"); name = paths.join("/"); if (!tag) { if (image.RepoTags) { const fromTag = (image.RepoTags[0] || ""); name = fromTag.slice(0, fromTag.indexOf(":")); tag = fromTag.slice(fromTag.indexOf(":") + 1); } } image.Name = registry ? name : `library/${name}`; image.Tag = tag; image.Registry = registry || "docker.io"; image.History = []; return image; }; export const coercePod = (pod: Pod) => { pod.Processes = { Processes: [], Titles: [], }; // See issue #54 - it returns null on failure pod.Containers = Array.isArray(pod.Containers) ? pod.Containers : []; return pod; } export const coerceNetwork = (it: any): Network => { return { dns_enabled: false, driver: it.Driver, id: it.Id, internal: it.Internal, ipam_options: it.IPAM as any, ipv6_enabled: it.EnabledIPv6, labels: it.Labels, name: it.Name, network_interface: "n/a", options: {}, subnets: [], created: it.Created }; } interface ApiDriverConfig<D> { timeout?: number; headers?: { [key: string]: any}; params?: URLSearchParams | D; baseURL?: string; } export class ApiDriver { private connector?: Connector; public async request<T = any, D = any>(method: string, url: string, data?: D, config?: ApiDriverConfig<D>) { if (!this.connector) { throw new Error("Connector is required"); } const request = { method, url, ...config, data } // Direct HTTP invocations where possible const reply = await Native.getInstance().proxyHTTPRequest<ContainerClientResponse<T>>(request, this.connector); return reply.result; } public async get<T = any, D = any>(url: string, config?: ApiDriverConfig<D>) { return this.request<T, D>("GET", url, undefined, config); } public async delete<T = any, D = any>(url: string, config?: ApiDriverConfig<D>) { return this.request<T, D>("DELETE", url, undefined, config); } public async head<T = any, D = any>(url: string, config?: ApiDriverConfig<D>) { return this.request<T, D>("HEAD", url, undefined, config); } public async post<T = any, D = any>(url: string, data?: D, config?: ApiDriverConfig<D>) { return this.request<T, D>("POST", url, data, config); } public async put<T = any, D = any>(url: string, data?: D, config?: ApiDriverConfig<D>) { return this.request<T, D>("PUT", url, data, config); } public async patch<T = any, D = any>(url: string, data?: D, config?: ApiDriverConfig<D>) { return this.request<T, D>("PATCH", url, data, config); } public setConnector(connector: Connector) { this.connector = connector; } } export class ContainerClient { protected dataApiDriver: ApiDriver; protected connector?: Connector; constructor() { this.dataApiDriver = new ApiDriver(); } setConnector(connector: Connector) { this.connector = connector; this.dataApiDriver.setConnector(connector); } getConnector() { return this.connector; } protected async withResult<T>(handler: () => Promise<T>) { const response = await handler(); return response; } async getDomain() { return this.withResult<Domain>(async () => { const [containers, images, machines, volumes] = await Promise.all([ this.getContainers(), this.getImages(), this.getMachines(), this.getVolumes() ]); const domain: Domain = { containers, images, machines, volumes }; return domain; }); } async getImages() { return this.withResult<ContainerImage[]>(async () => { const result = await this.dataApiDriver.get<ContainerImage[]>("/images/json"); return result.ok ? result.data.map((it) => coerceImage(it)) : []; }); } async getImage(id: string, opts?: FetchImageOptions) { return this.withResult<ContainerImage>(async () => { const params = new URLSearchParams(); const result = await this.dataApiDriver.get<ContainerImage>(`/images/${id}/json`, { params }); const image = coerceImage(result.data); if (opts?.withHistory) { image.History = await this.getImageHistory(id); } return image; }); } async getImageHistory(id: string) { return this.withResult<ContainerImageHistory[]>(async () => { const result = await this.dataApiDriver.get<ContainerImageHistory[]>(`/images/${id}/history`); return result.data; }); } async removeImage(id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.delete<boolean>(`/images/${id}`); return result.ok; }); } async pullImage(name: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/images/pull`, undefined, { params: { reference: name } }); return result.ok; }); } async pushImage(id: string, opts?: PushImageOptions) { return this.withResult<boolean>(async () => { const params: { [key: string]: string } = {}; if (opts) { if (opts.destination) { params.destination = opts.destination; } if (opts.tlsVerify === false) { params.tslVerify = "false"; } } const result = await this.dataApiDriver.post<boolean>(`/images/${id}/push`, undefined, { params }); return result.ok; }); } // container async getContainers() { return this.withResult<Container[]>(async () => { const result = await this.dataApiDriver.get<Container[]>("/containers/json", { params: { all: true } }); return result.ok ? result.data.map((it) => coerceContainer(it)) : []; }); } async getContainer(id: string, opts?: FetchContainerOptions) { return this.withResult<Container>(async () => { const result = await this.dataApiDriver.get<Container>(`/containers/${id}/json`); const container = coerceContainer(result.data); if (opts?.withLogs) { container.Logs = await this.getContainerLogs(id); } return container; }); } async getContainerLogs(id: string) { return this.withResult<string[]>(async () => { const result = await this.dataApiDriver.get<string[]>(`/containers/${id}/logs`, { params: { stdout: true, stderr: true } }); return `${result.data as any}`.trim().split("\n"); }); } async getContainerStats(id: string) { return this.withResult<ContainerStats>(async () => { const result = await this.dataApiDriver.get<ContainerStats>(`/containers/${id}/stats`, { params: { stream: false } }); return result.data; }); } async pauseContainer(id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/containers/${id}/pause`); return result.ok; }); } async unpauseContainer(id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/containers/${id}/unpause`); return result.ok; }); } async stopContainer(id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/containers/${id}/stop`); return result.ok; }); } async restartContainer(id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/containers/${id}/restart`); return result.ok; }); } async removeContainer(id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.delete<boolean>(`/containers/${id}`, { params: { force: true, v: true } }); return result.ok; }); } async createContainer(opts: CreateContainerOptions) { return this.withResult<{ created: boolean; started: boolean; }>(async () => { const creator = { image: opts.ImageId, name: opts.Name, mounts: opts.Mounts?.filter((mount) => mount.source && mount.destination).map((mount) => { return { Source: mount.source, Destination: mount.destination, Type: mount.type }; }), portmappings: opts.PortMappings?.map((mapping) => { return { protocol: mapping.protocol, container_port: mapping.container_port, host_ip: mapping.host_ip === "localhost" ? "127.0.0.1" : mapping.host_ip, host_port: mapping.host_port }; }) }; let url = "/containers/create"; if (opts.Name) { const searchParams = new URLSearchParams(); searchParams.set("name", opts.Name) url = `${url}?${searchParams.toString()}`; } const createResult = await this.dataApiDriver.post<{ Id: string }>(url, creator); const create = { created: false, started: false }; if (createResult.ok) { create.created = true; if (opts.Start) { const { Id } = createResult.data; const startResult = await this.dataApiDriver.post(`/containers/${Id}/start`); if (startResult.ok) { create.started = true; } } else { create.started = false; } } return create; }); } // Volumes async getVolumes() { return this.withResult<Volume[]>(async () => { const engine = this.connector?.engine || ""; let serviceUrl = "/volumes/json"; let processData = (input: any) => input as Volume[]; if (engine.startsWith("docker")) { serviceUrl = "/volumes"; processData = (input: any) => { const output = input.Volumes; return output as Volume[]; }; } const result = await this.dataApiDriver.get<Volume[]>(serviceUrl); return result.ok ? processData(result.data) : []; }); } async getVolume(nameOrId: string, opts?: FetchVolumeOptions) { return this.withResult<Volume>(async () => { const engine = this.connector?.engine || ""; let serviceUrl = `/volumes/${nameOrId}/json`; if (engine.startsWith("docker")) { serviceUrl = `/volumes/${nameOrId}`; } const result = await this.dataApiDriver.get<Volume>(serviceUrl); return result.data; }); } async inspectVolume(nameOrId: string) { return this.withResult<Volume>(async () => { const result = await this.dataApiDriver.get<Volume>(`/volumes/${nameOrId}/json`); return result.data; }); } async createVolume(opts: CreateVolumeOptions) { return this.withResult<Volume>(async () => { const creator = opts; const result = await this.dataApiDriver.post<Volume>("/volumes/create", creator); return result.data; }); } async removeVolume(nameOrId: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.delete<boolean>(`/volumes/${nameOrId}`, { params: { force: true } }); return result.ok; }); } async pruneVolumes(filters: any) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post("/volumes/prune", filters); return result.ok; }); } // Secrets async getSecrets() { return this.withResult<Secret[]>(async () => { const result = await this.dataApiDriver.get<Secret[]>("/secrets/json"); return result.ok ? result.data : []; }); } async getSecret(nameOrId: string, opts?: FetchSecretOptions) { return this.withResult<Secret>(async () => { const result = await this.dataApiDriver.get<Secret>(`/secrets/${nameOrId}/json`); return result.data; }); } async inspectSecret(nameOrId: string) { return this.withResult<Secret>(async () => { const result = await this.dataApiDriver.get<Secret>(`/secrets/${nameOrId}/json`); return result.data; }); } async createSecret(opts: CreateSecretOptions) { return this.withResult<Secret>(async () => { const creator = { Secret: opts.Secret }; const params: { name: string; driver?: string } = { name: opts.name }; if (opts.driver) { params.driver = opts.driver; } const result = await this.dataApiDriver.post<Secret>("/secrets/create", creator, { params }); return result.data; }); } async removeSecret(id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.delete<boolean>(`/secrets/${id}`, { params: { force: true } }); return result.ok; }); } // System async getSystemInfo() { return this.withResult<SystemInfo>(async () => { return await Native.getInstance().getSystemInfo(); }); } async pruneSystem() { return this.withResult<SystemPruneReport>(async () => { return await Native.getInstance().pruneSystem(); }); } // HTTP API // Containers async connectToContainer(item: Container) { return this.withResult<boolean>(async () => { return await Native.getInstance().connectToContainer({ id: item.Id, title: item.Name || item.Names?.[0], shell: undefined }); }); } // Controller scopes - WSL distributions, LIMA instances and podman machines async getControllerScopes() { return this.withResult<ControllerScope[]>(async () => { return await Native.getInstance().getControllerScopes(); }); } // Machines async getMachines() { return this.withResult<Machine[]>(async () => { const items = await Native.getInstance().getMachines(); return items as Machine[]; }); } async inspectMachine(Name: string) { return this.withResult<Machine>(async () => { return await Native.getInstance().inspectMachine(Name); }); } async createMachine(opts: CreateMachineOptions) { return this.withResult<Machine>(async () => { return await Native.getInstance().createMachine(opts); }); } async removeMachine(Name: string) { return this.withResult<boolean>(async () => { return await Native.getInstance().removeMachine(Name); }); } async stopMachine(Name: string) { return this.withResult<boolean>(async () => { return await Native.getInstance().stopMachine(Name); }); } async restartMachine(Name: string) { return this.withResult<boolean>(async () => { return await Native.getInstance().restartMachine(Name); }); } async connectToMachine(Name: string) { return this.withResult<boolean>(async () => { return await Native.getInstance().connectToMachine(Name); }); } // Pods async getPods() { return this.withResult<Pod[]>(async () => { const result = await this.dataApiDriver.get<Pod[]>("/pods/json", { params: { all: true } }); return result.ok ? result.data.map((it) => coercePod(it)) : []; }); } async getPod(Id: string) { return this.withResult<Pod>(async () => { const result = await this.dataApiDriver.get<Pod>(`/pods/${Id}/json`); const item = coercePod(result.data); return item; }); } async getPodProcesses(Id: string) { return this.withResult<PodProcessReport>(async () => { const result = await this.dataApiDriver.get<PodProcessReport>(`/pods/${Id}/top`); if (!result.data) { return { Processes: [], Titles: [] }; } return result.data; }); } async getPodLogs(Id: string, tail?: number) { return this.withResult<ProgramExecutionResult>(async () => { const reply = await Native.getInstance().getPodLogs(Id, tail); return reply; }); } async createPod(opts: CreatePodOptions) { return this.withResult<{ created: boolean; started: boolean; }>(async () => { const creator = { name: opts.Name, }; let url = "/pods/create"; if (opts.Name) { const searchParams = new URLSearchParams(); searchParams.set("name", opts.Name) url = `${url}?${searchParams.toString()}`; } const createResult = await this.dataApiDriver.post<{ Id: string }>(url, creator); const create = { created: false, started: false }; if (createResult.ok) { create.created = true; if (opts.Start) { const { Id } = createResult.data; const startResult = await this.dataApiDriver.post(`/pods/${Id}/start`); if (startResult.ok) { create.started = true; } } else { create.started = false; } } return create; }); } async removePod(Id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.delete<boolean>(`/pods/${Id}`, { params: { force: true, v: true } }); return result.ok; }); } async stopPod(Id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/pods/${Id}/stop`); return result.ok; }); } async restartPod(Id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/pods/${Id}/restart`); return result.ok; }); } async pausePod(Id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/pods/${Id}/pause`); return result.ok; }); } async unpausePod(Id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/pods/${Id}/unpause`); return result.ok; }); } async killPod(Id: string) { return this.withResult<boolean>(async () => { const result = await this.dataApiDriver.post<boolean>(`/pods/${Id}/kill`); return result.ok; }); } // System async resetSystem() { return this.withResult<SystemResetReport>(async () => { return await Native.getInstance().resetSystem(); }); } // Generators async generateKube(opts: GenerateKubeOptions) { return this.withResult<ProgramExecutionResult>(async () => { const reply = await Native.getInstance().generateKube(opts.entityId); return reply; }); } // Configuration globals async getGlobalUserSettings() { return this.withResult<GlobalUserSettings>(async () => { const reply = await Native.getInstance().getGlobalUserSettings(); return reply; }); } async setGlobalUserSettings(options: Partial<GlobalUserSettingsOptions>) { return this.withResult<GlobalUserSettings>(async () => { const reply = await Native.getInstance().setGlobalUserSettings(options); return reply; }); } // Configuration per engine async getEngineUserSettings(id: string) { return this.withResult<any>(async () => { const reply = await Native.getInstance().getEngineUserSettings(id); return reply; }); } async setEngineUserSettings(id: string, settings: Partial<EngineConnectorSettings>) { return this.withResult<EngineConnectorSettings>(async () => { const reply = await Native.getInstance().setEngineUserSettings(id, settings); return reply; }); } async testProgramReachability(opts: EngineProgramOptions) { return this.withResult<ProgramTestResult>(async () => { return await Native.getInstance().testProgramReachability(opts); }); } async testApiReachability(opts: EngineApiOptions) { return this.withResult<TestResult>(async () => { return await Native.getInstance().testApiReachability(opts); }); } async findProgram(opts: FindProgramOptions) { return this.withResult<Program>(async () => { return await Native.getInstance().findProgram(opts); }); } async start(opts: ConnectOptions | undefined) { return this.withResult<ApplicationDescriptor>(async () => { const descriptor = await Native.getInstance().start(opts); return descriptor; }); } // Network async getNetworks() { return this.withResult<Network[]>(async () => { if (this.connector?.adapter === ContainerAdapter.DOCKER) { const result = await this.dataApiDriver.get<Network[]>("/networks", { baseURL: "http://localhost" }); return (result.data as any[]).map(coerceNetwork); } const result = await this.dataApiDriver.get<Network[]>("/networks/json", { baseURL: "http://d/v4.0.0/libpod" }); return result.data; }); } async getNetwork(name: string) { return this.withResult<Network>(async () => { if (this.connector?.adapter === ContainerAdapter.DOCKER) { const result = await this.dataApiDriver.get<Network[]>(`/networks/${encodeURIComponent(name)}`, { baseURL: "http://localhost" }); return result.data as any; } const result = await this.dataApiDriver.get<Network>(`/networks/${encodeURIComponent(name)}/json`, { baseURL: "http://d/v4.0.0/libpod" }); return result.data; }); } async createNetwork(opts: CreateNetworkOptions) { return this.withResult<Network>(async () => { const creator = opts; if (this.connector?.adapter === ContainerAdapter.DOCKER) { const creatorDocker = { Name: creator.name, Driver: creator.driver, Internal: creator.internal, EnableIPv6: creator.ipv6_enabled, }; // TODO: Subnets const result = await this.dataApiDriver.post<Network>("/networks/create", creatorDocker, { baseURL: "http://localhost" }); if (result.ok) { const network = await this.getNetwork((result.data as any).Id); return coerceNetwork(network); } console.error("Unable to create network", result); throw new Error("Unable to create network"); } const result = await this.dataApiDriver.post<Network>("/networks/create", creator, { baseURL: "http://d/v4.0.0/libpod" }); return result.data; }); } async removeNetwork(name: string) { return this.withResult<boolean>(async () => { if (this.connector?.adapter === ContainerAdapter.DOCKER) { const result = await this.dataApiDriver.delete<Network[]>(`/networks/${encodeURIComponent(name)}`, { baseURL: "http://localhost" }); return result.ok; } const result = await this.dataApiDriver.delete<boolean>(`/networks/${encodeURIComponent(name)}`, { baseURL: "http://d/v4.0.0/libpod" }); return result.ok; }); } }
the_stack
import * as os from 'os'; import * as path from 'path'; import * as im from 'immutable'; import * as editor from '../../editor'; import * as lexical from '../lexical'; import * as _static from '../../static'; // --------------------------------------------------------------------------- export type Environment = im.Map<string, LocalBind | FunctionParam>; export const emptyEnvironment = im.Map<string, LocalBind | FunctionParam>(); export const envFromLocalBinds = ( local: Local | ObjectField | FunctionParam ): Environment => { if (isLocal(local)) { const defaultLocal: {[key: string]: LocalBind} = {}; const binds = local.binds .reduce( (acc: {[key: string]: LocalBind}, bind: LocalBind) => { acc[bind.variable.name] = bind; return acc; }, defaultLocal); return im.Map(binds); } else if (isObjectField(local)) { if (local.expr2 == null || local.id == null) { throw new Error(`INTERNAL ERROR: Object local fields can't have a null expr2 or id field`); } const bind: LocalBind = new LocalBind( local.id, local.expr2, local.methodSugar, local.ids, local.trailingComma, local.loc, ); return im.Map<string, LocalBind>().set(local.id.name, bind); } // Else, it's a `FunctionParam`, i.e., a free parameter (or a free // parameter with a default value). Either way, emit that. return im.Map<string, LocalBind | FunctionParam>().set(local.id, local); } export const envFromParams = ( params: FunctionParams ): Environment => { return params .reduce( (acc: Environment, field: FunctionParam) => { return acc.merge(envFromLocalBinds(field)); }, emptyEnvironment ); } export const envFromFields = ( fields: ObjectFields, ): Environment => { return fields .filter((field: ObjectField) => { const localKind: ObjectFieldKind = "ObjectLocal"; return field.kind === localKind; }) .reduce( (acc: Environment, field: ObjectField) => { return acc.merge(envFromLocalBinds(field)); }, emptyEnvironment ); } export const renderAsJson = (node: Node): string => { return "```\n" + JSON.stringify( node, (k, v) => { if (k === "parent") { return v == null ? "null" : (<Node>v).type; } else if (k === "env") { return v == null ? "null" : `${Object.keys(v).join(", ")}`; } else if (k === "rootObject") { return v == null ? "null" : (<Node>v).type; } else { return v; } }, " ") + "\n```"; } // --------------------------------------------------------------------------- // NodeKind captures the type of the node. Implementing this as a // union of specific strings allows us to `switch` on node type. // Additionally, specific nodes can specialize and restrict the `type` // field to be something like `type: "ObjectNode" = "ObjectNode"`, // which will cause a type error if something tries to instantiate on // `ObjectNode` with a `type` that is not this specific string. export type NodeKind = "CommentNode" | "CompSpecNode" | "ApplyNode" | "ApplyBraceNode" | "ApplyParamAssignmentNode" | "ArrayNode" | "ArrayCompNode" | "AssertNode" | "BinaryNode" | "BuiltinNode" | "ConditionalNode" | "DollarNode" | "ErrorNode" | "FunctionNode" | "FunctionParamNode" | "IdentifierNode" | "ImportNode" | "ImportStrNode" | "IndexNode" | "LocalBindNode" | "LocalNode" | "LiteralBooleanNode" | "LiteralNullNode" | "LiteralNumberNode" | "LiteralStringNode" | "ObjectFieldNode" | "ObjectNode" | "DesugaredObjectFieldNode" | "DesugaredObjectNode" | "ObjectCompNode" | "ObjectComprehensionSimpleNode" | "SelfNode" | "SuperIndexNode" | "UnaryNode" | "VarNode"; // isValueType returns true if the node is a computed value literal // (e.g., a string literal, an object literal, and so on). // // Notably, this explicitly omits structures whose value must be // computed at runtime: particularly object comprehension, array // comprehension, self, super, and function types (whose value depends // on parameter binds). export const isValueType = (node: Node): boolean => { // TODO(hausdorff): Consider adding object comprehension here, too. return isLiteralBoolean(node) || isLiteralNull(node) || isLiteralNumber(node) || isLiteralString(node) || isObjectNode(node); } // --------------------------------------------------------------------------- export interface Node { readonly type: NodeKind readonly loc: lexical.LocationRange prettyPrint(): string rootObject: Node | null; parent: Node | null; // Filled in by the visitor. env: Environment | null; // Filled in by the visitor. } export type Nodes = im.List<Node> // NodeBase is a simple abstract base class that makes sure we're // initializing the parent and env members to null. It is not exposed // to the public because it is meant to be a transparent base blass // for all `Node` implementations. abstract class NodeBase implements Node { readonly type: NodeKind readonly loc: lexical.LocationRange constructor() { this.rootObject = null; this.parent = null; this.env = null; } abstract prettyPrint: () => string; rootObject: Node | null; parent: Node | null; // Filled in by the visitor. env: Environment | null; // Filled in by the visitor. } export const isNode = (thing): thing is Node => { // TODO: Probably want to check the types of the properties instead. return thing instanceof NodeBase; } // --------------------------------------------------------------------------- // Resolve represents a resolved node, including a fully-qualified RFC // 1630/1738-compliant URI representing the absolute location of the // Jsonnet file the symbol occurs in. export class Resolve { constructor( public readonly fileUri: editor.FileUri, public readonly value: Node | IndexedObjectFields, ) {} } export const isResolve = (thing): thing is Resolve => { return thing instanceof Resolve; } // ResolutionContext represents the context we carry along as we // attempt to resolve symbols. For example, an `import` node will have // a filename, and to locate it, we will need to (1) search for the // import path relative to the current path, or (2) look in the // `libPaths` for it if necessary. This "context" is carried along in // this object. export class ResolutionContext { constructor ( public readonly compiler: _static.LexicalAnalyzerService, public readonly documents: editor.DocumentManager, public readonly currFile: editor.FileUri, ) {} public withUri = (currFile: editor.FileUri): ResolutionContext => { return new ResolutionContext(this.compiler, this.documents, currFile); } } export interface Resolvable extends NodeBase { resolve(context: ResolutionContext): Resolve | ResolveFailure } export const isResolvable = (node: NodeBase): node is Resolvable => { return node instanceof NodeBase && typeof node["resolve"] === "function"; } export interface FieldsResolvable extends NodeBase { resolveFields(context: ResolutionContext): Resolve | ResolveFailure } export const isFieldsResolvable = ( node: NodeBase ): node is FieldsResolvable => { return node instanceof NodeBase && typeof node["resolveFields"] === "function"; } export interface TypeGuessResolvable extends NodeBase { resolveTypeGuess(context: ResolutionContext): Resolve | ResolveFailure } export const isTypeGuessResolvable = ( node: NodeBase ): node is TypeGuessResolvable => { return node instanceof NodeBase && typeof node["resolveTypeGuess"] === "function"; } // --------------------------------------------------------------------------- // IdentifierName represents a variable / parameter / field name. //+gen set export type IdentifierName = string export type IdentifierNames = im.List<IdentifierName> export type IdentifierSet = im.Set<IdentifierName>; export class Identifier extends NodeBase { readonly type: "IdentifierNode" = "IdentifierNode"; constructor( readonly name: IdentifierName, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return this.name; } public resolve = (context: ResolutionContext): Resolve | ResolveFailure => { if (this.parent == null) { // An identifier with no parent is not a valid Jsonnet file. return Unresolved.Instance; } return tryResolve(this.parent, context) } } export const isIdentifier = (node): node is Identifier => { return node instanceof Identifier; } // TODO(jbeda) implement interning of IdentifierNames if necessary. The C++ // version does so. // --------------------------------------------------------------------------- export type CommentKind = "CppStyle" | "CStyle" | "HashStyle"; export interface Comment extends Node { // TODO: This Kind/Type part seems wrong, as it does in // `ObjectField`. readonly type: "CommentNode"; readonly kind: CommentKind readonly text: im.List<string> }; export type Comments = im.List<Comment>; export type BindingComment = CppComment | CComment | HashComment | null; export const isBindingComment = (node): node is BindingComment => { return isCppComment(node) || isCComment(node); } export const isComment = (node: Node): node is Comment => { const nodeType: NodeKind = "CommentNode"; return node.type === nodeType; } export class CppComment extends NodeBase implements Comment { readonly type: "CommentNode" = "CommentNode"; readonly kind: "CppStyle" = "CppStyle"; constructor( readonly text: im.List<string>, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return this.text.join(os.EOL); } } export const isCppComment = (node): node is CppComment => { return node instanceof CppComment; } export class CComment extends NodeBase implements Comment { readonly type: "CommentNode" = "CommentNode"; readonly kind: "CStyle" = "CStyle"; constructor( readonly text: im.List<string>, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return this.text.join(os.EOL); } } export const isCComment = (node): node is CComment => { return node instanceof CComment; } export class HashComment extends NodeBase implements Comment { readonly type: "CommentNode" = "CommentNode"; readonly kind: "HashStyle" = "HashStyle"; constructor( readonly text: im.List<string>, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return this.text.join(os.EOL); } } export const isHashComment = (node): node is HashComment => { return node instanceof HashComment; } // --------------------------------------------------------------------------- export type CompKind = "CompFor" | "CompIf"; export interface CompSpec extends Node { readonly type: "CompSpecNode" readonly kind: CompKind readonly varName: Identifier | null // null when kind != compSpecFor readonly expr: Node }; export type CompSpecs = im.List<CompSpec>; export const isCompSpec = (node: Node): node is CompSpec => { const nodeType: NodeKind = "CompSpecNode"; return node.type === nodeType; } export class CompSpecIf extends NodeBase implements CompSpec { readonly type: "CompSpecNode" = "CompSpecNode"; readonly kind: "CompIf" = "CompIf"; readonly varName: Identifier | null = null // null when kind != compSpecFor constructor( readonly expr: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `if ${this.expr.prettyPrint()}`; } } export const isCompSpecIf = (node): node is CompSpec => { return node instanceof CompSpecIf; } export class CompSpecFor extends NodeBase implements CompSpec { readonly type: "CompSpecNode" = "CompSpecNode"; readonly kind: "CompFor" = "CompFor"; constructor( readonly varName: Identifier, // null for `CompSpecIf` readonly expr: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `for ${this.varName.prettyPrint()} in ${this.expr.prettyPrint()}`; } } export const isCompSpecFor = (node): node is CompSpec => { return node instanceof CompSpecFor; } // --------------------------------------------------------------------------- // Apply represents a function call export class Apply extends NodeBase implements TypeGuessResolvable { readonly type: "ApplyNode" = "ApplyNode"; constructor( readonly target: Node, readonly args: Nodes, readonly trailingComma: boolean, readonly tailStrict: boolean, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const argsString = this.args .map((arg: Node) => arg.prettyPrint()) .join(", "); // NOTE: Space between `tailstrict` is important. const tailStrictString = this.tailStrict ? " tailstrict" : ""; return `${this.target.prettyPrint()}(${argsString}${tailStrictString})`; } public resolveTypeGuess = ( context: ResolutionContext ): Resolve | ResolveFailure => { if (!isResolvable(this.target)) { return Unresolved.Instance; } const fn = this.target.resolve(context); if (!isResolvedFunction(fn) || !isObjectField(fn.functionNode)) { return Unresolved.Instance; } const body = fn.functionNode.expr2; if (isBinary(body) && body.op == "BopPlus" && isSelf(body.left)) { return body.left.resolve(context); } return Unresolved.Instance; } } export const isApply = (node): node is Apply => { return node instanceof Apply; } export class ApplyParamAssignment extends NodeBase { readonly type: "ApplyParamAssignmentNode" = "ApplyParamAssignmentNode"; constructor( readonly id: IdentifierName, readonly right: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `${this.id}=${this.right.prettyPrint()}`; } } export type ApplyParamAssignments = im.List<ApplyParamAssignment> export const isApplyParamAssignment = (node): node is ApplyParamAssignment => { return node instanceof ApplyParamAssignment; }; // --------------------------------------------------------------------------- // ApplyBrace represents e { }. Desugared to e + { }. export class ApplyBrace extends NodeBase { readonly type: "ApplyBraceNode" = "ApplyBraceNode"; constructor( readonly left: Node, readonly right: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `${this.left.prettyPrint()} ${this.right.prettyPrint()}`; } } export const isApplyBrace = (node): node is ApplyBrace => { return node instanceof ApplyBrace; } // --------------------------------------------------------------------------- // Array represents array constructors [1, 2, 3]. export class Array extends NodeBase { readonly type: "ArrayNode" = "ArrayNode"; constructor( readonly elements: Nodes, readonly trailingComma: boolean, readonly headingComment: Comment | null, readonly trailingComment: Comment | null, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const elementsString = this.elements .map((element: Node) => element.prettyPrint()) .join(", "); return `[${elementsString}]`; } } export const isArray = (node): node is Array => { return node instanceof Array; } // --------------------------------------------------------------------------- // ArrayComp represents array comprehensions (which are like Python list // comprehensions) export class ArrayComp extends NodeBase { readonly type: "ArrayCompNode" = "ArrayCompNode"; constructor( readonly body: Node, readonly trailingComma: boolean, readonly specs: CompSpecs, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const specsString = this.specs .map((spec: CompSpec) => spec.prettyPrint()) .join(", "); return `[${specsString} ${this.body.prettyPrint()}]`; } } export const isArrayComp = (node): node is ArrayComp => { return node instanceof ArrayComp; } // --------------------------------------------------------------------------- // Assert represents an assert expression (not an object-level assert). // // After parsing, message can be nil indicating that no message was // specified. This AST is elimiated by desugaring. export class Assert extends NodeBase { readonly type: "AssertNode" = "AssertNode"; constructor( readonly cond: Node, readonly message: Node | null, readonly rest: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `assert ${this.cond.prettyPrint()}`; } } export const isAssert = (node): node is Assert => { return node instanceof Assert; } // --------------------------------------------------------------------------- export type BinaryOp = "BopMult" | "BopDiv" | "BopPercent" | "BopPlus" | "BopMinus" | "BopShiftL" | "BopShiftR" | "BopGreater" | "BopGreaterEq" | "BopLess" | "BopLessEq" | "BopManifestEqual" | "BopManifestUnequal" | "BopBitwiseAnd" | "BopBitwiseXor" | "BopBitwiseOr" | "BopAnd" | "BopOr"; const BopStrings = { BopMult: "*", BopDiv: "/", BopPercent: "%", BopPlus: "+", BopMinus: "-", BopShiftL: "<<", BopShiftR: ">>", BopGreater: ">", BopGreaterEq: ">=", BopLess: "<", BopLessEq: "<=", BopManifestEqual: "==", BopManifestUnequal: "!=", BopBitwiseAnd: "&", BopBitwiseXor: "^", BopBitwiseOr: "|", BopAnd: "&&", BopOr: "||", }; export const BopMap = im.Map<string, BinaryOp>({ "*": "BopMult", "/": "BopDiv", "%": "BopPercent", "+": "BopPlus", "-": "BopMinus", "<<": "BopShiftL", ">>": "BopShiftR", ">": "BopGreater", ">=": "BopGreaterEq", "<": "BopLess", "<=": "BopLessEq", "==": "BopManifestEqual", "!=": "BopManifestUnequal", "&": "BopBitwiseAnd", "^": "BopBitwiseXor", "|": "BopBitwiseOr", "&&": "BopAnd", "||": "BopOr", }); // Binary represents binary operators. export class Binary extends NodeBase implements FieldsResolvable { readonly type: "BinaryNode" = "BinaryNode"; constructor( readonly left: Node, readonly op: BinaryOp, readonly right: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const leftString = this.left.prettyPrint(); const opString = BopStrings[this.op]; const rightString = this.right.prettyPrint(); return `${leftString} ${opString} ${rightString}`; } public resolveFields = ( context: ResolutionContext, ): Resolve | ResolveFailure => { // Recursively merge fields if it's another mixin; if it's an // object, return fields; else, no fields to return. if (this.op !== "BopPlus") { return Unresolved.Instance; } const left = tryResolveIndirections(this.left, context); if (isResolveFailure(left) || !isIndexedObjectFields(left.value)) { return Unresolved.Instance; } const right = tryResolveIndirections(this.right, context); if (isResolveFailure(right) || !isIndexedObjectFields(right.value)) { return Unresolved.Instance; } let merged = left.value; right.value.forEach( (v: ObjectField, k: string) => { // TODO(hausdorff): Account for syntax sugar here. For // example: // // `{foo: "bar"} + {foo+: "bar"}` // // should produce `{foo: "barbar"} but because we are merging // naively, we will report the value as simply `"bar"`. The // reason we have punted for now is mainly that we have to // implement an ad hoc version of Jsonnet's type coercion. merged = merged.set(k, v); }); return new Resolve(context.currFile, merged); } } export const isBinary = (node): node is Binary => { return node instanceof Binary; } // --------------------------------------------------------------------------- // Builtin represents built-in functions. // // There is no parse rule to build this AST. Instead, it is used to build the // std object in the interpreter. export class Builtin extends NodeBase { readonly type: "BuiltinNode" = "BuiltinNode"; constructor( readonly id: number, readonly params: IdentifierNames, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const paramsString = this.params.join(", "); return `std.${this.id}(${paramsString})`; } } export const isBuiltin = (node): node is Builtin => { return node instanceof Builtin; } // --------------------------------------------------------------------------- // Conditional represents if/then/else. // // After parsing, branchFalse can be nil indicating that no else branch // was specified. The desugarer fills this in with a LiteralNull export class Conditional extends NodeBase { readonly type: "ConditionalNode" = "ConditionalNode"; constructor( readonly cond: Node, readonly branchTrue: Node, readonly branchFalse: Node | null, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const trueClause = `then ${this.branchTrue.prettyPrint()}`; const falseClause = this.branchFalse == null ? "" : `else ${this.branchFalse.prettyPrint()}`; return `if ${this.cond.prettyPrint()} ${trueClause} ${falseClause}`; } } export const isConditional = (node): node is Conditional => { return node instanceof Conditional; } // --------------------------------------------------------------------------- // Dollar represents the $ keyword export class Dollar extends NodeBase implements Resolvable { readonly type: "DollarNode" = "DollarNode"; constructor( readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `$`; } public resolve = (context: ResolutionContext): Resolve | ResolveFailure => { if (this.rootObject == null) { return Unresolved.Instance; } return new Resolve(context.currFile, this.rootObject); } }; export const isDollar = (node): node is Dollar => { return node instanceof Dollar; } // --------------------------------------------------------------------------- // Error represents the error e. export class ErrorNode extends NodeBase { readonly type: "ErrorNode" = "ErrorNode"; constructor( readonly expr: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `error ${this.expr.prettyPrint()}`; } } export const isError = (node): node is ErrorNode => { return node instanceof ErrorNode; } // --------------------------------------------------------------------------- // Function represents a function call. (jbeda: or is it function defn?) export class Function extends NodeBase { readonly type: "FunctionNode" = "FunctionNode"; constructor( readonly parameters: FunctionParams, readonly trailingComma: boolean, readonly body: Node, readonly headingComment: BindingComment, readonly trailingComment: Comments, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const params = this.parameters .map((param: FunctionParam) => param.prettyPrint()) .join(", "); return `function (${params}) ${this.body.prettyPrint()}`; } } export const isFunction = (node): node is Function => { return node instanceof Function; } export class FunctionParam extends NodeBase { readonly type: "FunctionParamNode" = "FunctionParamNode"; constructor( readonly id: IdentifierName, readonly defaultValue: Node | null, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const defaultValueString = this.defaultValue == null ? "" : `=${this.defaultValue.prettyPrint()}`; return `(parameter) ${this.id}${defaultValueString}`; } } export type FunctionParams = im.List<FunctionParam> export const isFunctionParam = (node): node is FunctionParam => { return node instanceof FunctionParam; } // --------------------------------------------------------------------------- // Import represents import "file". export class Import extends NodeBase implements Resolvable { readonly type: "ImportNode" = "ImportNode"; constructor( readonly file: string, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `import "${this.file}"`; } public resolve = (context: ResolutionContext): Resolve | ResolveFailure => { const {text: docText, version: version, resolvedPath: fileUri} = context.documents.get(this); const cached = context.compiler.cache(fileUri, docText, version); if (_static.isFailedParsedDocument(cached)) { return Unresolved.Instance; } let resolved = cached.parse; // If the var was pointing at an import, then resolution probably // has `local` definitions at the top of the file. Get rid of // them, since they are not useful for resolving the index // identifier. while (isLocal(resolved)) { resolved = resolved.body; } return new Resolve(fileUri, resolved); } } export const isImport = (node): node is Import => { return node instanceof Import; } // --------------------------------------------------------------------------- // ImportStr represents importstr "file". export class ImportStr extends NodeBase { readonly type: "ImportStrNode" = "ImportStrNode"; constructor( readonly file: string, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `importstr "${this.file}"`; } } export const isImportStr = (node): node is ImportStr => { return node instanceof ImportStr; } // --------------------------------------------------------------------------- // Index represents both e[e] and the syntax sugar e.f. // // One of index and id will be nil before desugaring. After desugaring id // will be nil. export interface Index extends Node, Resolvable { readonly type: "IndexNode" readonly target: Node readonly index: Node | null readonly id: Identifier | null } const resolveIndex = ( index: Index, context: ResolutionContext, ): Resolve | ResolveFailure => { if ( index.target == null || (!isResolvable(index.target) && !isFieldsResolvable(index.target) && !isTypeGuessResolvable(index.target)) ) { throw new Error( `INTERNAL ERROR: Index node must have a resolvable target:\n${renderAsJson(index)}`); } else if (index.id == null) { return Unresolved.Instance; } // Find root target, look up in environment. let resolvedTarget = tryResolveIndirections(index.target, context); if (isResolveFailure(resolvedTarget)) { return new UnresolvedIndexTarget(index); } else if (!isIndexedObjectFields(resolvedTarget.value)) { return new UnresolvedIndexTarget(index); } const filtered = resolvedTarget.value.filter((field: ObjectField) => { return field.id != null && index.id != null && field.id.name == index.id.name; }); if (filtered.count() == 0) { return new UnresolvedIndexId(index, resolvedTarget.value); } else if (filtered.count() != 1) { throw new Error( `INTERNAL ERROR: Object contained multiple fields with name '${index.id.name}'}`); } const field = filtered.first(); if (field.methodSugar) { return new ResolvedFunction(field); } else if (field.expr2 == null) { throw new Error( `INTERNAL ERROR: Object field can't have null property expr2:\n${renderAsJson(field)}'}`); } return new Resolve(context.currFile, field.expr2); } export const isIndex = (node: Node): node is Index => { const nodeType: NodeKind = "IndexNode"; return node.type === nodeType; } export class IndexSubscript extends NodeBase implements Index { readonly type: "IndexNode" = "IndexNode"; readonly id: Identifier | null = null; constructor( readonly target: Node, readonly index: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `${this.target.prettyPrint()}[${this.index.prettyPrint()}]`; } public resolve = (context: ResolutionContext): Resolve | ResolveFailure => resolveIndex(this, context); } export const isIndexSubscript = (node): node is Index => { return node instanceof IndexSubscript; } export class IndexDot extends NodeBase implements Index { readonly type: "IndexNode" = "IndexNode"; readonly index: Node | null = null; constructor( readonly target: Node, readonly id: Identifier, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `${this.target.prettyPrint()}.${this.id.prettyPrint()}`; } public resolve = (context: ResolutionContext): Resolve | ResolveFailure => resolveIndex(this, context); } export const isIndexDot = (node): node is Index => { return node instanceof IndexDot; } // --------------------------------------------------------------------------- // LocalBind is a helper struct for Local export class LocalBind extends NodeBase { readonly type: "LocalBindNode" = "LocalBindNode"; constructor( readonly variable: Identifier, readonly body: Node, readonly functionSugar: boolean, readonly params: FunctionParams, // if functionSugar is true readonly trailingComma: boolean, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const idString = this.variable.prettyPrint(); if (this.functionSugar) { const paramsString = this.params .map((param: FunctionParam) => param.id) .join(", "); return `${idString}(${paramsString})`; } return `${idString} = ${this.body.prettyPrint()}`; } } export type LocalBinds = im.List<LocalBind> export const isLocalBind = (node): node is LocalBind => { return node instanceof LocalBind; } // Local represents local x = e; e. After desugaring, functionSugar is false. export class Local extends NodeBase { readonly type: "LocalNode" = "LocalNode"; constructor( readonly binds: LocalBinds, readonly body: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const bindsString = this.binds .map((bind: LocalBind) => bind.prettyPrint()) .join(",\n "); return `local ${bindsString}`; } } export const isLocal = (node): node is Local => { return node instanceof Local; } // --------------------------------------------------------------------------- // LiteralBoolean represents true and false export class LiteralBoolean extends NodeBase { readonly type: "LiteralBooleanNode" = "LiteralBooleanNode"; constructor( readonly value: boolean, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `${this.value}`; } } export const isLiteralBoolean = (node): node is LiteralBoolean => { return node instanceof LiteralBoolean; } // --------------------------------------------------------------------------- // LiteralNull represents the null keyword export class LiteralNull extends NodeBase { readonly type: "LiteralNullNode" = "LiteralNullNode"; constructor( readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `null`; } } export const isLiteralNull = (node): node is LiteralNull => { return node instanceof LiteralNull; } // --------------------------------------------------------------------------- // LiteralNumber represents a JSON number export class LiteralNumber extends NodeBase { readonly type: "LiteralNumberNode" = "LiteralNumberNode"; constructor( readonly value: number, readonly originalString: string, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `${this.originalString}`; } } export const isLiteralNumber = (node): node is LiteralNumber => { return node instanceof LiteralNumber; } // --------------------------------------------------------------------------- export type LiteralStringKind = "StringSingle" | "StringDouble" | "StringBlock"; // LiteralString represents a JSON string export interface LiteralString extends Node { readonly type: "LiteralStringNode" readonly value: string readonly kind: LiteralStringKind readonly blockIndent: string } export const isLiteralString = (node: Node): node is LiteralString => { const nodeType: NodeKind = "LiteralStringNode"; return node.type === nodeType; } export class LiteralStringSingle extends NodeBase implements LiteralString { readonly type: "LiteralStringNode" = "LiteralStringNode"; readonly kind: "StringSingle" = "StringSingle"; readonly blockIndent: "" = ""; constructor( readonly value: string, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `'${this.value}'`; } } export const isLiteralStringSingle = (node): node is LiteralStringSingle => { return node instanceof LiteralStringSingle; } export class LiteralStringDouble extends NodeBase implements LiteralString { readonly type: "LiteralStringNode" = "LiteralStringNode"; readonly kind: "StringDouble" = "StringDouble"; readonly blockIndent: "" = ""; constructor( readonly value: string, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `"${this.value}"`; } } export const isLiteralStringDouble = (node): node is LiteralString => { return node instanceof LiteralStringDouble; } export class LiteralStringBlock extends NodeBase implements LiteralString { readonly type: "LiteralStringNode" = "LiteralStringNode"; readonly kind: "StringBlock" = "StringBlock"; constructor( readonly value: string, readonly blockIndent: string, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `|||${this.value}|||`; } } export const isLiteralStringBlock = (node): node is LiteralStringBlock => { return node instanceof LiteralStringBlock; } // --------------------------------------------------------------------------- export type ObjectFieldKind = "ObjectAssert" | // assert expr2 [: expr3] where expr3 can be nil "ObjectFieldID" | // id:[:[:]] expr2 "ObjectFieldExpr" | // '['expr1']':[:[:]] expr2 "ObjectFieldStr" | // expr1:[:[:]] expr2 "ObjectLocal"; // local id = expr2 export type ObjectFieldHide = "ObjectFieldHidden" | // f:: e "ObjectFieldInherit" | // f: e "ObjectFieldVisible"; // f::: e const objectFieldHideStrings = im.Map<ObjectFieldHide, string>({ "ObjectFieldHidden": "::", "ObjectFieldInherit": ":", "ObjectFieldVisible": ":::", }); // export interface ObjectField extends NodeBase { // readonly type: "ObjectFieldNode" // readonly kind: ObjectFieldKind // readonly hide: ObjectFieldHide // (ignore if kind != astObjectField*) // readonly superSugar: boolean // +: (ignore if kind != astObjectField*) // readonly methodSugar: boolean // f(x, y, z): ... (ignore if kind == astObjectAssert) // readonly expr1: Node | null // Not in scope of the object // readonly id: Identifier | null // readonly ids: FunctionParams // If methodSugar == true then holds the params. // readonly trailingComma: boolean // If methodSugar == true then remembers the trailing comma // readonly expr2: Node | null // In scope of the object (can see self). // readonly expr3: Node | null // In scope of the object (can see self). // readonly headingComments: Comments // } export class ObjectField extends NodeBase { readonly type: "ObjectFieldNode" = "ObjectFieldNode"; constructor( readonly kind: ObjectFieldKind, readonly hide: ObjectFieldHide, // (ignore if kind != astObjectField*) readonly superSugar: boolean, // +: (ignore if kind != astObjectField*) readonly methodSugar: boolean, // f(x, y, z): ... (ignore if kind == astObjectAssert) readonly expr1: Node | null, // Not in scope of the object readonly id: Identifier | null, readonly ids: FunctionParams, // If methodSugar == true then holds the params. readonly trailingComma: boolean, // If methodSugar == true then remembers the trailing comma readonly expr2: Node | null, // In scope of the object (can see self). readonly expr3: Node | null, // In scope of the object (can see self). readonly headingComments: BindingComment, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { switch (this.kind) { case "ObjectAssert": return prettyPrintObjectAssert(this); case "ObjectFieldID": return prettyPrintObjectFieldId(this); case "ObjectLocal": return prettyPrintObjectLocal(this); case "ObjectFieldExpr": case "ObjectFieldStr": default: throw new Error(`INTERNAL ERROR: Unrecognized object field kind '${this.kind}':\n${renderAsJson(this)}`); } } } export const isObjectField = (node): node is ObjectField => { return node instanceof ObjectField; } const prettyPrintObjectAssert = (field: ObjectField): string => { if (field.expr2 == null) { throw new Error(`INTERNAL ERROR: object 'assert' must have expression to assert:\n${renderAsJson(field)}`); } return field.expr3 == null ? `assert ${field.expr2.prettyPrint()}` : `assert ${field.expr2.prettyPrint()} : ${field.expr3.prettyPrint()}`; } const prettyPrintObjectFieldId = (field: ObjectField): string => { if (field.id == null) { throw new Error(`INTERNAL ERROR: object field must have id:\n${renderAsJson(field)}`); } const idString = field.id.prettyPrint(); const hide = objectFieldHideStrings.get(field.hide); if (field.methodSugar) { const argsList = field.ids .map((param: FunctionParam) => param.id) .join(", "); return `(method) ${idString}(${argsList})${hide}`; } return `(field) ${idString}${hide}`; } const prettyPrintObjectLocal = (field: ObjectField): string => { if (field.id == null) { throw new Error(`INTERNAL ERROR: object field must have id:\n${renderAsJson(field)}`); } const idString = field.id.prettyPrint(); if (field.methodSugar) { const argsList = field.ids .map((param: FunctionParam) => param.id) .join(", "); return `(method) local ${idString}(${argsList})`; } return `(field) local ${idString}`; } // TODO(jbeda): Add the remaining constructor helpers here export type ObjectFields = im.List<ObjectField>; export type IndexedObjectFields = im.Map<string, ObjectField>; // NOTE: Type parameters are erased at runtime, so we can't check them // here. export const isIndexedObjectFields = (thing): thing is IndexedObjectFields => { return im.Map.isMap(thing); } export const indexFields = (fields: ObjectFields): IndexedObjectFields => { return fields .reduce(( acc: im.Map<string, ObjectField>, field: ObjectField ) => { return field.id != null && acc.set(field.id.name, field) || acc; }, im.Map<string, ObjectField>() ); } // --------------------------------------------------------------------------- // Object represents object constructors { f: e ... }. // // The trailing comma is only allowed if len(fields) > 0. Converted to // DesugaredObject during desugaring. export class ObjectNode extends NodeBase implements FieldsResolvable { readonly type: "ObjectNode" = "ObjectNode"; constructor( readonly fields: ObjectFields, readonly trailingComma: boolean, readonly headingComments: BindingComment, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { const fields = this.fields .filter((field: ObjectField) => field.kind === "ObjectFieldID") .map((field: ObjectField) => ` ${field.prettyPrint()}`) .join(",\n"); return `(module) {\n${fields}\n}`; } public resolveFields = ( context: ResolutionContext, ): Resolve | ResolveFailure => { return new Resolve(context.currFile, indexFields(this.fields)); } } export const isObjectNode = (node): node is ObjectNode => { return node instanceof ObjectNode; } // --------------------------------------------------------------------------- export interface DesugaredObjectField extends NodeBase { readonly type: "DesugaredObjectFieldNode" readonly hide: ObjectFieldHide readonly name: Node readonly body: Node } export type DesugaredObjectFields = im.List<DesugaredObjectField>; // DesugaredObject represents object constructors { f: e ... } after // desugaring. // // The assertions either return true or raise an error. export interface DesugaredObject extends NodeBase { readonly type: "DesugaredObjectNode" readonly asserts: Nodes readonly fields: DesugaredObjectFields } export const isDesugaredObject = (node: Node): node is DesugaredObject => { const nodeType: NodeKind = "DesugaredObjectNode"; return node.type === nodeType; } // --------------------------------------------------------------------------- // ObjectComp represents object comprehension // { [e]: e for x in e for.. if... }. // export interface ObjectComp extends NodeBase { // readonly type: "ObjectCompNode" // readonly fields: ObjectFields // readonly trailingComma: boolean // readonly specs: CompSpecs // } export class ObjectComp extends NodeBase { readonly type: "ObjectCompNode" = "ObjectCompNode"; constructor( readonly fields: ObjectFields, readonly trailingComma: boolean, readonly specs: CompSpecs, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `[OBJECT COMP]` } } export const isObjectComp = (node): node is ObjectComp => { return node instanceof ObjectComp; } // --------------------------------------------------------------------------- // ObjectComprehensionSimple represents post-desugaring object // comprehension { [e]: e for x in e }. // // TODO: Rename this to `ObjectCompSimple` export interface ObjectComprehensionSimple extends NodeBase { readonly type: "ObjectComprehensionSimpleNode" readonly field: Node readonly value: Node readonly id: Identifier readonly array: Node } export const isObjectComprehensionSimple = ( node: Node ): node is ObjectComprehensionSimple => { const nodeType: NodeKind = "ObjectComprehensionSimpleNode"; return node.type === nodeType; } // --------------------------------------------------------------------------- // Self represents the self keyword. export class Self extends NodeBase implements Resolvable { readonly type: "SelfNode" = "SelfNode"; constructor( readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `self`; } public resolve = (context: ResolutionContext): Resolve | ResolveFailure => { let curr: Node | null = this; while (true) { if (curr == null || curr.parent == null) { return Unresolved.Instance } if (isObjectNode(curr)) { return curr.resolveFields(context); } curr = curr.parent; } } }; export const isSelf = (node): node is Self => { return node instanceof Self; } // --------------------------------------------------------------------------- // SuperIndex represents the super[e] and super.f constructs. // // Either index or identifier will be set before desugaring. After desugaring, id will be // nil. export class SuperIndex extends NodeBase { readonly type: "SuperIndexNode" = "SuperIndexNode"; constructor( readonly index: Node | null, readonly id: Identifier | null, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { if (this.id != null) { return `super.${this.id.prettyPrint()}`; } else if (this.index != null) { return `super[${this.index.prettyPrint()}]` } throw new Error(`INTERNAL ERROR: Can't pretty-print super index if both 'id' and 'index' fields are null`); } } export const isSuperIndex = (node): node is SuperIndex => { return node instanceof SuperIndex; } // --------------------------------------------------------------------------- export type UnaryOp = "UopNot" | "UopBitwiseNot" | "UopPlus" | "UopMinus"; export const UopStrings = { UopNot: "!", UopBitwiseNot: "~", UopPlus: "+", UopMinus: "-", }; export const UopMap = im.Map<string, UnaryOp>({ "!": "UopNot", "~": "UopBitwiseNot", "+": "UopPlus", "-": "UopMinus", }); // Unary represents unary operators. export class Unary extends NodeBase { readonly type: "UnaryNode" = "UnaryNode"; constructor( readonly op: UnaryOp, readonly expr: Node, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return `${UopStrings[this.op]}${this.expr.prettyPrint()}`; } } export const isUnary = (node): node is Unary => { return node instanceof Unary; } // --------------------------------------------------------------------------- // Var represents variables. export class Var extends NodeBase implements Resolvable { readonly type: "VarNode" = "VarNode"; constructor( readonly id: Identifier, readonly loc: lexical.LocationRange, ) { super(); } public prettyPrint = (): string => { return this.id.prettyPrint(); } public resolve = (context: ResolutionContext): Resolve | ResolveFailure => { // Look up in the environment, get docs for that definition. if (this.env == null) { throw new Error( `INTERNAL ERROR: AST improperly set up, property 'env' can't be null:\n${renderAsJson(this)}`); } else if (!this.env.has(this.id.name)) { return Unresolved.Instance; } return resolveFromEnv(this.id.name, this.env, context); } } export const isVar = (node): node is Var => { return node instanceof Var; } // --------------------------------------------------------------------------- const resolveFromEnv = ( idName: string, env: Environment, context: ResolutionContext, ): Resolve | ResolveFailure => { const bind = env.get(idName); if (bind == null) { return Unresolved.Instance; } if (isFunctionParam(bind)) { // A function param is either a free variable, or it has a default // value. We consider both of these to be free variables, since we // would not know the value until the function was applied. return new ResolvedFreeVar(bind); } if (bind.body == null) { throw new Error(`INTERNAL ERROR: Bind can't have null body:\n${bind}`); } return tryResolve(bind.body, context); } const tryResolve = ( node: Node, context: ResolutionContext, ): Resolve | ResolveFailure => { if (isFunction(node)) { return new ResolvedFunction(node); } else if (isResolvable(node)) { return node.resolve(context); } else if (isFieldsResolvable(node)) { // Found an object or perhaps an object mixin. Break. return node.resolveFields(context); } else if (isValueType(node)) { return new Resolve(context.currFile, node); } else { return Unresolved.Instance; } } export const tryResolveIndirections = ( node: Node, context: ResolutionContext, ): Resolve | ResolveFailure => { // This loop will try to "strip out the indirections" of an // argument to a mixin. For example, consider the expression // `foo1.bar + foo2.bar` in the following example: // // local bar1 = {a: 1, b: 2}, // local bar2 = {b: 3, c: 4}, // local foo1 = {bar: bar1}, // local foo2 = {bar: bar2}, // useMerged: foo1.bar + foo2.bar, // // In this case, if we try to resolve `foo1.bar + foo2.bar`, we // will first need to resolve `foo1.bar`, and then the value of // that resolve, `bar1`, which resolves to an object, and so on. // // This loop follows these indirections: first, it resolves // `foo1.bar`, and then `bar1`, before encountering an object // and stopping. let resolved: Resolve | ResolveFailure = new Resolve(context.currFile, node); while (true) { if (isResolveFailure(resolved)) { return resolved; } else if (isIndexedObjectFields(resolved.value)) { // We've resolved to a set of fields. Return. return resolved; } else if (isResolvable(resolved.value)) { resolved = resolved.value.resolve(context.withUri(resolved.fileUri)); } else if (isFieldsResolvable(resolved.value)) { resolved = resolved.value.resolveFields(context.withUri(resolved.fileUri)); } else if (isTypeGuessResolvable(resolved.value)) { resolved = resolved.value.resolveTypeGuess(context.withUri(resolved.fileUri)); } else if (isValueType(resolved.value)) { // We've resolved to a value. Return. return resolved; } else { return Unresolved.Instance; } } } // --------------------------------------------------------------------------- // Failures. // --------------------------------------------------------------------------- // ResolveFailure represents a failure to resolve a symbol to a "value // type", for our particular definition of that term, which is // captured by `isValueType`. // // For example, a symbol might refer to a function, which we would not // consider a "value type", and hence we would return a // `ResolveFailure`. export type ResolveFailure = ResolvedFunction | ResolvedFreeVar | // Resolved to uncompletable nodes. UnresolvedIndexId | UnresolvedIndexTarget | // Failed to resolve `Index` node. Unresolved; // Misc. export const isResolveFailure = (thing): thing is ResolveFailure => { return thing instanceof ResolvedFunction || thing instanceof ResolvedFreeVar || thing instanceof UnresolvedIndexId || thing instanceof UnresolvedIndexTarget || thing instanceof Unresolved; } // ResolvedFunction represents the event that we have tried to resolve // a symbol to a "value type" (as defined by `isValueType`), but // failed since that value depends on the resolution of a function, // which cannot be resolved to a value type without binding the // parameters. export class ResolvedFunction { constructor( public readonly functionNode: Function | ObjectField | LocalBind ) {} }; export const isResolvedFunction = (thing): thing is ResolvedFunction => { return thing instanceof ResolvedFunction; } // ResolvedFreeVar represents the event that we have tried to resolve // a value to a "value type" (as defined by `isValueType`), but failed // since that value is a free parameter, and must be bound at runtime // to be computed. // // A good example of such a situation is `self`, `super`, and // function parameters. export class ResolvedFreeVar { constructor(public readonly variable: Var | FunctionParam) {} }; export const isResolvedFreeVar = (thing): thing is ResolvedFreeVar => { return thing instanceof ResolvedFreeVar; } export type UnresolvedIndex = UnresolvedIndexTarget | UnresolvedIndexId; export const isUnresolvedIndex = (thing): thing is UnresolvedIndex => { return thing instanceof UnresolvedIndexTarget || thing instanceof UnresolvedIndexId; } // UnresolvedIndexTarget represents a failure to resolve an `Index` // node because the target has failed to resolve. // // For example, in `foo.bar.baz`, failure to resolve either `foo` or // `bar`, would result in an `UnresolvedIndexTarget`. // // NOTE: If `bar` fails to resolve, then we will still report an // `UnresolvedIndexTarget`, since `bar` is the target of `bar.baz`. export class UnresolvedIndexTarget { constructor( public readonly index: Index, ) {} } export const isUnresolvedIndexTarget = (thing): thing is UnresolvedIndexTarget => { return thing instanceof UnresolvedIndexTarget; } // UnresolvedIndexId represents a failure to resolve the ID of an // `Index` node. // // For example, in `foo.bar.baz`, `baz` is the ID, hence failing to // resolve `baz` will result in this error. // // NOTE: Only `baz` can cause an `UnresolvedIndexId` failure in this // example. The reason failing to resolve `bar` doesn't cause an // `UnresolvedIndexId` is because `bar` is the target in `bar.baz`. export class UnresolvedIndexId { constructor( public readonly index: Index, public readonly resolvedTarget: IndexedObjectFields, ) {} } export const isUnresolvedIndexId = (thing): thing is UnresolvedIndexId => { return thing instanceof UnresolvedIndexId; } // Unresolved represents a miscelleneous failure to resolve a symbol. // Typically this occurs the structure of the AST is not amenable to // static analysis, and we simply punt. // // TODO: Expand this to more cases as `onComplete` features require it. export class Unresolved { public static readonly Instance = new Unresolved(); // NOTE: This is a work around for a bug in the TypeScript type // checker. We have not had time to report this bug, but when this // line is commented out, then use of `isResolveFailure` will cause // the type we're checking to resolve to `never` (TypeScript's // bottom type), which causes compile to fail. private readonly foo = "foo"; } export const isUnresolved = (thing): thing is Unresolved => { return thing instanceof Unresolved; }
the_stack
import ffi from "ffi"; import Struct from "ref-struct"; import { Stores } from "../schema/stores"; import { KotsApp } from "./"; import { Params } from "../server/params"; import { putObject } from "../util/s3"; import path from "path"; import tmp from "tmp"; import fs from "fs"; import { extractDownstreamNamesFromTarball, extractInstallationSpecFromTarball, extractPreflightSpecFromTarball, extractSupportBundleSpecFromTarball, extractAppSpecFromTarball, extractKotsAppSpecFromTarball, extractAppTitleFromTarball, extractAppIconFromTarball, extractKotsAppLicenseFromTarball, extractAnalyzerSpecFromTarball, extractConfigSpecFromTarball, extractConfigValuesFromTarball, extractBackupSpecFromTarball, } from "../util/tar"; import { KotsAppRegistryDetails } from "../kots_app" import { Cluster } from "../cluster"; import * as _ from "lodash"; import yaml from "js-yaml"; import { StatusServer } from "../airgap/status"; import { getDiffSummary } from "../util/utilities"; import { ReplicatedError } from "../server/errors"; import { createGitCommitForVersion } from "./gitops"; const GoString = Struct({ p: "string", n: "longlong" }); const GoBool = "bool"; function kots() { return ffi.Library("/lib/kots.so", { TestRegistryCredentials: ["void", [GoString, GoString, GoString, GoString, GoString]], UpdateCheck: ["void", [GoString, GoString, GoString]], UpdateDownload: ["void", [GoString, GoString, GoString, GoString, GoString]], UpdateDownloadFromAirgap: ["void", [GoString, GoString, GoString, GoString, GoString]], RewriteVersion: ["void", [GoString, GoString, GoString, GoString, GoString, GoString, GoBool, GoBool, GoString]], TemplateConfig: [GoString, [GoString, GoString, GoString, GoString]], EncryptString: [GoString, [GoString, GoString]], DecryptString: [GoString, [GoString, GoString]], RenderFile: ["void", [GoString, GoString, GoString, GoString]], }); } export interface Update { cursor: string; versionLabel: string; } export async function kotsAppDownloadUpdates(updatesAvailable: Update[], app: KotsApp, stores: Stores): Promise<void> { const registryInfo = await stores.kotsAppStore.getAppRegistryDetails(app.id); for (let i = 0; i < updatesAvailable.length; i++) { const update = updatesAvailable[i]; try { await stores.kotsAppStore.setUpdateDownloadStatus(`Downloading release ${update.versionLabel}`, "running"); await kotsAppDownloadUpdate(update.cursor, app, registryInfo, stores); } catch (err) { if (i === updatesAvailable.length - 1) { console.error(`Failed to download release ${update.cursor}: ${err}`); throw err; } } } } export async function kotsAppDownloadUpdate(cursor: string, app: KotsApp, registryInfo: KotsAppRegistryDetails, stores: Stores): Promise<boolean> { // We need to include the last archive because if there is an update, the ffi function will update it const tmpDir = tmp.dirSync(); const archive = path.join(tmpDir.name, "archive.tar.gz"); try { fs.writeFileSync(archive, await app.getArchive("" + (app.currentSequence!))); const namespace = getK8sNamespace(); const statusServer = new StatusServer(); await statusServer.start(tmpDir.name); const socketParam = new GoString(); socketParam["p"] = statusServer.socketFilename; socketParam["n"] = statusServer.socketFilename.length; const archiveParam = new GoString(); archiveParam["p"] = archive; archiveParam["n"] = archive.length; const namespaceParam = new GoString(); namespaceParam["p"] = namespace; namespaceParam["n"] = namespace.length; const cursorParam = new GoString(); cursorParam["p"] = cursor; cursorParam["n"] = cursor.length; const registryJson = JSON.stringify(registryInfo) const registryJsonParam = new GoString(); registryJsonParam["p"] = registryJson; registryJsonParam["n"] = registryJson.length; kots().UpdateDownload(socketParam, archiveParam, namespaceParam, registryJsonParam, cursorParam); await statusServer.connection(); const isUpdateAvailable: number = await statusServer.termination((resolve, reject, obj): boolean => { if (obj.status === "running") { stores.kotsAppStore.setUpdateDownloadStatus(obj.display_message, "running"); return false; } if (obj.status === "terminated") { if (obj.exit_code !== -1) { resolve(obj.exit_code); } else { reject(new Error(obj.display_message)); } return true; } return false; }); if (isUpdateAvailable < 0) { console.log("error downloading update") return false; } if (isUpdateAvailable > 0) { await saveUpdateVersion(archive, app, stores, "Upstream Update"); } return isUpdateAvailable > 0; } finally { tmpDir.removeCallback(); } } export async function kotsAppDownloadUpdateFromAirgap(airgapFile: string, app: KotsApp, registryInfo: KotsAppRegistryDetails, stores: Stores): Promise<void> { const tmpDir = tmp.dirSync(); const archive = path.join(tmpDir.name, "archive.tar.gz"); try { fs.writeFileSync(archive, await app.getArchive("" + (app.currentSequence!))); const namespace = getK8sNamespace(); const statusServer = new StatusServer(); await statusServer.start(tmpDir.name); const socketParam = new GoString(); socketParam["p"] = statusServer.socketFilename; socketParam["n"] = statusServer.socketFilename.length; const archiveParam = new GoString(); archiveParam["p"] = archive; archiveParam["n"] = archive.length; const namespaceParam = new GoString(); namespaceParam["p"] = namespace; namespaceParam["n"] = namespace.length; const airgapFileParam = new GoString(); airgapFileParam["p"] = airgapFile; airgapFileParam["n"] = airgapFile.length; const registryJson = JSON.stringify(registryInfo) const registryJsonParam = new GoString(); registryJsonParam["p"] = registryJson; registryJsonParam["n"] = registryJson.length; kots().UpdateDownloadFromAirgap(socketParam, archiveParam, namespaceParam, registryJsonParam, airgapFileParam); await statusServer.connection(); const isUpdateAvailable: number = await statusServer.termination((resolve, reject, obj): boolean => { if (obj.status === "running") { stores.kotsAppStore.setUpdateDownloadStatus(obj.display_message, "running"); return false; } if (obj.status === "terminated") { if (obj.exit_code !== -1) { resolve(obj.exit_code); } else { reject(new Error(obj.display_message)); } return true; } return false; }); if (isUpdateAvailable) { await saveUpdateVersion(archive, app, stores, "Airgap Upload"); } } finally { tmpDir.removeCallback(); } } export async function kotsRenderFile(app: KotsApp, stores: Stores, input: string, registryInfo: KotsAppRegistryDetails): Promise<string> { const filename = tmp.tmpNameSync(); fs.writeFileSync(filename, input); // for the status server const tmpDir = tmp.dirSync(); const archive = path.join(tmpDir.name, "archive.tar.gz"); try { fs.writeFileSync(archive, await app.getArchive("" + (app.currentSequence!))); const statusServer = new StatusServer(); await statusServer.start(tmpDir.name); const socketParam = new GoString(); socketParam["p"] = statusServer.socketFilename; socketParam["n"] = statusServer.socketFilename.length; const filepathParam = new GoString(); filepathParam["p"] = filename; filepathParam["n"] = filename.length; const archivePathParam = new GoString(); archivePathParam["p"] = archive; archivePathParam["n"] = archive.length; const registryJson = JSON.stringify(registryInfo) const registryJsonParam = new GoString(); registryJsonParam["p"] = registryJson; registryJsonParam["n"] = registryJson.length; kots().RenderFile(socketParam, filepathParam, archivePathParam, registryJsonParam); await statusServer.connection(); await statusServer.termination((resolve, reject, obj): boolean => { // Return true if completed if (obj.status === "terminated") { if (obj.exit_code !== -1) { resolve(); } else { reject(new Error(obj.display_message)); } return true; } return false; }); const rendered = fs.readFileSync(filename); return rendered.toString(); } finally { tmpDir.removeCallback(); } } async function saveUpdateVersion(archive: string, app: KotsApp, stores: Stores, updateSource: string) { // if there was an update available, expect that the new archive is in the smae place as the one we pased in const params = await Params.getParams(); const buffer = fs.readFileSync(archive); const newSequence = (await stores.kotsAppStore.getMaxSequence(app.id)) + 1; const objectStorePath = path.join(params.shipOutputBucket.trim(), app.id, `${newSequence}.tar.gz`); await putObject(params, objectStorePath, buffer, params.shipOutputBucket); const installationSpec = await extractInstallationSpecFromTarball(buffer); const supportBundleSpec = await extractSupportBundleSpecFromTarball(buffer); const analyzersSpec = await extractAnalyzerSpecFromTarball(buffer); const preflightSpec = await extractPreflightSpecFromTarball(buffer); const appSpec = await extractAppSpecFromTarball(buffer); const kotsAppSpec = await extractKotsAppSpecFromTarball(buffer); const appTitle = await extractAppTitleFromTarball(buffer); const appIcon = await extractAppIconFromTarball(buffer); const kotsAppLicense = await extractKotsAppLicenseFromTarball(buffer); const configSpec = await extractConfigSpecFromTarball(buffer); const configValues = await extractConfigValuesFromTarball(buffer); const backupSpec = await extractBackupSpecFromTarball(buffer); console.log(`Save new version ${app.id}:${newSequence}, cursor=${installationSpec.cursor}`); await stores.kotsAppStore.createMidstreamVersion( app.id, newSequence, installationSpec.versionLabel, installationSpec.releaseNotes, installationSpec.cursor, installationSpec.channelName, installationSpec.encryptionKey, supportBundleSpec, analyzersSpec, preflightSpec, appSpec, kotsAppSpec, kotsAppLicense, configSpec, configValues, appTitle, appIcon, backupSpec ); const clusterIds = await stores.kotsAppStore.listClusterIDsForApp(app.id); for (const clusterId of clusterIds) { const downstreamGitops = await stores.kotsAppStore.getDownstreamGitOps(app.id, clusterId); let commitUrl = ""; let gitDeployable = false; if (downstreamGitops.enabled) { const commitMessage = `Updates to the upstream of ${app.name}`; commitUrl = await createGitCommitForVersion(stores, app.id, clusterId, newSequence, commitMessage); if (commitUrl !== "") { gitDeployable = true; } } const status = preflightSpec ? "pending_preflight" : "pending"; const diffSummary = await getDiffSummary(app); await stores.kotsAppStore.createDownstreamVersion(app.id, newSequence, clusterId, installationSpec.versionLabel, status, updateSource, diffSummary, commitUrl, gitDeployable); } } export async function kotsPullFromLicense(socket: string, out: string, kotsApp: KotsApp, downstreamName: string, stores: Stores) { const namespace = getK8sNamespace(); const socketParam = new GoString(); socketParam["p"] = socket; socketParam["n"] = socket.length; const licenseDataParam = new GoString(); licenseDataParam["p"] = kotsApp.license; licenseDataParam["n"] = Buffer.from(kotsApp.license!).length; const downstreamParam = new GoString(); downstreamParam["p"] = downstreamName; downstreamParam["n"] = downstreamName.length; const namespaceParam = new GoString(); namespaceParam["p"] = namespace; namespaceParam["n"] = namespace.length; const outParam = new GoString(); outParam["p"] = out; outParam["n"] = out.length; kots().PullFromLicense(socketParam, licenseDataParam, downstreamParam, namespaceParam, outParam); // args are returned so they are not garbage collected before native code is done return { socketParam, licenseDataParam, downstreamParam, namespaceParam, outParam, }; } export async function kotsAppFromData(out: string, kotsApp: KotsApp, stores: Stores): Promise<{ hasPreflight: boolean, isConfigurable: boolean }> { const params = await Params.getParams(); const buffer = fs.readFileSync(out); const objectStorePath = path.join(params.shipOutputBucket.trim(), kotsApp.id, "0.tar.gz"); await putObject(params, objectStorePath, buffer, params.shipOutputBucket); const installationSpec = await extractInstallationSpecFromTarball(buffer); const supportBundleSpec = await extractSupportBundleSpecFromTarball(buffer); const analyzersSpec = await extractAnalyzerSpecFromTarball(buffer); const preflightSpec = await extractPreflightSpecFromTarball(buffer); const appSpec = await extractAppSpecFromTarball(buffer); const kotsAppSpec = await extractKotsAppSpecFromTarball(buffer); const appTitle = await extractAppTitleFromTarball(buffer); const appIcon = await extractAppIconFromTarball(buffer); const kotsAppLicense = await extractKotsAppLicenseFromTarball(buffer); const configSpec = await extractConfigSpecFromTarball(buffer); const configValues = await extractConfigValuesFromTarball(buffer); kotsApp.isConfigurable = !!configSpec; kotsApp.hasPreflight = !!preflightSpec; const backupSpec = await extractBackupSpecFromTarball(buffer); if (kotsAppLicense) { // update kots app with latest license await stores.kotsAppStore.updateKotsAppLicense(kotsApp.id, kotsAppLicense); } await stores.kotsAppStore.createMidstreamVersion( kotsApp.id, 0, installationSpec.versionLabel, installationSpec.releaseNotes, installationSpec.cursor, installationSpec.channelName, installationSpec.encryptionKey, supportBundleSpec, analyzersSpec, preflightSpec, appSpec, kotsAppSpec, kotsAppLicense, configSpec, configValues, appTitle, appIcon, backupSpec ); const downstreams = await extractDownstreamNamesFromTarball(buffer); const clusters = await stores.clusterStore.listAllUsersClusters(); for (const downstream of downstreams) { const cluster = _.find(clusters, (c: Cluster) => { return c.title === downstream; }); if (!cluster) { continue; } const downstreamState = kotsApp.isConfigurable ? "pending_config" : kotsApp.hasPreflight ? "pending_preflight" : "deployed"; await stores.kotsAppStore.createDownstream(kotsApp.id, downstream, cluster.id); await stores.kotsAppStore.createDownstreamVersion(kotsApp.id, 0, cluster.id, installationSpec.versionLabel, downstreamState, "Kots Install", "", "", false); } return { isConfigurable: kotsApp.isConfigurable, hasPreflight: kotsApp.hasPreflight, }; } export async function kotsAppFromAirgapData(out: string, app: KotsApp, stores: Stores): Promise<{ hasPreflight: boolean, isConfigurable: boolean }> { const params = await Params.getParams(); const buffer = fs.readFileSync(out); const objectStorePath = path.join(params.shipOutputBucket.trim(), app.id, "0.tar.gz"); await putObject(params, objectStorePath, buffer, params.shipOutputBucket); const installationSpec = await extractInstallationSpecFromTarball(buffer); const supportBundleSpec = await extractSupportBundleSpecFromTarball(buffer); const analyzersSpec = await extractAnalyzerSpecFromTarball(buffer); const preflightSpec = await extractPreflightSpecFromTarball(buffer); const appSpec = await extractAppSpecFromTarball(buffer); const kotsAppSpec = await extractKotsAppSpecFromTarball(buffer); const appTitle = await extractAppTitleFromTarball(buffer); const appIcon = await extractAppIconFromTarball(buffer); const kotsAppLicense = await extractKotsAppLicenseFromTarball(buffer); const configSpec = await extractConfigSpecFromTarball(buffer); const configValues = await extractConfigValuesFromTarball(buffer); const backupSpec = await extractBackupSpecFromTarball(buffer); await stores.kotsAppStore.createMidstreamVersion( app.id, 0, installationSpec.versionLabel, installationSpec.releaseNotes, installationSpec.cursor, installationSpec.channelName, installationSpec.encryptionKey, supportBundleSpec, analyzersSpec, preflightSpec, appSpec, kotsAppSpec, kotsAppLicense, configSpec, configValues, appTitle, appIcon, backupSpec ); const downstreams = await extractDownstreamNamesFromTarball(buffer); const clusters = await stores.clusterStore.listAllUsersClusters(); for (const downstream of downstreams) { const cluster = _.find(clusters, (c: Cluster) => { return c.title === downstream; }); if (!cluster) { continue; } await stores.kotsAppStore.createDownstream(app.id, downstream, cluster.id); await stores.kotsAppStore.createDownstreamVersion(app.id, 0, cluster.id, installationSpec.versionLabel, "deployed", "Airgap Upload", "", "", false); } await stores.kotsAppStore.setKotsAirgapAppInstalled(app.id); return { hasPreflight: !!preflightSpec, isConfigurable: !!configSpec, }; } export async function kotsTestRegistryCredentials(endpoint: string, username: string, password: string, repo: string): Promise<String> { const tmpDir = tmp.dirSync(); try { const statusServer = new StatusServer(); await statusServer.start(tmpDir.name); const socketParam = new GoString(); socketParam["p"] = statusServer.socketFilename; socketParam["n"] = statusServer.socketFilename.length; const endpointParam = new GoString(); endpointParam["p"] = endpoint; endpointParam["n"] = endpoint.length; const usernameParam = new GoString(); usernameParam["p"] = username; usernameParam["n"] = username.length; const passwordParam = new GoString(); passwordParam["p"] = password; passwordParam["n"] = password.length; const repoParam = new GoString(); repoParam["p"] = repo; repoParam["n"] = repo.length; kots().TestRegistryCredentials(socketParam, endpointParam, usernameParam, passwordParam, repoParam); let testError = ""; await statusServer.connection(); await statusServer.termination((resolve, reject, obj): boolean => { // Return true if completed if (obj.status === "terminated") { if (obj.exit_code !== 0) { testError = obj.display_message; } resolve(); return true; } return false; }); return testError; } finally { tmpDir.removeCallback(); } } export async function kotsTemplateConfig(configSpec: string, configValues: string, license: string, registryInfo: KotsAppRegistryDetails): Promise<any> { const configDataParam = new GoString(); configDataParam["p"] = configSpec; configDataParam["n"] = Buffer.from(configSpec).length; const configValuesDataParam = new GoString(); configValuesDataParam["p"] = configValues; configValuesDataParam["n"] = Buffer.from(configValues).length; const licenseParam = new GoString(); licenseParam["p"] = license; licenseParam["n"] = Buffer.from(license).length; const registryJson = JSON.stringify(registryInfo) const registryJsonParam = new GoString(); registryJsonParam["p"] = registryJson; registryJsonParam["n"] = registryJson.length; const templatedConfig = kots().TemplateConfig(configDataParam, configValuesDataParam, licenseParam, registryJsonParam); if (templatedConfig == "" || templatedConfig["p"] == "") { throw new ReplicatedError("failed to template config"); } try { return yaml.safeLoad(templatedConfig["p"]); } catch (err) { throw new ReplicatedError(`Failed to parse templated config ${err}`); } } export async function kotsEncryptString(cipherString: string, message: string): Promise<string> { const cipherStringParam = new GoString(); cipherStringParam["p"] = cipherString; cipherStringParam["n"] = Buffer.from(cipherString).length; const messageParam = new GoString(); messageParam["p"] = message; messageParam["n"] = Buffer.from(message).length; const encrypted = kots().EncryptString(cipherStringParam, messageParam); if (encrypted["p"] === null) { throw new ReplicatedError("Failed to encrypt string via FFI call"); } return encrypted["p"]; } export async function kotsDecryptString(cipherString: string, message: string): Promise<string> { const cipherStringParam = new GoString(); cipherStringParam["p"] = cipherString; cipherStringParam["n"] = Buffer.from(cipherString).length; const messageParam = new GoString(); messageParam["p"] = message; messageParam["n"] = Buffer.from(message).length; const decrypted = kots().DecryptString(cipherStringParam, messageParam); if (decrypted["p"] === null) { throw new ReplicatedError("Failed to encrypt string via FFI call"); } return decrypted["p"]; } export async function kotsRewriteVersion(app: KotsApp, archive: string, downstreams: string[], registryInfo: KotsAppRegistryDetails, copyImages: boolean, outputFile: string, stores: Stores, updatedConfigValues: string): Promise<string> { const tmpDir = tmp.dirSync(); try { const k8sNamespace = getK8sNamespace(); const statusServer = new StatusServer(); await statusServer.start(tmpDir.name); const socketParam = new GoString(); socketParam["p"] = statusServer.socketFilename; socketParam["n"] = statusServer.socketFilename.length; const inputPathParam = new GoString(); inputPathParam["p"] = archive; inputPathParam["n"] = archive.length; const outputFileParam = new GoString(); outputFileParam["p"] = outputFile; outputFileParam["n"] = outputFile.length; const downstreamsStr = JSON.stringify(downstreams) const downstreamsParam = new GoString(); downstreamsParam["p"] = downstreamsStr; downstreamsParam["n"] = downstreamsStr.length; const k8sNamespaceParam = new GoString(); k8sNamespaceParam["p"] = k8sNamespace; k8sNamespaceParam["n"] = k8sNamespace.length; const registryJson = JSON.stringify(registryInfo) const registryJsonParam = new GoString(); registryJsonParam["p"] = registryJson; registryJsonParam["n"] = registryJson.length; const updatedConfigValuesParam = new GoString(); updatedConfigValuesParam["p"] = updatedConfigValues; updatedConfigValuesParam["n"] = updatedConfigValues.length; kots().RewriteVersion(socketParam, inputPathParam, outputFileParam, downstreamsParam, k8sNamespaceParam, registryJsonParam, copyImages, app.isAirgap, updatedConfigValuesParam); let errrorMessage = ""; await statusServer.connection(); await statusServer.termination((resolve, reject, obj): boolean => { // Return true if completed if (obj.status === "running") { stores.kotsAppStore.setImageRewriteStatus(obj.display_message, "running"); return false; } if (obj.status === "terminated") { if (obj.exit_code !== 0) { errrorMessage = obj.display_message; } resolve(); return true; } return false; }); if (errrorMessage) { await stores.kotsAppStore.setImageRewriteStatus(errrorMessage, "failed"); throw new ReplicatedError(errrorMessage); } return ""; } finally { tmpDir.removeCallback(); } } export function getK8sNamespace(): string { if (process.env["DEV_NAMESPACE"]) { return String(process.env["DEV_NAMESPACE"]); } if (process.env["POD_NAMESPACE"]) { return String(process.env["POD_NAMESPACE"]); } return "default"; } export function getKotsadmNamespace(): string { if (process.env["POD_NAMESPACE"]) { return String(process.env["POD_NAMESPACE"]); } return "default"; }
the_stack
import gulp, { TaskFunction } from 'gulp'; import path from 'path'; import chalk from 'chalk'; import isEmail from 'validator/lib/isEmail'; import isUrl from 'validator/lib/isURL'; import npmValidate from 'validate-npm-package-name'; import inquirer, { QuestionCollection } from 'inquirer'; import { args, runShellCommand } from './util'; import logger from '../common/logger'; import { LicenseType } from '../model/license-type'; import { PackerOptions } from '../model/packer-options'; import { parseBuildMode, parseScriptPreprocessorExtension, parseStylePreprocessorExtension, parseTestEnvironment } from './parser'; import { getConfigFileGenerateTasks } from './generate-config-util'; import { getTestSpecGeneratorTasks } from './generate-test-util'; import { getExampleSourceGenerationsTasks } from './generate-source-util'; import { getDemoSourceGenerationTasks } from './generate-demo-source-util'; import { buildPackageConfig } from './generate-package-config'; /** * Initialize project generation associated gulp tasks */ export default function init() { /** * Project generate gulp task. */ gulp.task('generate', async () => { const log = logger.create('[generate]'); try { log.trace('start'); const questions: QuestionCollection<PackerOptions> = [ { message: 'Give us a small description about the library (optional)?', name: 'description', type: 'input' }, { message: 'Give us a set of comma separated package keywords (optional)?', name: 'keywords', type: 'input' }, { message: "Author's name (optional)?", name: 'author', type: 'input' }, { message: "Author's email address (optional)?", name: 'email', type: 'input', when: (answers: PackerOptions) => { return !!answers.author; }, validate: (value: string) => { return !value || isEmail(value) ? true : 'Value must be a valid email address'; } }, { message: "Author's github username (optional)?", name: 'githubUsername', type: 'input', validate: () => { return true; // todo: add GH username validation here } }, { message: 'Library homepage link (optional)?', name: 'website', type: 'input', validate: (value: string) => { return !value || isUrl(value) ? true : 'Value must be a valid URL'; } }, { choices: ['none', 'typescript'], default: 0, message: "What's the script pre processor you want to use?", name: 'scriptPreprocessor', type: 'list' }, { default: true, message: 'Do you want style sheet support?', name: 'styleSupport', type: 'confirm' }, { choices: ['scss', 'sass', 'less', 'stylus', 'none'], default: 0, message: "What's the style pre processor you want to use?", name: 'stylePreprocessor', type: 'list', when: (answers: PackerOptions) => { return answers.styleSupport; } }, { default: false, message: 'Do you want to inline bundle styles within script?', name: 'bundleStyles', type: 'confirm', when: (answers: PackerOptions) => { return answers.styleSupport; } }, { default: true, message: 'Are you building a browser compliant library?', name: 'browserCompliant', type: 'confirm' }, { default: false, message: 'Are you building a node CLI project?', name: 'cliProject', type: 'confirm', when: (answers: PackerOptions) => { return !answers.browserCompliant; } }, { default: false, message: 'Are you building a react library?', name: 'reactLib', type: 'confirm', when: (answers: PackerOptions) => { return answers.browserCompliant; } }, { choices: ['umd', 'amd', 'iife', 'system'], default: 0, message: "What's the build bundle format you want to use?", name: 'bundleFormat', type: 'list', when: (answers: PackerOptions) => { return answers.browserCompliant; } }, { default: 'my-lib', message: "What's the AMD id you want to use?", name: 'amdId', type: 'input', validate: (value: string) => { const matches = value.match(/^(?:[a-z]\d*(?:-[a-z])?)*$/i); return !!matches || "AMD id should only contain alphabetic characters, i.e: 'my-bundle'"; }, when: (answers: PackerOptions) => { return answers.bundleFormat === 'umd' || answers.bundleFormat === 'amd'; } }, { default: 'com.lib', message: "What's the library namespace you want to use?", name: 'namespace', type: 'input', validate: (value: string) => { const matches = value.match(/^(?:[a-z]\d*(?:\.[a-z])?)+$/i); return !!matches || "Namespace should be an object path, i.e: 'ys.nml.lib'"; }, when: (answers: PackerOptions) => { return ( answers.bundleFormat === 'umd' || answers.bundleFormat === 'iife' || answers.bundleFormat === 'system' ); } }, { choices: ['jest', 'mocha', 'jasmine'], default: 0, message: 'Which unit test framework do you want to use?', name: 'testFramework', type: 'list', when: (answers: PackerOptions) => { return answers.reactLib; } }, { choices: ['mocha', 'jasmine', 'jest'], default: 0, message: 'Which unit test framework do you want to use?', name: 'testFramework', type: 'list', when: (answers: PackerOptions) => { return !answers.reactLib; } }, { default: true, message: 'Do you want to use enzyme to test react components?', name: 'useEnzyme', type: 'confirm', when: (answers: PackerOptions) => { return answers.reactLib; } }, { choices: ['jsdom', 'browser'], default: 0, message: 'Choose the test environment that will be used for testing?', name: 'testEnvironment', type: 'list', when: (answers: PackerOptions) => { return ( answers.browserCompliant && !answers.reactLib && (answers.testFramework === 'jasmine' || answers.testFramework === 'mocha') ); } }, { default: new Date().getFullYear(), message: "What's the library copyright year (optional)?", name: 'year', type: 'input' }, { choices: [ LicenseType.MIT, LicenseType.APACHE_2, LicenseType.MPL_2, LicenseType.BSD_2, LicenseType.BSD_3, LicenseType.ISC, LicenseType.LGPL_3, LicenseType.GLP_3, LicenseType.UNLICENSE ], default: 0, message: "What's the license you want to use?", name: 'license', type: 'list' }, { default: false, message: 'Do you want to use yarn as package manager?', name: 'isYarn', type: 'confirm' } ]; if (args.length < 2) { log.error( 'Please provide a library name to generate the project\n%s', chalk.blue('npx packer-cli generate my-library') ); process.exit(1); return; } const packageName = args[1]; const packageNameValidity = npmValidate(packageName); if (!packageNameValidity.validForNewPackages) { if (packageNameValidity.errors) { log.error('Package name error: %s', packageNameValidity.errors.join('\n')); } else if (packageNameValidity.warnings) { log.error('Package name error: %s', packageNameValidity.warnings.join('\n')); } process.exit(1); return; } const options: PackerOptions = await inquirer.prompt<PackerOptions>(questions); options.bundleFormat = options.bundleFormat || 'cjs'; const testEnvironment = parseTestEnvironment(options); const packageConfig = buildPackageConfig(options, testEnvironment, packageName); const scriptExt = parseScriptPreprocessorExtension(options.scriptPreprocessor); const projectDir = path.join(process.cwd(), packageName); const styleExt = parseStylePreprocessorExtension(options.stylePreprocessor); const buildMode = parseBuildMode(options); const tasks: TaskFunction[] = [ ...getExampleSourceGenerationsTasks(options, styleExt, scriptExt, buildMode, projectDir, log), ...getTestSpecGeneratorTasks(options, scriptExt, testEnvironment, projectDir, log), ...getDemoSourceGenerationTasks(options, buildMode, packageName, projectDir, log), ...getConfigFileGenerateTasks(options, packageConfig, buildMode, scriptExt, testEnvironment, projectDir, log) ]; await gulp.series([ gulp.parallel(tasks), async () => { if (!args.includes('--skipInstall') && !args.includes('-sk')) { await runShellCommand(options.isYarn ? 'yarn install' : 'npm install', projectDir, log); } log.info('📦 package generated 🚀'); } ])(() => { // No implementation }); } catch (e) { log.error('task failure\n%s', e.stack || e.message); process.exit(1); } }); }
the_stack
import { DB } from 'https://deno.land/x/sqlite@v2.4.2/mod.ts'; import { AccessRecord, checkAccessRecord, checkDomainRecord, DomainRecord, isAccessRecordBeta1, isDomainRecordBeta1 } from './model.ts'; const VERSION = 4; export class Database { private readonly _db: DB; constructor(path: string) { this._db = new DB(path); this._db.query(`create table if not exists access${VERSION}( filename text not null, line integer not null, stream text null, accessorIdentifier text not null, accessorIdentifierType text not null, tccService text, identifier text not null, kind text not null, timestamp text not null, version integer null, category text null, outOfProcess text null, primary key (filename, line)) without rowid`); this._db.query(`create table if not exists domain${VERSION}( filename text not null, line integer not null, bundleId text not null, domain text not null, context text not null, initiatedType string not null, effectiveUserId number null, domainType number not null, timeStamp text not null, hasAppBundleName text null, hits integer not null, domainOwner string not null, firstTimeStamp string not null, primary key (filename, line)) without rowid`); } getFilenames(): string[] { const filenames = [...this._db.query(`select distinct filename from access${VERSION} union select distinct filename from domain${VERSION} order by filename desc`)].map(([filename]) => filename); return filenames; } getDates(filename: string) { const date = [...this._db.query(`select distinct substr(timestamp, 1, 10) date from access${VERSION} where filename = ? union select distinct substr(timestamp, 1, 10) date from domain${VERSION} where filename = ? order by date desc`, [filename, filename])].map(([date]) => date); return date; } getBundleIds(filename: string) { const bundleId = [...this._db.query(`select distinct accessorIdentifier bundleId from access${VERSION} where filename = ? union select bundleId from domain${VERSION} where filename = ? order by bundleId`, [filename, filename])].map(([bundleId]) => bundleId); return bundleId; } getTypes(filename: string): string[] { const streams = [...this._db.query(`select distinct stream, tccService, category from access${VERSION} where filename = ? order by stream, tccService, category`, [filename])].map(([stream, tccService, category]) => computeStream(stream, tccService, category)); const rt = streams.map(v => `access/${v}`); rt.unshift('access'); rt.push('domains'); return rt; } clearAccess(filename: string) { this._db.query(`delete from access${VERSION} where filename = ?`, [ filename ]); } insertAccess(filename: string, line: number, record: AccessRecord, category: string | undefined, outOfProcess: string | undefined) { const timestamp = checkAccessRecord(record); const version = isAccessRecordBeta1(record) ? record.version : undefined; const stream = isAccessRecordBeta1(record) ? record.stream : undefined; this._db.query(`insert into access${VERSION}(filename, line, stream, accessorIdentifier, accessorIdentifierType, tccService, identifier, kind, timestamp, version, category, outOfProcess) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [filename, line, stream, record.accessor.identifier, record.accessor.identifierType, record.tccService, record.identifier, record.kind, timestamp, version, category, outOfProcess]); if (this._db.changes !== 1) throw new Error(`Failed to insert access record`); } clearDomain(filename: string) { this._db.query(`delete from domain${VERSION} where filename = ?`, [ filename ]); } insertDomain(filename: string, line: number, bundleId: string, record: DomainRecord) { checkDomainRecord(record); const effectiveUserId = isDomainRecordBeta1(record) ? record.effectiveUserId : undefined; const hasAppBundleName = isDomainRecordBeta1(record) ? record['hasApp.bundleName'] : undefined; this._db.query(`insert into domain${VERSION}(filename, line, bundleId, domain, effectiveUserId, domainType, timeStamp, hasAppBundleName, context, hits, domainOwner, initiatedType, firstTimeStamp) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [filename, line, bundleId, record.domain, effectiveUserId, record.domainType, record.timeStamp, hasAppBundleName, record.context, record.hits, record.domainOwner, record.initiatedType, record.firstTimeStamp]); if (this._db.changes !== 1) throw new Error(`Failed to insert domain record`); } getAccessSummariesByDate(filename: string, opts: { date?: string, type?: string, bundleId?: string } = {}): Map<string, AccessSummary[]> { const rows = this._db.query(`select stream, tccService, accessorIdentifier, timestamp, identifier, kind, category from access${VERSION} where filename = ?`, [ filename ]); const summariesByIdentifier = new Map<string, AccessSummary>(); for (const [stream, tccService, accessorIdentifier, timestamp, identifier, kind, category] of rows) { let timestampStart = kind === 'intervalEnd' ? undefined : timestamp; let timestampEnd = kind === 'intervalEnd' ? timestamp : undefined; let date = timestampStart ? timestampStart.substring(0, 10) : undefined; const existing = summariesByIdentifier.get(identifier); if (!existing) { // ensure timestampStart & date have initial defined values (in case we don't get an intervalStart), this is better than nothing timestampStart = timestamp; date = timestampStart.substring(0, 10); summariesByIdentifier.set(identifier, { date, stream: computeStream(stream, tccService, category), bundleId: accessorIdentifier, timestampStart, timestampEnd }); } else { timestampStart = timestampStart || existing.timestampStart; timestampEnd = timestampEnd || existing.timestampStart; date = date || existing.date; summariesByIdentifier.set(identifier, { ...existing, timestampStart, timestampEnd, date }); } } const summariesByDate = new Map<string, AccessSummary[]>(); for (const summary of summariesByIdentifier.values()) { const date = summary.date; if (opts.date && opts.date !== date) continue; if (opts.type && !streamMatchesType(summary.stream, opts.type)) continue; if (opts.bundleId && opts.bundleId !== summary.bundleId) continue; if (!summariesByDate.has(date)) { summariesByDate.set(date, []); } summariesByDate.get(date)!.push(summary); } sortByTimestampDescending(summariesByDate, v => v.timestampStart); return summariesByDate; } getDomainSummariesByDate(filename: string, opts: { date?: string, bundleId?: string } = {}): Map<string, DomainSummary[]> { const rows = this._db.query(`select timestamp, bundleId, domain, hits from domain${VERSION} where filename = ?`, [ filename ]); const summariesByDate = new Map<string, DomainSummary[]>(); for (const [timestamp, bundleId, domain, hits] of rows) { const date = timestamp.substring(0, 10); if (opts.date && opts.date !== date) continue; if (opts.bundleId && opts.bundleId !== bundleId) continue; if (!summariesByDate.has(date)) { summariesByDate.set(date, []); } summariesByDate.get(date)!.push({ date, bundleId, timestamp, domain, hits }); } sortByTimestampDescending(summariesByDate, v => v.timestamp); return summariesByDate; } getCommonSummariesByDate(filename: string, opts: { date?: string, type?: string, bundleId?: string } = {}): Map<string, CommonSummary[]> { const accessSummariesByDate = this.getAccessSummariesByDate(filename, opts); const domainSummariesByDate = this.getDomainSummariesByDate(filename, opts); const commonSummariesByDate = new Map<string, CommonSummary[]>(); for (const date of accessSummariesByDate.keys()) { for (const accessSummary of accessSummariesByDate.get(date)!) { const timestamp = accessSummary.timestampStart; if (!commonSummariesByDate.has(date)) { commonSummariesByDate.set(date, []); } commonSummariesByDate.get(date)!.push({ timestamp, accessSummary }); } } for (const date of domainSummariesByDate.keys()) { for (const domainSummary of domainSummariesByDate.get(date)!) { const timestamp = domainSummary.timestamp; if (!commonSummariesByDate.has(date)) { commonSummariesByDate.set(date, []); } commonSummariesByDate.get(date)!.push({ timestamp, domainSummary }); } } sortByTimestampDescending(commonSummariesByDate, v => v.timestamp); return commonSummariesByDate; } close() { this._db.close(); } } // export interface AccessSummary { readonly date: string; readonly stream: string; readonly bundleId: string; readonly timestampStart: string; readonly timestampEnd?: string; } export interface DomainSummary { readonly date: string; readonly bundleId: string; readonly timestamp: string; readonly domain: string; readonly hits: number; } export interface CommonSummary { timestamp: string; accessSummary?: AccessSummary; domainSummary?: DomainSummary; } // function computeStream(stream: string, tccService: string | undefined, category: string | undefined): string { if (category) return category; let rt = stream; if (rt.startsWith('com.apple.privacy.accounting.stream.')) rt = rt.substring('com.apple.privacy.accounting.stream.'.length); if (tccService) { rt += '/' + tccService; } return rt; } function streamMatchesType(stream: string, type: string): boolean { return type === 'access' || type === `access/${stream}`; } function sortByTimestampDescending<T>(valuesByDate: Map<string, T[]>, timestampFn: (item: T) => string) { for (const summaries of valuesByDate.values()) { summaries.sort((lhs, rhs) => -timestampFn(lhs).localeCompare(timestampFn(rhs))); } }
the_stack
import { EToolName } from '@/constant/store'; import { IFileInfo, IStepInfo } from '@/store'; import { getBaseName, jsonParser } from './tool/common'; import { DrawUtils } from '@labelbee/lb-annotation'; import ColorCheatSheet from '@/assets/color.json'; // 获取 color cheat sheet 内的颜色 export const getRgbFromColorCheatSheet = (index: number) => { const rgb = ColorCheatSheet[index].rgb; return `rgb(${rgb.r},${rgb.g},${rgb.b})`; }; export const getRgbaColorListFromColorCheatSheet = (index: number) => { const rgb = ColorCheatSheet[index].rgb; return [rgb.r, rgb.g, rgb.b, 255]; }; interface CocoDataFormat { // 导出数据无需支持 // info: { // year: number; // version: string; // description: string; // contributor: string; // url: string; // date_created: string; // date_time - 2017/09/01 // }; images: Array<ICocoImage>; annotations: Array<ICocoObjectDetection>; categories: Array<{ id: number; name: string; supercategory: string; }>; } interface ICocoImage { id: number; width: number; height: number; file_name: string; // 导出数据无需支持 // license: number; // flickr_url: string; // coco_url: string; // date_captured: string; // LabelBee 补充内容 valid?: boolean; rotate?: number; } interface ICocoObjectDetection { id: number; image_id: number; category_id: number; segmentation: number[]; // RLE or [polygon], 现只支持 [polygon] 格式 area: number; bbox: number[]; // 检测框, x, y, width, height // 导出数据无需支持 iscrowd: 0 | 1; // 0 代表 segmentation 使用 [polygon] 形式, 1 代表 RLE 格式 textAttribute?: string; // 对其内部数据 order?: number; valid?: boolean; } /** * 平台默认多边形 */ interface IDefaultPolygon { x: number; y: number; } export default class DataTransfer { /** * 将 sensebee 多边形点集转换成的 COCO - POLYGON 格式 * @param pointList * @returns */ public static transferPolygon2CocoPolygon(pointList: IDefaultPolygon[]) { return pointList.reduce<number[]>((acc, cur) => [...acc, cur.x, cur.y], []); } /** * 获取多边形面积 * @param pointList * @returns */ public static getPolygonArea(pointList: IDefaultPolygon[]) { let total = 0; for (let i = 0, l = pointList.length; i < l; i++) { const addX = pointList[i].x; const addY = pointList[i == pointList.length - 1 ? 0 : i + 1].y; const subX = pointList[i == pointList.length - 1 ? 0 : i + 1].x; const subY = pointList[i].y; total += addX * addY * 0.5; total -= subX * subY * 0.5; } return Math.abs(total); } /** * 获取当前的多边形的边缘 bbox * @param pointList * @returns */ public static getPolygonBbox(pointList: IDefaultPolygon[]) { if (pointList.length < 3 || !pointList.length) { return 0; } let ltx = Number.MAX_SAFE_INTEGER; let lty = Number.MAX_SAFE_INTEGER; let rbx = 0; let rby = 0; pointList.forEach((polygon) => { if (polygon.x < ltx) { ltx = polygon.x; } if (polygon.y < lty) { lty = polygon.y; } if (polygon.x > rbx) { rbx = polygon.x; } if (polygon.y > rby) { rby = polygon.y; } }); return [ltx, lty, rbx - ltx, rby - lty]; } /** * 将 sensebee 格式转换为 coco 格式 * 仅限工具: 拉框、多边形 * 1. 拉框 - 属性属性解析 * 2. 多边形 * @param fileList */ public static transferDefault2Coco(fileList: IFileInfo[], stepList: IStepInfo[]) { const mainObject: CocoDataFormat = { images: [], annotations: [], categories: [ { id: 0, name: '', supercategory: '', }, ], }; /** * 提取步骤中的配置 - 将 attributeList 同步至 coco 的 categories */ const config = jsonParser(stepList[0]?.config); if (config?.attributeList) { mainObject.categories = mainObject.categories.concat( config?.attributeList?.map((v: any, i: number) => ({ id: i + 1, name: v.value, supercategory: '', })) ?? [], ); } let image_id = 1; let result_id = 1; fileList.forEach((info) => { const result = jsonParser(info.result); // 1. 添加图片基础信息 const images: ICocoImage = { id: image_id, file_name: getBaseName(info.url), width: result?.width ?? 0, height: result?.height ?? 0, valid: result?.valid ?? true, rotate: result?.rotate ?? 0, }; // 2. 标注结果 const annotation: any[] = []; // 获取当前标注 const getCategoryID = (data: any) => { let category_id = 0; // 0 默认为 if (data?.attribute) { const category = mainObject.categories.find((v) => v.name === data.attribute); if (category) { category_id = category.id; } else { category_id = mainObject.categories.length; mainObject.categories.push({ id: category_id, name: data.attribute, supercategory: '', }); } } return category_id; }; // TODO 默认使用第一步的数据 const step1Result = result['step_1']?.result; switch (result['step_1']?.toolName) { case EToolName.Rect: step1Result?.forEach((rect: any) => { let category_id = getCategoryID(rect); const defaultData = { image_id, id: result_id, bbox: [rect.x, rect.y, rect.width, rect.height], iscrowd: 0, segmentation: [], category_id, }; let area = 0; if (rect.width && rect.height) { area = rect.width * rect.height; } Object.assign(defaultData, { area }); if (rect.textAttribute) { Object.assign(defaultData, { textAttribute: rect.textAttribute }); } if (rect.order) { Object.assign(defaultData, { order: rect.order }); } annotation.push(defaultData); result_id++; }); break; case EToolName.Polygon: step1Result?.forEach((polygon: any) => { let category_id = getCategoryID(polygon); const defaultData = { image_id, id: result_id, iscrowd: 0, segmentation: [this.transferPolygon2CocoPolygon(polygon.pointList)], area: this.getPolygonArea(polygon.pointList), bbox: this.getPolygonBbox(polygon.pointList), category_id, }; if (polygon.textAttribute) { Object.assign(defaultData, { textAttribute: polygon.textAttribute }); } if (polygon.order) { Object.assign(defaultData, { order: polygon.order }); } annotation.push(defaultData); result_id++; }); break; default: { // } } mainObject.images.push(images); mainObject.annotations = mainObject.annotations.concat(annotation); image_id++; }); return mainObject; } /** * 格式化属性配置,提取属性配置字符串 * * @param stepList */ public static attributeConfigFormat(stepList: IStepInfo[]) { let categories = [ { id: -1, value: '', name: '', }, ]; let idString = ''; /** * 提取步骤中的配置 - 将 attributeList 同步至 categories */ const config = jsonParser(stepList[0]?.config); if (config?.attributeList) { categories = categories.concat( config?.attributeList?.map((v: any, i: number) => ({ id: i, value: v.value, name: v.key, })) ?? [], ); } categories.forEach((v: any, i: number) => { idString += `${v.id} ${v.value}` + '\n'; }); return { categories, idString }; } /** * 将 sensebee 格式转换为 yolo 格式 * 仅限工具: 拉框 * @param result */ public static transferDefault2Yolo(result: any, categories: any[]) { let dataString = ''; const width = result?.width ?? 0; const height = result?.height ?? 0; if (result?.step_1) { result?.step_1?.result?.forEach((v: any, i: number) => { const x = v?.x ?? 0; const y = v?.y ?? 0; const bboxWidth = v?.width; const bboxHeight = v?.height; const category = categories.find((item: any) => v.attribute === item.value); const ratioX = (x / width).toFixed(6); const ratioY = (y / height).toFixed(6); const ratioWidth = (bboxWidth / width).toFixed(6); const ratioHeight = (bboxHeight / height).toFixed(6); const labelClass = category.id ?? -1; dataString += `${labelClass} ${ratioX} ${ratioY} ${ratioWidth} ${ratioHeight}`; // 非最后一行都加换行 if (i !== result?.step_1?.result?.length - 1) { dataString = dataString + '\n'; } }); } return dataString; } /** * 导出 Mask 的格式数据 * @param width * @param height * @param polygon * @param defaultKeyList * @returns */ public static transferPolygon2ADE20k( width: number, height: number, polygon: any[], defaultKeyList: string[] = [], ) { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const keyList: string[] = [...defaultKeyList]; // 背景绘制为的 0 - 全黑 - rgb (0,0,0) DrawUtils.drawRectWithFill(canvas, { x: 0, y: 0, width, height }, { color: `rgb(0, 0, 0)` }); if (polygon.length > 0) { polygon.forEach((p) => { let key = ''; if (p.attribute) { key = p.attribute; } let colorIndex = keyList.findIndex((v) => v === key); if (colorIndex === -1) { keyList.push(key); colorIndex = keyList.length - 1; } DrawUtils.drawPolygonWithFill(canvas, p.pointList, { color: getRgbFromColorCheatSheet(colorIndex + 1), }); }); } const MIME_TYPE = 'image/png'; // Get the DataUrl from the Canvas const url = canvas.toDataURL(MIME_TYPE, 1); // remove Base64 stuff from the Image const base64Data = url.replace(/^data:image\/png;base64,/, ''); return [base64Data, keyList]; } /** * 导出灰值图 * canvas 仅能导出三通道的值,暂时以上相同值导出 * @param width * @param height * @param polygon * @param defaultKeyList * @returns */ public static transferPolygon2Gray( width: number, height: number, polygon: any[], defaultKeyList: string[] = [], ) { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const keyList: string[] = [...defaultKeyList]; // 背景绘制为的 0 - 全黑 - rgb (0,0,0) DrawUtils.drawRectWithFill(canvas, { x: 0, y: 0, width, height }, { color: `rgb(0, 0, 0)` }); if (polygon.length > 0) { polygon.forEach((p) => { let key = ''; if (p.attribute) { key = p.attribute; } let colorIndex = keyList.findIndex((v) => v === key); if (colorIndex === -1) { keyList.push(key); colorIndex = keyList.length - 1; } const trainIds = colorIndex + 1; DrawUtils.drawPolygonWithFill(canvas, p.pointList, { color: `rgb(${trainIds},${trainIds},${trainIds})`, }); }); } const MIME_TYPE = 'image/png'; // Get the DataUrl from the Canvas const url = canvas.toDataURL(MIME_TYPE, 1); // remove Base64 stuff from the Image const base64Data = url.replace(/^data:image\/png;base64,/, ''); return [base64Data, keyList]; } }
the_stack
import { options, tasks, objectForEach, cleanNode, triggerEvent } from '@tko/utils' import { observable, isWritableObservable, isObservable } from '@tko/observable' import { isComputed } from '@tko/computed' import { MultiProvider } from '@tko/provider.multi' import { DataBindProvider } from '@tko/provider.databind' import { applyBindings, dataFor } from '@tko/bind' import { bindings as coreBindings } from '@tko/binding.core' import { bindings as templateBindings } from '@tko/binding.template' import { bindings as ifBindings } from '@tko/binding.if' import components from '@tko/utils.component' import { bindings as componentBindings } from '@tko/binding.component' import {ComponentProvider} from '../dist' import { useMockForTasks } from '@tko/utils/helpers/jasmine-13-helper' describe('Components: Custom elements', function () { var bindingHandlers beforeEach(function () { jasmine.prepareTestNode() useMockForTasks(options) var provider = new MultiProvider({ providers: [new DataBindProvider(), new ComponentProvider()] }) options.bindingProviderInstance = provider bindingHandlers = provider.bindingHandlers bindingHandlers.set(componentBindings) bindingHandlers.set(templateBindings) bindingHandlers.set(coreBindings) bindingHandlers.set(ifBindings) }) afterEach(function () { expect(tasks.resetForTesting()).toEqual(0) jasmine.Clock.reset() components.unregister('test-component') }) it('Inserts components into custom elements with matching names', function () { components.register('test-component', { template: 'custom element <span data-bind="text: 123"></span>' }) var initialMarkup = '<div>hello <test-component></test-component></div>' testNode.innerHTML = initialMarkup // Since components are loaded asynchronously, it doesn't show up synchronously applyBindings(null, testNode) expect(testNode).toContainHtml(initialMarkup) // ... but when the component is loaded, it does show up jasmine.Clock.tick(1) expect(testNode).toContainHtml('<div>hello <test-component>custom element <span data-bind="text: 123">123</span></test-component></div>') }) it('Inserts components into custom elements with matching non-dashed names', function () { if (jasmine.ieVersion || window.HTMLUnknownElement) { // Phantomjs 1.x doesn't include HTMLUnknownElement and will fail this test this.after(function () { components.unregister('somefaroutname') }) components.register('somefaroutname', { template: 'custom element <span data-bind="text: 123"></span>', ignoreCustomElementWarning: true }) var initialMarkup = '<div>hello <somefaroutname></somefaroutname></div>' testNode.innerHTML = initialMarkup // Since components are loaded asynchronously, it doesn't show up synchronously applyBindings(null, testNode) expect(testNode).toContainHtml(initialMarkup) // ... but when the component is loaded, it does show up jasmine.Clock.tick(1) expect(testNode).toContainHtml('<div>hello <somefaroutname>custom element <span data-bind="text: 123">123</span></somefaroutname></div>') } }) it('Does not insert components into standard elements with matching names', function () { this.after(function () { components.unregister('em') }) components.register('em', { template: 'custom element <span data-bind="text: 123"></span>', ignoreCustomElementWarning: true }) var initialMarkup = '<div>hello <em></em></div>' testNode.innerHTML = initialMarkup applyBindings(null, testNode) jasmine.Clock.tick(1) expect(testNode).toContainHtml(initialMarkup) }) it('Is possible to override getComponentNameForNode to determine which component goes into which element', function () { const cp = new ComponentProvider() options.bindingProviderInstance = cp cp.bindingHandlers.set(componentBindings) cp.getComponentNameForNode = function (node) { return node.tagName === 'A' ? 'test-component' : null } components.register('test-component', { template: 'custom element' }) // Set up a getComponentNameForNode function that maps "A" tags to // test-component. testNode.innerHTML = '<div>hello <a>&nbsp;</a> <b>ignored</b></div>' // See the component show up. applyBindings(null, testNode) jasmine.Clock.tick(1) expect(testNode).toContainHtml('<div>hello <a>custom element</a> <b>ignored</b></div>') }) it('Is possible to have regular data-bind bindings on a custom element, as long as they don\'t attempt to control descendants', function () { components.register('test-component', { template: 'custom element' }) testNode.innerHTML = '<test-component data-bind="visible: shouldshow"></test-component>' // Bind with a viewmodel that controls visibility var viewModel = { shouldshow: observable(true) } applyBindings(viewModel, testNode) jasmine.Clock.tick(1) expect(testNode).toContainHtml('<test-component data-bind="visible: shouldshow">custom element</test-component>') expect(testNode.childNodes[0].style.display).not.toBe('none') // See that the 'visible' binding still works viewModel.shouldshow(false) expect(testNode.childNodes[0].style.display).toBe('none') expect(testNode.childNodes[0].innerHTML).toBe('custom element') }) it('Is not possible to have regular data-bind bindings on a custom element if they also attempt to control descendants', function () { components.register('test-component', { template: 'custom element' }) testNode.innerHTML = '<test-component data-bind="if: true"></test-component>' expect(function () { applyBindings(null, testNode) }) .toThrowContaining('Multiple bindings (if and component) are trying to control descendant bindings of the same element.') // Even though applyBindings threw an exception, the component still gets bound (asynchronously) jasmine.Clock.tick(1) }) it('Is possible to call applyBindings directly on a custom element', function () { components.register('test-component', { template: 'custom element' }) testNode.innerHTML = '<test-component></test-component>' var customElem = testNode.childNodes[0] expect(customElem.tagName.toLowerCase()).toBe('test-component') applyBindings(null, customElem) jasmine.Clock.tick(1) expect(customElem.innerHTML).toBe('custom element') }) it('Throws if you try to duplicate the \'component\' binding on a custom element that matches a component', function () { components.register('test-component', { template: 'custom element' }) testNode.innerHTML = '<test-component data-bind="component: {}"></test-component>' expect(function () { applyBindings(null, testNode) }).toThrowContaining('The binding "component" is duplicated by multiple providers') }) it('Is possible to pass literal values', function () { var suppliedParams = [] components.register('test-component', { template: 'Ignored', viewModel: function (params) { suppliedParams.push(params) // The raw value for each param is a computed giving the literal value objectForEach(params, function (key, value) { if (key !== '$raw') { expect(isComputed(params.$raw[key])).toBe(true) expect(params.$raw[key]()).toBe(value) } }) } }) testNode.innerHTML = '<test-component params="nothing: null, num: 123, bool: true, obj: { abc: 123 }, str: \'mystr\'"></test-component>' applyBindings(null, testNode) jasmine.Clock.tick(1) delete suppliedParams[0].$raw // Don't include '$raw' in the following assertion, as we only want to compare supplied values expect(suppliedParams).toEqual([{ nothing: null, num: 123, bool: true, obj: { abc: 123 }, str: 'mystr' }]) }) it('Supplies an empty params object (with empty $raw) if a custom element has no params attribute', function () { var suppliedParams = [] components.register('test-component', { template: 'Ignored', viewModel: function (params) { suppliedParams.push(params) } }) testNode.innerHTML = '<test-component></test-component>' applyBindings(null, testNode) jasmine.Clock.tick(1) expect(suppliedParams).toEqual([{ $raw: {} }]) }) it('Supplies an empty params object (with empty $raw) if a custom element has an empty whitespace params attribute', function () { var suppliedParams = [] components.register('test-component', { template: 'Ignored', viewModel: function (params) { suppliedParams.push(params) } }) testNode.innerHTML = '<test-component params=" "></test-component>' applyBindings(null, testNode) jasmine.Clock.tick(1) expect(suppliedParams).toEqual([{ $raw: {} }]) }) it('Should not confuse parameters with bindings', function () { var called = false bindingHandlers.set({ donotcall: function () { called = true } }) components.register('test-component', { template: 'Ignore', synchronous: true }) testNode.innerHTML = '<test-component params="donotcall: value"></test-component>' applyBindings({value: 123}, testNode) // The only binding it should look up is "component" expect(called).toBe(false) }) it('Should update component when observable view model changes', function () { components.register('test-component', { template: '<p>the value: <span data-bind="text: textToShow"></span></p>' }) testNode.innerHTML = '<test-component params="textToShow: value"></test-component>' var vm = observable({ value: 'A' }) applyBindings(vm, testNode) jasmine.Clock.tick(1) expect(testNode).toContainText('the value: A') vm({ value: 'Z' }) jasmine.Clock.tick(1) expect(testNode).toContainText('the value: Z') }) it('Is possible to pass observable instances', function () { components.register('test-component', { template: '<p>the observable: <span data-bind="text: receivedobservable"></span></p>', viewModel: function (params) { this.receivedobservable = params.suppliedobservable expect(this.receivedobservable.subprop).toBe('subprop') this.dispose = function () { this.wasDisposed = true } // The $raw value for this param is a computed giving the observable instance expect(isComputed(params.$raw.suppliedobservable)).toBe(true) expect(params.$raw.suppliedobservable()).toBe(params.suppliedobservable) } }) // See we can supply an observable instance, which is received with no wrapper around it var myobservable = observable(1) myobservable.subprop = 'subprop' testNode.innerHTML = '<test-component params="suppliedobservable: myobservable"></test-component>' applyBindings({ myobservable: myobservable }, testNode) jasmine.Clock.tick(1) var viewModelInstance = dataFor(testNode.firstChild.firstChild) expect(testNode.firstChild).toContainText('the observable: 1') // See the observable instance can mutate, without causing the component to tear down myobservable(2) expect(testNode.firstChild).toContainText('the observable: 2') expect(dataFor(testNode.firstChild.firstChild)).toBe(viewModelInstance) // Didn't create a new instance expect(viewModelInstance.wasDisposed).not.toBe(true) }) it('Is possible to pass expressions that can vary observably', function () { var rootViewModel = { myobservable: observable('Alpha') }, constructorCallCount = 0 components.register('test-component', { template: '<p>the string reversed: <span data-bind="text: receivedobservable"></span></p>', viewModel: function (params) { constructorCallCount++ this.receivedobservable = params.suppliedobservable this.dispose = function () { this.wasDisposed = true } // See we didn't get the original observable instance. Instead we got a read-only computed property. expect(this.receivedobservable).not.toBe(rootViewModel.myobservable) expect(isComputed(this.receivedobservable)).toBe(true) expect(isWritableObservable(this.receivedobservable)).toBe(false) // The $raw value for this param is a computed property whose value is raw result // of evaluating the binding value. Since the raw result in this case is itself not // observable, it's the same value as the regular (non-$raw) supplied parameter. expect(isComputed(params.$raw.suppliedobservable)).toBe(true) expect(params.$raw.suppliedobservable()).toBe(params.suppliedobservable()) } }) // Bind, using an expression that evaluates the observable during binding testNode.innerHTML = '<test-component params=\'suppliedobservable: myobservable().split("").reverse().join("")\'></test-component>' applyBindings(rootViewModel, testNode) jasmine.Clock.tick(1) expect(testNode.firstChild).toContainText('the string reversed: ahplA') var componentViewModelInstance = dataFor(testNode.firstChild.firstChild) expect(constructorCallCount).toBe(1) expect(rootViewModel.myobservable.getSubscriptionsCount()).toBe(1) // See that mutating the underlying observable modifies the supplied computed property, // but doesn't cause the component to tear down rootViewModel.myobservable('Beta') expect(testNode.firstChild).toContainText('the string reversed: ateB') expect(constructorCallCount).toBe(1) expect(dataFor(testNode.firstChild.firstChild)).toBe(componentViewModelInstance) // No new viewmodel needed expect(componentViewModelInstance.wasDisposed).not.toBe(true) expect(rootViewModel.myobservable.getSubscriptionsCount()).toBe(1) // No extra subscription needed // See also that subscriptions to the evaluated observables are disposed // when the custom element is cleaned cleanNode(testNode) expect(componentViewModelInstance.wasDisposed).toBe(true) expect(rootViewModel.myobservable.getSubscriptionsCount()).toBe(0) }) it('Is possible to pass expressions that can vary observably and evaluate as writable observable instances', function () { var constructorCallCount = 0 components.register('test-component', { template: '<input data-bind="value: myval"/>', viewModel: function (params) { constructorCallCount++ this.myval = params.somevalue // See we received a writable observable expect(isWritableObservable(this.myval)).toBe(true) // See we received a computed, not either of the original observables expect(isComputed(this.myval)).toBe(true) // See we can reach the original inner observable directly if needed via $raw // (e.g., because it has subobservables or similar) var originalObservable = params.$raw.somevalue() expect(isObservable(originalObservable)).toBe(true) expect(isComputed(originalObservable)).toBe(false) if (originalObservable() === 'inner1') { expect(originalObservable).toBe(innerObservable) // See there's no wrapper } } }) // Bind to a viewmodel with nested observables; see the expression is evaluated as expected // The component itself doesn't have to know or care that the supplied value is nested - the // custom element syntax takes care of producing a single computed property that gives the // unwrapped inner value. var innerObservable = observable('inner1'), outerObservable = observable({ inner: innerObservable }) testNode.innerHTML = '<test-component params="somevalue: outer().inner"></test-component>' applyBindings({ outer: outerObservable }, testNode) jasmine.Clock.tick(1) expect(testNode.childNodes[0].childNodes[0].value).toEqual('inner1') expect(outerObservable.getSubscriptionsCount()).toBe(1) expect(innerObservable.getSubscriptionsCount()).toBe(1) expect(constructorCallCount).toBe(1) // See we can mutate the inner value and see the result show up innerObservable('inner2') expect(testNode.childNodes[0].childNodes[0].value).toEqual('inner2') expect(outerObservable.getSubscriptionsCount()).toBe(1) expect(innerObservable.getSubscriptionsCount()).toBe(1) expect(constructorCallCount).toBe(1) // See that we can mutate the observable from within the component testNode.childNodes[0].childNodes[0].value = 'inner3' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(innerObservable()).toEqual('inner3') // See we can mutate the outer value and see the result show up (cleaning subscriptions to the old inner value) var newInnerObservable = observable('newinner') outerObservable({ inner: newInnerObservable }) expect(testNode.childNodes[0].childNodes[0].value).toEqual('newinner') expect(outerObservable.getSubscriptionsCount()).toBe(1) expect(innerObservable.getSubscriptionsCount()).toBe(0) expect(newInnerObservable.getSubscriptionsCount()).toBe(1) expect(constructorCallCount).toBe(1) // See that we can mutate the new observable from within the component testNode.childNodes[0].childNodes[0].value = 'newinner2' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(newInnerObservable()).toEqual('newinner2') expect(innerObservable()).toEqual('inner3') // original one hasn't changed // See that subscriptions are disposed when the component is cleanNode(testNode) expect(outerObservable.getSubscriptionsCount()).toBe(0) expect(innerObservable.getSubscriptionsCount()).toBe(0) expect(newInnerObservable.getSubscriptionsCount()).toBe(0) }) it('Supplies any custom parameter called "$raw" in preference to the function that yields raw parameter values', function () { var constructorCallCount = 0, suppliedValue = {} components.register('test-component', { template: 'Ignored', viewModel: function (params) { constructorCallCount++ expect(params.$raw).toBe(suppliedValue) } }) testNode.innerHTML = '<test-component params="$raw: suppliedValue"></test-component>' applyBindings({ suppliedValue: suppliedValue }, testNode) jasmine.Clock.tick(1) expect(constructorCallCount).toBe(1) }) it('Disposes the component when the custom element is cleaned', function () { // This is really a behavior of the component binding, not custom elements. // This spec just shows that custom elements don't break it for any reason. var componentViewModel = { dispose: function () { this.wasDisposed = true } } components.register('test-component', { template: 'custom element', viewModel: { instance: componentViewModel } }) testNode.innerHTML = '<test-component></test-component>' // See it binds properly applyBindings(null, testNode) jasmine.Clock.tick(1) expect(testNode.firstChild).toContainHtml('custom element') // See the viewmodel is disposed when the corresponding DOM element is expect(componentViewModel.wasDisposed).not.toBe(true) cleanNode(testNode.firstChild) expect(componentViewModel.wasDisposed).toBe(true) }) it('Can nest custom elements', function () { // Note that, for custom elements to work properly on IE < 9, you *must*: // (1) Reference jQuery // (2) Register any component that will be used as a custom element // (e.g., components.register(...)) *before* the browser parses any // markup containing that custom element // // The reason for (2) is the same as the well-known issue that IE < 9 cannot // parse markup containing HTML5 elements unless you've already called // document.createElement(thatElementName) first. Our old-IE compatibility // code causes this to happen automatically for all registered components. // // The reason for (1) is that KO's built-in simpleHtmlParse logic uses .innerHTML // on a <div> that is not attached to any document, which means the trick from // (1) does not work. Referencing jQuery overrides the HTML parsing logic to // uses jQuery's, which uses a temporary document fragment, and our old-IE compatibility // code has patched createDocumentFragment to enable preregistered components // to act as custom elements in that document fragment. If we wanted, we could // amend simpleHtmlParse to use a document fragment, but it seems unlikely that // anyone targetting IE < 9 would not be using jQuery. this.after(function () { components.unregister('outer-component') components.unregister('inner-component') }) components.register('inner-component', { template: 'the inner component with value [<span data-bind="text: innerval"></span>]' }) components.register('outer-component', { template: 'the outer component [<inner-component params="innerval: outerval.innerval"></inner-component>] goodbye' }) var initialMarkup = '<div>hello [<outer-component params="outerval: outerval"></outer-component>] world</div>' testNode.innerHTML = initialMarkup applyBindings({ outerval: { innerval: 'my value' } }, testNode) try { jasmine.Clock.tick(1) expect(testNode).toContainText('hello [the outer component [the inner component with value [my value]] goodbye] world') } catch (ex) { if (ex.message.indexOf('Unexpected call to method or property access.') >= 0) { // On IE < 9, this scenario is only supported if you have referenced jQuery. // So don't consider this to be a failure if jQuery isn't referenced. if (!window.jQuery) { return } } throw ex } }) it('Is possible to set up components that receive, inject, and bind templates supplied by the user of the component (sometimes called "templated components" or "transclusion")', function () { // This spec repeats assertions made in other specs elsewhere, but is useful to prove the end-to-end technique this.after(function () { components.unregister('special-list') }) // First define a reusable 'special-list' component that produces a <ul> in which the <li>s are filled with the supplied template // Note: It would be even simpler to write "template: { nodes: $componentTemplateNodes }", which would also work. // However it's useful to have test coverage for the more longwinded approach of passing nodes via your // viewmodel as well, so retaining the longer syntax for this test. components.register('special-list', { template: '<ul class="my-special-list" data-bind="foreach: specialListItems">' + '<li data-bind="template: { nodes: $component.suppliedItemTemplate }">' + '</li>' + '</ul>', viewModel: { createViewModel: function (params, componentInfo) { return { specialListItems: params.items, suppliedItemTemplate: componentInfo.templateNodes } } } }) // Now make some view markup that uses <special-list> and supplies a template to be used inside each list item testNode.innerHTML = '<h1>Cheeses</h1>' + '<special-list params="items: cheeses">' + '<em data-bind="text: name">x</em> has quality <em data-bind="text: quality">x</em>' + '</special-list>' // Finally, bind it all to some data applyBindings({ cheeses: [ { name: 'brie', quality: 7 }, { name: 'cheddar', quality: 9 }, { name: 'roquefort', quality: 3 } ] }, testNode) jasmine.Clock.tick(1) expect(testNode.childNodes[0]).toContainText('Cheeses') expect(testNode.childNodes[1].childNodes[0].tagName.toLowerCase()).toEqual('ul') expect(testNode.childNodes[1].childNodes[0].className).toEqual('my-special-list') expect(testNode.childNodes[1].childNodes[0]).toContainHtml( '<li data-bind="template: { nodes: $component.supplieditemtemplate }">' + '<em data-bind="text: name">brie</em> has quality <em data-bind="text: quality">7</em>' + '</li>' + '<li data-bind="template: { nodes: $component.supplieditemtemplate }">' + '<em data-bind="text: name">cheddar</em> has quality <em data-bind="text: quality">9</em>' + '</li>' + '<li data-bind="template: { nodes: $component.supplieditemtemplate }">' + '<em data-bind="text: name">roquefort</em> has quality <em data-bind="text: quality">3</em>' + '</li>' ) }) it('Should call an afterRender callback function', function () { components.register('test-component', { template: 'custom element'}) testNode.innerHTML = '<test-component data-bind="afterRender: callback"></test-component>' var callbacks = 0, viewModel = { callback: function (nodes, data) { expect(nodes.length).toEqual(1) expect(nodes[0]).toEqual(testNode.childNodes[0].childNodes[0]) expect(data).toEqual(undefined) callbacks++ } } applyBindings(viewModel, testNode) expect(callbacks).toEqual(0) jasmine.Clock.tick(1) expect(testNode).toContainHtml('<test-component data-bind="afterrender: callback">custom element</test-component>') }) })
the_stack
import { Action, Thunk, Computed, Reducer, Generic, ActionOn, ThunkOn, createStore, action, thunk, computed, actionOn, thunkOn, reducer, } from 'easy-peasy'; interface Foo { name: string; age: number; } interface StoreModel { one: One; two: Two; three: Three; four: Four; five: Five; six: Six; seven: Seven; eight: Eight; nine: Nine; ten: Ten; } interface Deepest { one: string; two: Action<Deepest, string>; } interface One { deep: { deeper: { deepest: Deepest; }; }; tooDeep: { deep: { deeper: { deepest: Deepest; }; }; }; one: OneOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<One, string>; thirteen: Thunk<One, string>; fourteen: Computed<One, string, StoreModel>; fifteen: ActionOn<One>; sixteen: ThunkOn<One>; seventeen: Reducer<{ name: string }>; } interface OneOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Two { one: TwoOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Two, string>; thirteen: Thunk<Two, string>; fourteen: Computed<Two, string, StoreModel>; fifteen: ActionOn<Two>; sixteen: ThunkOn<Two>; seventeen: Reducer<{ name: string }>; } interface TwoOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Three { one: ThreeOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Three, string>; thirteen: Thunk<Three, string>; fourteen: Computed<Three, string, StoreModel>; fifteen: ActionOn<Three>; sixteen: ThunkOn<Three>; seventeen: Reducer<{ name: string }>; } interface ThreeOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Four { one: FourOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Four, string>; thirteen: Thunk<Four, string>; fourteen: Computed<Four, string, StoreModel>; fifteen: ActionOn<Four>; sixteen: ThunkOn<Four>; seventeen: Reducer<{ name: string }>; } interface FourOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Five { one: FiveOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Five, string>; thirteen: Thunk<Five, string>; fourteen: Computed<Five, string, StoreModel>; fifteen: ActionOn<Five>; sixteen: ThunkOn<Five>; seventeen: Reducer<{ name: string }>; } interface FiveOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Six { one: SixOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Six, string>; thirteen: Thunk<Six, string>; fourteen: Computed<Six, string, StoreModel>; fifteen: ActionOn<Six>; sixteen: ThunkOn<Six>; seventeen: Reducer<{ name: string }>; } interface SixOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Seven { one: SevenOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Seven, string>; thirteen: Thunk<Seven, string>; fourteen: Computed<Seven, string, StoreModel>; fifteen: ActionOn<Seven>; sixteen: ThunkOn<Seven>; seventeen: Reducer<{ name: string }>; } interface SevenOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Eight { one: EightOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Eight, string>; thirteen: Thunk<Eight, string>; fourteen: Computed<Eight, string, StoreModel>; fifteen: ActionOn<Eight>; sixteen: ThunkOn<Eight>; seventeen: Reducer<{ name: string }>; } interface EightOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Nine { one: NineOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Nine, string>; thirteen: Thunk<Nine, string>; fourteen: Computed<Nine, string, StoreModel>; fifteen: ActionOn<Nine>; sixteen: ThunkOn<Nine>; seventeen: Reducer<{ name: string }>; } interface NineOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } interface Ten { one: TenOne; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; eleven: string; twelve: Action<Ten, string>; thirteen: Thunk<Ten, string>; fourteen: Computed<Ten, string, StoreModel>; fifteen: ActionOn<Ten>; sixteen: ThunkOn<Ten>; seventeen: Reducer<{ name: string }>; } interface TenOne { one: string; two: boolean; three: { [key: string]: Foo }; four: Map<string, number>; five: number; six: string | boolean | number; seven: object; eight?: Set<string>; nine: Date; ten: Array<number>; } const model: StoreModel = { one: { deep: { deeper: { deepest: { one: 'one', two: action((state, payload) => { state.one = payload; }), }, }, }, tooDeep: { deep: { deeper: { deepest: { one: 'one', two: action((state, payload) => { state.one = payload; }), }, }, }, }, one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, two: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, three: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, four: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, five: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, six: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, seven: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, eight: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, nine: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, ten: { one: { one: 'one', two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], }, two: true, three: { foo: { name: 'foo', age: 1, }, }, four: new Map(), five: 5, six: 'six', seven: { anything: 'anything' }, eight: new Set(), nine: new Date(), ten: [1], eleven: '11', twelve: action((state, payload) => { state.six = payload; }), thirteen: thunk((actions, payload) => { actions.twelve(payload); }), fourteen: computed( [(state) => state.one.one, (state, globalState) => globalState.one.one], (one, two) => { return one + two; }, ), fifteen: actionOn( (actions) => actions.thirteen, (state, target) => { state.six = target.payload; }, ), sixteen: thunkOn( (actions) => actions.thirteen, (actions, target) => { actions.thirteen(target.payload); }, ), seventeen: reducer((state = { name: 'foo' }) => state), }, }; const store = createStore(model); store.getState().one.deep.deeper.deepest.one; // typings:expect-error store.getState().one.deep.deeper.deepest.two; // ❗️ This has hit our maximum depth level for mapping out state, therefore // the action still exists on the type where you would expect it not to store.getState().one.tooDeep.deep.deeper.deepest.two; store.getState().one.one.seven; store.getState().four.seven; store.getState().ten.one.ten[0]; store.getActions().one.thirteen('foo'); store.getActions().ten.thirteen('foo');
the_stack
* @fileoverview Mixin that implements lazy typesetting * * @author dpvc@mathjax.org (Davide Cervone) */ import {MathDocumentConstructor, ContainerList} from '../../core/MathDocument.js'; import {MathItem, STATE, newState} from '../../core/MathItem.js'; import {HTMLMathItem} from '../../handlers/html/HTMLMathItem.js'; import {HTMLDocument} from '../../handlers/html/HTMLDocument.js'; import {HTMLHandler} from '../../handlers/html/HTMLHandler.js'; import {handleRetriesFor} from '../../util/Retries.js'; import {OptionList} from '../../util/Options.js'; /** * Add the needed function to the window object. */ declare const window: { requestIdleCallback: (callback: () => void) => void; addEventListener: ((type: string, handler: (event: Event) => void) => void); matchMedia: (type: string) => { addListener: (handler: (event: Event) => void) => void; }; }; /** * Generic constructor for Mixins */ export type Constructor<T> = new(...args: any[]) => T; /** * A set of lazy MathItems */ export type LazySet = Set<string>; /*==========================================================================*/ /** * The data to map expression marker IDs back to their MathItem. */ export class LazyList<N, T, D> { /** * The next ID to use */ protected id: number = 0; /** * The map from IDs to MathItems */ protected items: Map<string, LazyMathItem<N, T, D>> = new Map(); /** * Add a MathItem to the list and return its ID * * @param {LazyMathItem} math The item to add * @return {string} The id for the newly added item */ public add(math: LazyMathItem<N, T, D>): string { const id = String(this.id++); this.items.set(id, math); return id; } /** * Get the MathItem with the given ID * * @param {string} id The ID of the MathItem to get * @return {LazyMathItem} The MathItem having that ID (if any) */ public get(id: string): LazyMathItem<N, T, D> { return this.items.get(id); } /** * Remove an item from the map * * @param {string} id The ID of the MathItem to remove */ public delete(id: string) { return this.items.delete(id); } } /*==========================================================================*/ newState('LAZYALWAYS', STATE.FINDMATH + 3); /** * The attribute to use for the ID on the marker node */ export const LAZYID = 'data-mjx-lazy'; /** * The properties added to MathItem for lazy typesetting * * @template N The HTMLElement node class * @template T The Text node class * @template D The Document class */ export interface LazyMathItem<N, T, D> extends MathItem<N, T, D> { /** * True when the MathItem needs to be lazy compiled */ lazyCompile: boolean; /** * True when the MathItem needs to be lazy displayed */ lazyTypeset: boolean; /** * The DOM node used to mark the location of the math to be lazy typeset */ lazyMarker: N; /** * True if this item is a TeX MathItem */ lazyTex: boolean; } /** * The mixin for adding lazy typesetting to MathItems * * @param {B} BaseMathItem The MathItem class to be extended * @return {AssistiveMathItem} The augmented MathItem class * * @template N The HTMLElement node class * @template T The Text node class * @template D The Document class * @template B The MathItem class to extend */ export function LazyMathItemMixin<N, T, D, B extends Constructor<HTMLMathItem<N, T, D>>>( BaseMathItem: B ): Constructor<LazyMathItem<N, T, D>> & B { return class extends BaseMathItem { /** * True when this item should be skipped during compilation * (i.e., it is not showing on screen, and has not needed to be * compiled for a later TeX expression that is showing). */ public lazyCompile: boolean = true; /** * True when this item should be skipped during typesetting * (i.e., it has not yet appeared on screen). */ public lazyTypeset: boolean = true; /** * The marker DOM node for this item. */ public lazyMarker: N; /** * True if this is a TeX expression. */ public lazyTex: boolean = false; /** * @override */ constructor(...args: any[]) { super(...args); if (!this.end.node) { // // This is a MathItem that isn't in the document // (so either from semantic enrich, or from convert()) // and should be typeset as usual. // this.lazyCompile = this.lazyTypeset = false; } } /** * Initially don't compile math, just use an empty math item, * then when the math comes into view (or is before something * that comes into view), compile it properly and mark the item * as only needing to be typeset. * * @override */ public compile(document: LazyMathDocument<N, T, D>) { if (!this.lazyCompile) { super.compile(document); return; } if (this.state() < STATE.COMPILED) { this.lazyTex = (this.inputJax.name === 'TeX'); this.root = document.mmlFactory.create('math'); this.state(STATE.COMPILED); } } /** * Only update the state if restore is true or false (null is used for setting lazy states) * @override */ public state(state: number = null, restore: boolean = false) { if (restore !== null) super.state(state, restore); return super.state(); } /** * Initially, just insert a marker for where the math will go, and * track it in the lazy list. Then, when it comes into view, * typeset it properly. * * @override */ public typeset(document: LazyMathDocument<N, T, D>) { if (!this.lazyTypeset) { super.typeset(document); return; } if (this.state() < STATE.TYPESET) { const adaptor = document.adaptor; if (!this.lazyMarker) { const id = document.lazyList.add(this); this.lazyMarker = adaptor.node('mjx-lazy', {[LAZYID]: id}); this.typesetRoot = adaptor.node('mjx-container', {}, [this.lazyMarker]); } this.state(STATE.TYPESET); } } /** * When the MathItem is added to the page, set the observer to watch * for it coming into view so that it can be typeset. * * @override */ public updateDocument(document: LazyMathDocument<N, T, D>) { super.updateDocument(document); if (this.lazyTypeset) { document.lazyObserver.observe(this.lazyMarker as any as Element); } } }; } /*==========================================================================*/ /** * The properties added to MathDocument for lazy typesetting * * @template N The HTMLElement node class * @template T The Text node class * @template D The Document class */ export interface LazyMathDocument<N, T, D> extends HTMLDocument<N, T, D> { /** * The Intersection Observer used to track the appearance of the expression markers */ lazyObserver: IntersectionObserver; /** * The mapping of markers to MathItems */ lazyList: LazyList<N, T, D>; /** * The containers whose contents should always be typeset */ lazyAlwaysContainers: N[]; /** * A function that will typeset all the remaining expressions (e.g., for printing) */ lazyTypesetAll(): Promise<void>; /** * Mark the math items that are to be always typeset */ lazyAlways(): void; } /** * The mixin for adding lazy typesetting to MathDocuments * * @param {B} BaseDocument The MathDocument class to be extended * @return {LazyMathDocument} The Lazy MathDocument class * * @template N The HTMLElement node class * @template T The Text node class * @template D The Document class * @template B The MathDocument class to extend */ export function LazyMathDocumentMixin<N, T, D, B extends MathDocumentConstructor<HTMLDocument<N, T, D>>>( BaseDocument: B ): MathDocumentConstructor<HTMLDocument<N, T, D>> & B { return class BaseClass extends BaseDocument { /** * @override */ public static OPTIONS: OptionList = { ...BaseDocument.OPTIONS, lazyMargin: '200px', lazyAlwaysTypeset: null, renderActions: { ...BaseDocument.OPTIONS.renderActions, lazyAlways: [STATE.LAZYALWAYS, 'lazyAlways', '', false] } }; /** * The Intersection Observer used to track the appearance of the expression markers */ public lazyObserver: IntersectionObserver; /** * The mapping of markers to MathItems */ public lazyList: LazyList<N, T, D>; /** * The containers whose contents should always be typeset */ public lazyAlwaysContainers: N[] = null; /** * Index of last container where math was found in lazyAlwaysContainers */ public lazyAlwaysIndex: number = 0; /** * A promise to make sure our compiling/typesetting is sequential */ protected lazyPromise: Promise<void> = Promise.resolve(); /** * The function used to typeset a set of lazy MathItems. * (uses requestIdleCallback if available, or setTimeout otherwise) */ protected lazyProcessSet: () => void; /** * True when a set of MathItems is queued for being processed */ protected lazyIdle: boolean = false; /** * The set of items that have come into view */ protected lazySet: LazySet = new Set(); /** * Augment the MathItem class used for this MathDocument, * then create the intersection observer and lazy list, * and bind the lazyProcessSet function to this instance * so it can be used as a callback more easily. Add the * event listeners to typeset everything before printing. * * @override * @constructor */ constructor(...args: any[]) { super(...args); // // Use the LazyMathItem for math items // this.options.MathItem = LazyMathItemMixin<N, T, D, Constructor<HTMLMathItem<N, T, D>>>(this.options.MathItem); // // Allocate a process bit for lazyAlways // const ProcessBits = (this.constructor as typeof HTMLDocument).ProcessBits; !ProcessBits.has('lazyAlways') && ProcessBits.allocate('lazyAlways'); // // Set up the lazy observer and other needed data // this.lazyObserver = new IntersectionObserver(this.lazyObserve.bind(this), {rootMargin: this.options.lazyMargin}); this.lazyList = new LazyList<N, T, D>(); const callback = this.lazyHandleSet.bind(this); this.lazyProcessSet = (window && window.requestIdleCallback ? () => window.requestIdleCallback(callback) : () => setTimeout(callback, 10)); // // Install print listeners to typeset the rest of the document before printing // if (window) { let done = false; const handler = () => { !done && this.lazyTypesetAll(); done = true; }; window.matchMedia('print').addListener(handler); // for Safari window.addEventListener('beforeprint', handler); // for everyone else } } /** * Check all math items for those that should always be typeset */ public lazyAlways() { if (!this.lazyAlwaysContainers || this.processed.isSet('lazyAlways')) return; for (const item of this.math) { const math = item as LazyMathItem<N, T, D>; if (math.lazyTypeset && this.lazyIsAlways(math)) { math.lazyCompile = math.lazyTypeset = false; } } this.processed.set('lazyAlways'); } /** * Check if the MathItem is in one of the containers to always typeset. * (start looking using the last container where math was found, * in case the next math is in the same container). * * @param {LazyMathItem<N,T,D>} math The MathItem to test * @return {boolean} True if one of the document's containers holds the MathItem */ protected lazyIsAlways(math: LazyMathItem<N, T, D>): boolean { if (math.state() < STATE.LAZYALWAYS) { math.state(STATE.LAZYALWAYS); const node = math.start.node; const adaptor = this.adaptor; const start = this.lazyAlwaysIndex; const end = this.lazyAlwaysContainers.length; do { const container = this.lazyAlwaysContainers[this.lazyAlwaysIndex]; if (adaptor.contains(container, node)) return true; if (++this.lazyAlwaysIndex >= end) { this.lazyAlwaysIndex = 0; } } while (this.lazyAlwaysIndex !== start); } return false; } /** * @override */ public state(state: number, restore: boolean = false) { super.state(state, restore); if (state < STATE.LAZYALWAYS) { this.processed.clear('lazyAlways'); } return this; } /** * Function to typeset all remaining expressions (for printing, etc.) * * @return {Promise} Promise that is resolved after the typesetting completes. */ public async lazyTypesetAll(): Promise<void> { // // The state we need to go back to (COMPILED or TYPESET). // let state = STATE.LAST; // // Loop through all the math... // for (const item of this.math) { const math = item as LazyMathItem<N, T, D>; // // If it is not lazy compile or typeset, skip it. // if (!math.lazyCompile && !math.lazyTypeset) continue; // // Mark the state that we need to start at. // if (math.lazyCompile) { math.state(STATE.COMPILED - 1); state = STATE.COMPILED; } else { math.state(STATE.TYPESET - 1); if (STATE.TYPESET < state) state = STATE.TYPESET; } // // Mark it as not lazy and remove it from the observer. // math.lazyCompile = math.lazyTypeset = false; math.lazyMarker && this.lazyObserver.unobserve(math.lazyMarker as any as Element); } // // If something needs updating // if (state === STATE.LAST) return Promise.resolve(); // // Reset the document state to the starting state that we need. // this.state(state - 1, null); // // Save the SVG font cache and set it to "none" temporarily // (needed by Firefox, which doesn't seem to process the // xlinks otherwise). // const fontCache = this.outputJax.options.fontCache; if (fontCache) this.outputJax.options.fontCache = 'none'; // // Typeset the math and put back the font cache when done. // this.reset(); return handleRetriesFor(() => this.render()).then(() => { if (fontCache) this.outputJax.options.fontCache = fontCache; }); } /** * The function used by the IntersectionObserver to monitor the markers coming into view. * When one (or more) does, add its math item to or remove it from the set to be processed, and * if added to the set, queue an idle task, if one isn't already pending. * * The idea is, if you start scrolling and reveal an expression marker, we add it into * the set and queue an idle task. But if you keep scrolling and the idle task hasn't run * yet, the mark may move out of view, and we don't want to waste time typesetting it, so * we remove it from the set. When you stop scrolling and the idle task finally runs, it * takes the expressions still in the set (those should be the ones still in view) and * starts typesetting them after having created a new set to add expressions to. If one * of the expressions loads an extension and the idle task has to pause, you can add new * expressions into the new list (or remove them from there), but can't affect the * current idle-task list. Those will be typeset even if they scroll out of view at that * point. * * Note that it is possible that an expression is added to the set and then removed * before the idle task runs, and it could be that the set is empty when it does. Then * the idle task does nothing, and new expressions are added to the new set to be * processed by the next idle task. * * @param {IntersectionObserverEntry[]} entries The markers that have come into or out of view. */ protected lazyObserve(entries: IntersectionObserverEntry[]) { for (const entry of entries) { const id = this.adaptor.getAttribute(entry.target as any as N, LAZYID); const math = this.lazyList.get(id); if (!math) continue; if (!entry.isIntersecting) { this.lazySet.delete(id); continue; } this.lazySet.add(id); if (!this.lazyIdle) { this.lazyIdle = true; this.lazyProcessSet(); } } } /** * Mark the MathItems in the set as needing compiling or typesetting, * and for TeX items, make sure the earlier TeX items are typeset * (in case they have automatic numbers, or define macros, etc.). * Then rerender the page to update the visible equations. */ protected lazyHandleSet() { const set = this.lazySet; this.lazySet = new Set(); this.lazyPromise = this.lazyPromise.then(() => { let state = this.compileEarlierItems(set) ? STATE.COMPILED : STATE.TYPESET; state = this.resetStates(set, state); this.state(state - 1, null); // reset processed bits to allow reprocessing return handleRetriesFor(() => { this.render(); this.lazyIdle = false; }); }); } /** * Set the states of the MathItems in the set, depending on * whether they need compiling or just typesetting, and * update the state needed for the page rerendering. * * @param {LazySet} set The set of math items to update * @param {number} state The state needed for the items * @return {number} The updated state based on the items */ protected resetStates(set: LazySet, state: number): number { for (const id of set.values()) { const math = this.lazyList.get(id); if (math.lazyCompile) { math.state(STATE.COMPILED - 1); state = STATE.COMPILED; } else { math.state(STATE.TYPESET - 1); } math.lazyCompile = math.lazyTypeset = false; math.lazyMarker && this.lazyObserver.unobserve(math.lazyMarker as any as Element); } return state; } /** * Mark any TeX items (earlier than the ones in the set) to be compiled. * * @param {LazySet} set The set of items that are newly visible * @return {boolean} True if there are TeX items to be typeset */ protected compileEarlierItems(set: LazySet): boolean { let math = this.earliestTex(set); if (!math) return false; let compile = false; for (const item of this.math) { const earlier = item as LazyMathItem<N, T, D>; if (earlier === math || !earlier?.lazyCompile || !earlier.lazyTex) { break; } earlier.lazyCompile = false; earlier.lazyMarker && this.lazyObserver.unobserve(earlier.lazyMarker as any as Element); earlier.state(STATE.COMPILED - 1); compile = true; } return compile; } /** * Find the earliest TeX math item in the set, if any. * * @param {LazySet} set The set of newly visble math items * @return {LazyMathItem} The earliest TeX math item in the set, if any */ protected earliestTex(set: LazySet): LazyMathItem<N, T, D> { let min: number = null; let minMath = null; for (const id of set.values()) { const math = this.lazyList.get(id); if (!math.lazyTex) continue; if (min === null || parseInt(id) < min) { min = parseInt(id); minMath = math; } } return minMath; } /** * If any of the removed items are observed or in the lazy list, remove them. * * @override */ public clearMathItemsWithin(containers: ContainerList<N>) { const items = super.clearMathItemsWithin(containers) as LazyMathItem<N, T, D>[]; for (const math of items) { const marker = math.lazyMarker; if (marker) { this.lazyObserver.unobserve(marker as any as Element); this.lazyList.delete(this.adaptor.getAttribute(marker, LAZYID)); } } return items; } /** * @override */ public render() { // // Get the containers whose content should always be typeset // const always = this.options.lazyAlwaysTypeset; this.lazyAlwaysContainers = !always ? null : this.adaptor.getElements(Array.isArray(always) ? always : [always], this.document); this.lazyAlwaysIndex = 0; super.render(); return this; } }; } /*==========================================================================*/ /** * Add lazy typesetting support to a Handler instance * * @param {Handler} handler The Handler instance to enhance * @return {Handler} The handler that was modified (for purposes of chaining extensions) * * @template N The HTMLElement node class * @template T The Text node class * @template D The Document class */ export function LazyHandler<N, T, D>(handler: HTMLHandler<N, T, D>): HTMLHandler<N, T, D> { // // Only update the document class if we can handle IntersectionObservers // if (typeof IntersectionObserver !== 'undefined') { handler.documentClass = LazyMathDocumentMixin<N, T, D, MathDocumentConstructor<HTMLDocument<N, T, D>>>( handler.documentClass ) as typeof HTMLDocument; } return handler; }
the_stack
import { ObjectID } from 'mongodb'; import { advanceTo, advanceBy } from "jest-date-mock"; import { QueryFilter, GraphbackCoreMetadata } from '@graphback/core'; import { Context, createTestingContext } from "./__util__"; import { buildSchema } from 'graphql'; import { MongoDBDataProvider } from '../src/MongoDBDataProvider'; describe('MongoDBDataProvider Basic CRUD', () => { interface Todo { _id: ObjectID; text: string; } let context: Context; const fields = ["_id", "text"]; const todoSchema = ` """ @model """ type Todos { _id: GraphbackObjectID! text: String } scalar GraphbackObjectID `; const defaultTodoSeed = [ { text: 'todo' }, { text: 'todo2' } ] afterEach(async (done) => { if (context) { await context.server.stop(); } done(); }) afterEach(async () => context?.server?.stop()); test('Test missing "_id: GraphbackObjectID" primary key', async () => { const schema = ` """ @model """ type MissingPrimaryKeyModel { id: ID! text: String } `; const defautConfig = { "create": true, "update": true, "findOne": true, "find": true, "delete": true, "subCreate": true, "subUpdate": true, "subDelete": true } try { const metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, buildSchema(schema)); const models = metadata.getModelDefinitions() for (const model of models) { new MongoDBDataProvider(model, undefined); } expect(true).toBeFalsy(); // should not reach here } catch (error) { expect(error.message).toEqual('Model "MissingPrimaryKeyModel" must contain a "_id: GraphbackObjectID" primary key. Visit https://graphback.dev/docs/model/datamodel#mongodb to see how to set up one for your MongoDB model.'); } }); test('Test mongo crud', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: defaultTodoSeed } }); let todo: Todo = await context.providers.Todos.create({ text: 'create a todo', }); expect(todo.text).toEqual('create a todo'); todo = await context.providers.Todos.update({ _id: todo._id, text: 'my updated first todo', }, fields); expect(todo.text).toEqual('my updated first todo'); const data = await context.providers.Todos.delete({ _id: todo._id }, fields); expect(data._id).toEqual(todo._id); }); test('find first 1 todo(s) excluding first todo', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: defaultTodoSeed } }); const todos = await context.providers.Todos.findBy({ page: { limit: 1, offset: 1 } }, ["text"]); // check that count is total number of seeded Todos const count = await context.providers.Todos.count({}); expect(count).toEqual(defaultTodoSeed.length); // check limit applied expect(todos.length).toEqual(1); expect(todos[0].text).toEqual('todo2'); }); test('find Todo by text', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: defaultTodoSeed } }); const all = await context.providers.Todos.findBy(); const todos: Todo[] = await context.providers.Todos.findBy({ filter: { text: { eq: all[0].text }, } }, ["_id"]); expect(todos.length).toBeGreaterThan(0); const count = await context.providers.Todos.count({ text: { eq: all[0].text } }) expect(count).toEqual(todos.length); }); test('find Todo by text, limit defaults to complete set', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: defaultTodoSeed } }); const text = 'todo-test'; for (let i = 0; i < 11; i++) { await context.providers.Todos.create({ text, }); } const todos: Todo[] = await context.providers.Todos.findBy({ filter: { text: { eq: text } }, page: { offset: 0 } }, fields); expect(todos.length).toEqual(11); const count = await context.providers.Todos.count({ text: { eq: text } }); expect(count).toEqual(11); }); test('find by text offset defaults to 0', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: defaultTodoSeed } }); const text = 'todo-test'; for (let i = 0; i < 2; i++) { await context.providers.Todos.create({ text, }); } const todos: Todo[] = await context.providers.Todos.findBy({ filter: { text: { eq: text } }, page: { limit: 1 } }, fields); expect(todos[0].text).toEqual(text); }); test('find first 1 todos by text', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: defaultTodoSeed } }); const text = 'todo-test'; for (let i = 0; i < 2; i++) { await context.providers.Todos.create({ text, }); } const todos: Todo[] = await context.providers.Todos.findBy({ filter: { text: { eq: text } }, page: { limit: 1, offset: 0 } }, fields); expect(todos.length).toEqual(1); expect(todos[0].text).toEqual(text); }); test('test orderby w/o order', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: [ { text: 'todo3' }, { text: 'todo1' }, { text: 'todo4' }, { text: 'todo2' }, { text: 'todo5' }, ] } }); const todos = await context.providers.Todos.findBy({ filter: { text: { contains: 'todo' } }, orderBy: { field: 'text' } }, fields); for (let t = 0; t < todos.length; t++) { expect(todos[t].text).toEqual(`todo${t + 1}`); } }); test('test orderby with desc order', async () => { context = await createTestingContext(todoSchema, { seedData: { Todos: [ { text: 'todo3' }, { text: 'todo1' }, { text: 'todo4' }, { text: 'todo2' }, { text: 'todo5' }, ] } }); const todos = await context.providers.Todos.findBy({ filter: { text: { contains: 'todo' } }, orderBy: { field: 'text', order: 'desc' } }, fields); for (let t = 0; t < todos.length; t++) { expect(todos[t].text).toEqual(`todo${5 - t}`); } }); test('createdAt', async () => { context = await createTestingContext(` """ @model @versioned """ type Note { _id: GraphbackObjectID! text: String } scalar GraphbackObjectID `); const cDate = new Date(2020, 5, 26, 18, 29, 23); advanceTo(cDate); const res = await context.providers.Note.create({ text: 'asdf' }); expect(res.createdAt).toEqual(cDate.getTime()); expect(res.createdAt).toEqual(res.updatedAt); }) test('updatedAt', async () => { context = await createTestingContext(` """ @model @versioned """ type Note { _id: GraphbackObjectID! text: String } scalar GraphbackObjectID `); const createDate = new Date(2020, 5, 26, 18, 29, 23); advanceTo(createDate); const res = await context.providers.Note.create({ text: 'asdf' }); expect(res.updatedAt).toEqual(createDate.getTime()); advanceBy(3000); const next = await context.providers.Note.update({ ...res, text: 'asdftrains' }, ["updatedAt", "createdAt"]); const updateDate = new Date(); expect(next.updatedAt).toEqual(updateDate.getTime()); expect(next.createdAt).toEqual(createDate.getTime()) }) test('select only requested fields', async () => { context = await createTestingContext(` """ @model """ type Todos { _id: GraphbackObjectID! text: String, description: String } scalar GraphbackObjectID `, { seedData: { Todos: [ { text: 'todo1', description: "first todo" }, { text: 'todo2', description: "second todo" }, { text: 'todo3', description: "third todo" } ] } }); const todos = await context.providers.Todos.findBy({}, ["_id", "text"]); expect(todos.length).toEqual(3); todos.forEach((todo: any) => { expect(todo._id).toBeDefined(); expect(todo.text).toBeDefined(); expect(todo.description).toBeUndefined(); // should be undefined since not selected }); const createdTodo = await context.providers.Todos.create({ text: "new todo", description: "todo add description" }); expect(createdTodo._id).toBeDefined(); const updatedTodo = await context.providers.Todos.update({ _id: createdTodo._id, text: "updated todo" }, ["text"]); expect(updatedTodo.description).toBeUndefined(); expect(updatedTodo.text).toEqual("updated todo"); const deletedTodo = await context.providers.Todos.update({ _id: createdTodo._id }, ["_id", "text", "description"]); expect(deletedTodo._id).toEqual(createdTodo._id); expect(deletedTodo.text).toEqual("updated todo"); expect(deletedTodo.description).toEqual("todo add description"); }); test('get todos with field value not in a given arrray argument', async () => { context = await createTestingContext(`""" @model """ type Todo { _id: GraphbackObjectID! items: Int } scalar GraphbackObjectID `, { seedData: { Todo: [ { items: 1, }, { items: 2, }, { items: 3 }, { items: 4 }, { items: 5 }, { items: 6 }, { items: 8 } ] } }); const { providers } = context; // verify that not in operator works const allTodos = await providers.Todo.findBy(); const newTodoItems = 2709; await providers.Todo.create({ items: newTodoItems }); const allTodosAfterCreation = await providers.Todo.findBy(); expect(allTodosAfterCreation.length).toEqual(allTodos.length + 1); // verify that a new todo was created // retrieve all todo that do not have the newTodoItems using the in operator and verify const oldTodos = await providers.Todo.findBy({ filter: { not: { items: { in: [newTodoItems] } } } }); expect(oldTodos).toEqual(allTodos); // assert that we did not retrieve the newly added todo item }); it('a && (b || c)', async () => { context = await createTestingContext(` scalar GraphbackObjectID """ @model """ type Todo { _id: GraphbackObjectID a: Int b: Int c: Int } `, { seedData: { Todo: [ { a: 1, b: 5, c: 8 }, { a: 1, b: 2, c: 10 }, { a: 1, b: 5, c: 3 }, { a: 6, b: 6, c: 3 } ] } }) const filter: QueryFilter = { a: { eq: 1 }, or: [ { c: { eq: 6 } }, { b: { eq: 5 } } ] } const items = await context.providers.Todo.findBy({ filter }); expect(items).toHaveLength(2); }); it('a && (b || c) starting at first $or', async () => { context = await createTestingContext(` scalar GraphbackObjectID """ @model """ type Todo { _id: GraphbackObjectID a: Int b: Int c: Int } `, { seedData: { Todo: [ { a: 1, b: 5, c: 8 }, { a: 1, b: 2, c: 10 }, { a: 1, b: 5, c: 3 }, { a: 6, b: 6, c: 3 } ] } }) const filter: QueryFilter = { or: [ { a: { eq: 1 }, or: [ { c: { eq: 6 } }, { b: { eq: 5 } } ] } ] } const items = await context.providers.Todo.findBy({ filter }); expect(items).toHaveLength(2); }); it('a && (c || b) from nested $or', async () => { context = await createTestingContext(` scalar GraphbackObjectID """ @model """ type Todo { _id: GraphbackObjectID a: Int b: Int c: Int } `, { seedData: { Todo: [ { a: 1, b: 1, c: 8 }, { a: 9, b: 2, c: 10 }, { a: 1, b: 5, c: 3 }, { a: 1, b: 6, c: 6 } ] } }); const filter: QueryFilter = { or: [ { a: { eq: 1 }, or: [ { c: { eq: 6 } }, { b: { eq: 5 } } ] } ] } const items = await context.providers.Todo.findBy({ filter }); expect(items).toHaveLength(2); }); it('a || a || a', async () => { context = await createTestingContext(` scalar GraphbackObjectID """ @model """ type Todo { _id: GraphbackObjectID a: Int b: Int c: Int } `, { seedData: { Todo: [ { a: 1, b: 5, c: 8 }, { a: 2, b: 2, c: 10 }, { a: 3, b: 5, c: 3 }, { a: 6, b: 6, c: 3 } ] } }); const filter: QueryFilter = { or: [ { a: { eq: 1 } }, { a: { eq: 2 } }, { a: { eq: 3 } } ] } const items = await context.providers.Todo.findBy({ filter }); expect(items).toHaveLength(3) }) it('a || (a && b)', async () => { context = await createTestingContext(` scalar GraphbackObjectID """ @model """ type Todo { _id: GraphbackObjectID a: Int b: Int c: Int } `, { seedData: { Todo: [ { a: 1, b: 5, c: 8 }, { a: 2, b: 3, c: 10 }, { a: 2, b: 3, c: 3 }, { a: 6, b: 6, c: 3 } ] } }); const filter: QueryFilter = { or: [ { a: { eq: 1 }, }, { or: [ { a: { eq: 2 }, b: { eq: 3 } } ] } ] } const items = await context.providers.Todo.findBy({ filter }); expect(items).toHaveLength(3) }) });
the_stack
export const vector2DTemplate = { annotation: { name: "TestVector2D", annotation: { description: "A sample vector 2D schema", }, }, typeid: "autodesk.appframework.tests:myVector2D-1.0.0", properties: [ { id: "x", typeid: "Float32", }, { id: "y", typeid: "Float32", }, ], }; export const vector3DTemplate = { annotation: { name: "TestVector3D", annotation: { description: "A sample vector 3D schema", }, }, typeid: "autodesk.appframework.tests:myVector3D-1.0.0", inherits: "autodesk.appframework.tests:myVector2D-1.0.0", properties: [ { id: "z", typeid: "Float32", }, ], }; export const enumUnoDosTresTemplate = { typeid: "autodesk.appframework.tests:myEnumUnoDosTres-1.0.0", inherits: "Enum", properties: [ { id: "uno", value: 1 }, { id: "dos", value: 2 }, { id: "tres", value: 3 }, ], }; export const bookDataTemplate = { annotation: { name: "TestBookList", annotation: { description: "A sample holder for book names (or whatever)", }, }, typeid: "autodesk.appframework.tests:myBookData-1.0.0", inherits: ["NamedProperty"], properties: [ { id: "book", typeid: "String", }, { id: "author", typeid: "String", }, ], }; export const collectionConstants = { typeid: "autodesk.appframework.tests:collectionConstants-1.0.0", constants: [ { id: "primitiveArray", typeid: "Int32", context: "array", value: [42, 43, 44], }, { id: "primitiveMap", typeid: "Int32", context: "map", value: { a: 42, b: 43 }, }, { id: "nonPrimitiveArray", typeid: "autodesk.appframework.tests:myVector2D-1.0.0", context: "array", value: [{ x: 42, y: 43 }, { x: 44, y: 45 }], }, { id: "nonPrimitiveMap", typeid: "autodesk.appframework.tests:myVector2D-1.0.0", context: "map", value: { a: { x: 42, y: 43 }, b: { x: 44, y: 45 }, }, }, { id: "bookSet", typeid: "autodesk.appframework.tests:myBookData-1.0.0", context: "set", value: [ { book: "The Hobbit", author: "Tolkien", }, { book: "Faust", author: "Goethe", }, ], }, ], }; export const genericTemplate = { annotation: { name: "TestComplexProperty", annotation: { description: "A sample template containing different datatypes.", }, }, typeid: "autodesk.appframework.tests:myGenericTemplate-1.0.0", properties: [ { id: "myF32Number", typeid: "Float32", value: 3, }, { id: "myVector", typeid: "autodesk.appframework.tests:myVector2D-1.0.0", value: { x: 1, y: 2 }, }, { id: "myEnumCases", properties: [ { id: "myEnum", typeid: "autodesk.appframework.tests:myEnumUnoDosTres-1.0.0", }, { id: "myEnumArray", typeid: "autodesk.appframework.tests:myEnumUnoDosTres-1.0.0", context: "array", value: [ 1, "dos", ], }, { id: "refToEnum", typeid: "Reference", value: "myEnum", }, { id: "refToEnumArrayEntry", typeid: "Reference", value: "myEnumArray[1]", }, { id: "refArrayToEnum", typeid: "Reference", context: "array", value: [ "myEnum", "refArrayToEnum[0]", "myEnumArray[0]", "refArrayToEnum[2]", "/myTestProperty.myEnumCases.refToEnum", "refArrayToEnum[4]", "/myTestProperty.myEnumCases.refToEnumArrayEntry", "refArrayToEnum[6]", ], }, { id: "refMapToEnum", typeid: "Reference", context: "map", value: { a: "myEnum", b: "refMapToEnum[a]", c: "myEnumArray[0]", d: "refMapToEnum[c]", e: "/myTestProperty.myEnumCases.refToEnum", f: "refMapToEnum[e]", g: "/myTestProperty.myEnumCases.refToEnumArrayEntry", h: "refMapToEnum[g]", }, }, ], }, { id: "myUint64Int64Cases", properties: [ { id: "myUint64", typeid: "Uint64", value: "4294967296", }, { id: "myUint64Array", typeid: "Uint64", context: "array", value: [ "4294967296", // new Uint64(0, 1) === 1<<32 "1024", // new Uint64(1024, 0) ], }, { id: "myInt64Map", typeid: "Int64", context: "map", value: { a: "4294967296", // new Int64(0, 1) === 1<<32 b: "1024", // new Int64(1024, 0) }, }, { id: "refToUint64", typeid: "Reference", value: "myUint64", }, { id: "refToUint64ArrayEntry", typeid: "Reference", value: "myUint64Array[0]", }, { id: "refToInt64MapEntry", typeid: "Reference", value: "myInt64Map[a]", }, { id: "refArrayToUint64Int64", typeid: "Reference", context: "array", value: [ "myUint64", "refArrayToUint64Int64[0]", "myUint64Array[0]", "refArrayToUint64Int64[2]", "myInt64Map[a]", "refArrayToUint64Int64[4]", "/myTestProperty.myUint64Int64Cases.refToUint64", "refArrayToUint64Int64[6]", "/myTestProperty.myUint64Int64Cases.refToUint64ArrayEntry", "refArrayToUint64Int64[8]", "/myTestProperty.myUint64Int64Cases.refToInt64MapEntry", "refArrayToUint64Int64[10]", ], }, { id: "refMapToUint64Int64", typeid: "Reference", context: "map", value: { a: "myUint64", b: "refMapToUint64Int64[a]", c: "myUint64Array[0]", d: "refMapToUint64Int64[c]", e: "myInt64Map[a]", f: "refMapToUint64Int64[e]", g: "/myTestProperty.myUint64Int64Cases.refToUint64", h: "refMapToUint64Int64[g]", i: "/myTestProperty.myUint64Int64Cases.refToUint64ArrayEntry", j: "refMapToUint64Int64[i]", k: "/myTestProperty.myUint64Int64Cases.refToInt64MapEntry", l: "refMapToUint64Int64[k]", }, }, ], }, { id: "myReference", typeid: "Reference", context: "single", value: "myVector", }, { id: "myMultiHopReference", typeid: "Reference", context: "single", value: "myReference", }, { id: "myI32Array", typeid: "Int32", context: "array", value: [ 0, 10, 20, 30, 40, ], }, { id: "myDynamicProperty", typeid: "NodeProperty", }, { id: "myComplexArray", typeid: "autodesk.appframework.tests:myVector2D-1.0.0", context: "array", value: [ { x: 1, y: 2, }, { x: 10, y: 20, }, ], }, { id: "myReferenceArray", typeid: "Reference", context: "array", value: [ "myF32Number", "../myTestProperty.myF32Number", "/myTestProperty.myF32Number", "myVector", "../myTestProperty.myVector", "/myTestProperty.myVector", "myI32Array[0]", "../myTestProperty.myI32Array[0]", "/myTestProperty.myI32Array[0]", "myComplexArray[0]", "/myTestProperty.myComplexArray[0]", "../myTestProperty.myComplexArray[0]", "myMap[firstNumber]", "../myTestProperty.myMap[firstNumber]", "/myTestProperty.myMap[firstNumber]", "myComplexMap[firstEntry]", "../myTestProperty.myComplexMap[firstEntry]", "/myTestProperty.myComplexMap[firstEntry]", "myReferenceArray[0]", "myReferenceArray[1]", "myReferenceArray[2]", "myReferenceArray[3]", "myReferenceArray[4]", "myReferenceArray[5]", "myReferenceArray[6]", "myReferenceArray[7]", "myReferenceArray[8]", "myReferenceArray[9]", "myReferenceArray[10]", "myReferenceArray[11]", "myReferenceArray[12]", "myReferenceArray[13]", "myReferenceArray[14]", "myReferenceArray[15]", "myReferenceArray[16]", "myReferenceArray[17]", ], }, { id: "myMap", typeid: "Int32", context: "map", value: { firstNumber: 1111, secondNumber: 2222, thirdNumber: 3333, }, }, { id: "myComplexMap", typeid: "autodesk.appframework.tests:myVector2D-1.0.0", context: "map", value: { firstEntry: { x: 10, y: 20, }, secondEntry: { x: 30, y: 40, }, thirdEntry: { x: 50, y: 60, }, }, }, { id: "myReferenceMap", typeid: "Reference", context: "map", value: { a: "myF32Number", b: "../myTestProperty.myF32Number", c: "/myTestProperty.myF32Number", d: "myVector", e: "../myTestProperty.myVector", f: "/myTestProperty.myVector", g: "myI32Array[0]", h: "../myTestProperty.myI32Array[0]", i: "/myTestProperty.myI32Array[0]", j: "myComplexArray[0]", k: "/myTestProperty.myComplexArray[0]", l: "../myTestProperty.myComplexArray[0]", m: "myMap[firstNumber]", n: "../myTestProperty.myMap[firstNumber]", o: "/myTestProperty.myMap[firstNumber]", p: "myComplexMap[firstEntry]", q: "../myTestProperty.myComplexMap[firstEntry]", r: "/myTestProperty.myComplexMap[firstEntry]", aa: "myReferenceMap[a]", bb: "myReferenceMap[b]", cc: "myReferenceMap[c]", dd: "myReferenceMap[d]", ee: "myReferenceMap[e]", ff: "myReferenceMap[f]", gg: "myReferenceMap[g]", hh: "myReferenceMap[h]", ii: "myReferenceMap[i]", jj: "myReferenceMap[j]", kk: "myReferenceMap[k]", ll: "myReferenceMap[l]", mm: "myReferenceMap[m]", nn: "myReferenceMap[n]", oo: "myReferenceMap[o]", pp: "myReferenceMap[p]", qq: "myReferenceMap[q]", rr: "myReferenceMap[r]", }, }, { id: "myBookSet", typeid: "autodesk.appframework.tests:myBookData-1.0.0", context: "set", value: [ { book: "Principia Mathematica", author: "Newton", }, { book: "Chamber of Secrets", author: "Rowling", }, { book: "Brief History of Time", author: "Hawking", }, ], }, ], };
the_stack
import { resolve } from 'path'; import { HostTree } from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as AddNsOptions } from './schema'; import { getFileContent } from '@schematics/angular/utility/test'; import * as stripJsonComments from 'strip-json-comments'; describe('Add {N} schematic', () => { const schematicRunner = new SchematicTestRunner( '@nativescript/schematics', resolve(__dirname, '../collection.json'), ); const project = 'foo'; const defaultOptions: AddNsOptions = { project, nsExtension: 'tns', webExtension: '', sample: false, skipAutoGeneratedComponent: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = new UnitTestTree(new HostTree()); appTree = await setupProject(appTree, schematicRunner, project); }); describe('when using the default options', () => { beforeEach(async () => { appTree = await schematicRunner.runSchematicAsync('add-ns', defaultOptions, appTree) .toPromise(); }); it('should add dependency to NativeScript schematics', () => { const configFile = '/angular.json'; expect(appTree.files).toContain(configFile); const configFileContent = JSON.parse(stripJsonComments(getFileContent(appTree, configFile))); expect(configFileContent.cli.defaultCollection).toBe('@nativescript/schematics'); }); it('should add {N} specific files', () => { const files = appTree.files; expect(files).toContain('/nativescript.config.ts'); expect(files).toContain('/tsconfig.tns.json'); expect(files).toContain('/src/app.css'); expect(files).toContain('/src/main.tns.ts'); expect(files).toContain('/src/package.json'); expect(files).toContain('/src/app/app.module.tns.ts'); expect(files).toContain('/src/app/app.component.tns.ts'); expect(files).toContain('/src/app/app.component.tns.html'); }); it('should add native app resources', () => { expect(appTree.files).toContain('/App_Resources/Android/app.gradle'); expect(appTree.files).toContain('/App_Resources/iOS/Info.plist'); }); it('should add {N} specifics to gitignore', () => { const gitignorePath = '/.gitignore'; expect(appTree.files).toContain(gitignorePath); const gitignore = getFileContent(appTree, gitignorePath); expect(gitignore.includes('node_modules/')).toBeTruthy(); expect(gitignore.includes('platforms/')).toBeTruthy(); expect(gitignore.includes('hooks/')).toBeTruthy(); expect(gitignore.includes('src/**/*.js')).toBeTruthy(); }); it('should add all required dependencies to the package.json', () => { const packageJsonPath = '/package.json'; expect(appTree.files).toContain(packageJsonPath); const packageJson = JSON.parse(stripJsonComments(getFileContent(appTree, packageJsonPath))); const { dependencies, devDependencies } = packageJson; expect(dependencies).toBeDefined(); expect(dependencies['@nativescript/angular']).toBeDefined(); expect(dependencies['@nativescript/theme']).toBeDefined(); expect(dependencies['@nativescript/core']).toBeDefined(); expect(dependencies['reflect-metadata']).toBeDefined(); expect(devDependencies['@nativescript/webpack']).toBeDefined(); expect(devDependencies['@nativescript/tslint-rules']).toBeDefined(); }); it('should add run scripts to the package json', () => { const packageJsonPath = '/package.json'; expect(appTree.files).toContain(packageJsonPath); const packageJson = JSON.parse(stripJsonComments(getFileContent(appTree, packageJsonPath))); const { scripts } = packageJson; expect(scripts).toBeDefined(); expect(scripts.android).toEqual('ns run android --no-hmr'); expect(scripts.ios).toEqual('ns run ios --no-hmr'); // expect(scripts.ngcc).toEqual('ngcc --properties es2015 module main --first-only'); // expect(scripts.postinstall).toEqual('npm run ngcc'); }); // it('should add NativeScript key to the package json', () => { // const packageJsonPath = '/package.json'; // expect(appTree.files).toContain(packageJsonPath); // const packageJson = JSON.parse(stripJsonComments(getFileContent(appTree, packageJsonPath))); // const { nativescript } = packageJson; // expect(nativescript).toBeDefined(); // expect(nativescript.id).toEqual('org.nativescript.ngsample'); // }); it('should modify the tsconfig.app.json (web) to include files and path mappings', () => { const webTsConfigPath = '/tsconfig.app.json'; expect(appTree.files).toContain(webTsConfigPath); const webTsconfig = JSON.parse(stripJsonComments(getFileContent(appTree, webTsConfigPath))); const files = webTsconfig.files; expect(files).toBeDefined(); expect(files.includes('src/main.ts')).toBeTruthy(); expect(files.includes('src/polyfills.ts')).toBeTruthy(); const paths = webTsconfig.compilerOptions.paths; expect(paths).toBeDefined(); expect(paths['@src/*']).toBeDefined(); const maps = paths['@src/*']; expect(maps).toContain('src/*.web'); expect(maps).toContain('src/*'); }); it('should create the tsconfig.tns.json with files and path mappings', () => { const nsTsConfigPath = '/tsconfig.tns.json'; expect(appTree.files).toContain(nsTsConfigPath); const nsTsConfig = JSON.parse(stripJsonComments(getFileContent(appTree, nsTsConfigPath))); const files = nsTsConfig.files; expect(files).toBeDefined(); expect(files).toContain('src/main.tns.ts'); const paths = nsTsConfig.compilerOptions.paths; expect(paths).toBeDefined(); expect(paths['@src/*']).toBeDefined(); const maps = paths['@src/*']; expect(maps).toContain('src/*.tns.ts'); expect(maps).toContain('src/*.ts'); }); it('should create the tsconfig.spec.json (web) with files', () => { const specTsConfigPath = '/tsconfig.spec.json'; expect(appTree.files).toContain(specTsConfigPath); const specTsConfig = JSON.parse(stripJsonComments(getFileContent(appTree, specTsConfigPath))); const files = specTsConfig.files; expect(files).toBeDefined(); expect(files.includes('src/test.ts')).toBeTruthy(); expect(files.includes('src/polyfills.ts')).toBeTruthy(); }); it('should modify the base tsconfig.json to include path mappings', () => { const baseTsConfigPath = '/tsconfig.base.json'; expect(appTree.files).toContain(baseTsConfigPath); const baseTsConfig = JSON.parse(stripJsonComments(getFileContent(appTree, baseTsConfigPath))); const paths = baseTsConfig.compilerOptions.paths; expect(paths).toBeDefined(); expect(paths['@src/*']).toBeDefined(); const maps = paths['@src/*']; expect(maps).toContain('src/*.android.ts'); expect(maps).toContain('src/*.ios.ts'); expect(maps).toContain('src/*.tns.ts'); expect(maps).toContain('src/*.web.ts'); expect(maps).toContain('src/*'); }); it('should modify tslint.json to include rule for using remapped imports', () => { const tsLintConfigPath = '/tslint.json'; expect(appTree.files).toContain(tsLintConfigPath); const tsLintConfig = JSON.parse(stripJsonComments(getFileContent(appTree, tsLintConfigPath))); const { extends: tsLintExtends, rules: tsLintRules } = tsLintConfig; expect(tsLintExtends).toEqual(jasmine.any(Array)); expect(tsLintExtends).toContain('@nativescript/tslint-rules'); expect(tsLintRules).toEqual(jasmine.any(Object)); expect(Object.keys(tsLintRules)).toContain('prefer-mapped-imports'); const rule = tsLintRules['prefer-mapped-imports']; const ruleOptions = rule[1]; const actualBaseUrl = ruleOptions['base-url']; expect(actualBaseUrl).toEqual('./'); }); it('should generate a sample shared component', () => { const { files } = appTree; const appRoutingModuleContent = appTree.readContent('/src/app/app-routing.module.tns.ts'); const appComponentTemplate = appTree.readContent('/src/app/app.component.tns.html'); expect(files).toContain('/src/app/auto-generated/auto-generated.component.ts'); expect(files).toContain('/src/app/auto-generated/auto-generated.component.html'); expect(files).toContain('/src/app/auto-generated/auto-generated.component.tns.html'); expect(appRoutingModuleContent).toMatch( /import { AutoGeneratedComponent } from '@src\/app\/auto-generated\/auto-generated.component'/, ); expect(appRoutingModuleContent).toMatch( /{\s+path: 'auto-generated',\s+component: AutoGeneratedComponent,\s+},/g, ); expect(appComponentTemplate).not.toContain( '<Label text="Entry Component works" textWrap="true"></Label>', ); }); }); describe('when the skipAutoGeneratedComponent flag is raised', () => { beforeEach(async () => { const options = { ...defaultOptions, skipAutoGeneratedComponent: true, }; appTree = await schematicRunner.runSchematicAsync('add-ns', options, appTree).toPromise(); }); it('should not add a sample shared component', () => { const { files } = appTree; const appRoutingModuleContent = appTree.readContent('/src/app/app-routing.module.tns.ts'); const appComponentTemplate = appTree.readContent('/src/app/app.component.tns.html'); expect(files).not.toContain('/src/app/auto-generated/auto-generated.component.css'); expect(files).not.toContain('/src/app/auto-generated/auto-generated.component.html'); expect(files).not.toContain('/src/app/auto-generated/auto-generated.component.ts'); expect(appRoutingModuleContent).not.toMatch( /import { AutoGeneratedComponent } from '.\/auto-generated\/auto-generated.component'/, ); expect(appRoutingModuleContent).toContain( 'export const routes: Routes = []', ); expect(appComponentTemplate).toContain( `This is just a fun sample for you to play with`, ); }); }); describe('when the sample flag is raised', () => { beforeEach(async () => { const options = { ...defaultOptions, sample: true, }; appTree = await schematicRunner.runSchematicAsync('add-ns', options, appTree).toPromise(); }); it('should generate sample files', () => { const { files } = appTree; expect(files).toContain('/src/app/barcelona/barcelona.common.ts'); expect(files).toContain('/src/app/barcelona/barcelona.module.ts'); expect(files).toContain('/src/app/barcelona/barcelona.module.tns.ts'); expect(files).toContain('/src/app/barcelona/player.service.ts'); expect(files).toContain('/src/app/barcelona/player.model.ts'); expect(files).toContain('/src/app/barcelona/players/players.component.ts'); expect(files).toContain('/src/app/barcelona/players/players.component.html'); expect(files).toContain('/src/app/barcelona/players/players.component.tns.html'); expect(files).toContain('/src/app/barcelona/player-detail/player-detail.component.ts'); expect(files).toContain('/src/app/barcelona/player-detail/player-detail.component.html'); expect(files).toContain('/src/app/barcelona/player-detail/player-detail.component.tns.html'); }); it('should configure routing for redirection', () => { const appRoutingModuleContent = appTree.readContent('/src/app/app-routing.module.tns.ts'); expect(appRoutingModuleContent).toMatch( /{\s+path: '',\s+redirectTo: '\/players',\s+pathMatch: 'full',\s+},/g, ); }); }); }); async function setupProject( tree: UnitTestTree, schematicRunner: SchematicTestRunner, name: string, ) { tree = await schematicRunner.runExternalSchematicAsync( '@schematics/angular', 'workspace', { name: 'workspace', version: '10.1.0', newProjectRoot: '', }, ).toPromise(); tree = await schematicRunner.runExternalSchematicAsync( '@schematics/angular', 'application', { name, projectRoot: '', }, tree, ).toPromise(); return tree; }
the_stack
import * as functions from "firebase-functions"; import * as admin from "firebase-admin"; import * as utils from "../lib/utils"; import { order_status, possible_transitions, order_status_keys, timeEventMapping } from "../common/constant"; import { createCustomer } from "../stripe/customer"; import moment from "moment-timezone"; import { sendMessageToCustomer, notifyNewOrderToRestaurant } from "./notify"; import { Context } from "../models/TestType"; export const updateOrderTotalDataAndUserLog = async (db, transaction, customerUid, order, restaurantId, ownerUid, timePlaced, positive) => { const timezone = (functions.config() && functions.config().order && functions.config().order.timezone) || "Asia/Tokyo"; const menuIds = Object.keys(order); const date = moment(timePlaced.toDate()).tz(timezone).format("YYYYMMDD"); // Firestore transactions require all reads to be executed before all writes. // Read !! const totalRef: { [key: string]: any } = {}; const totals: { [key: string]: any } = {}; const nums: { [key: string]: number } = {}; await Promise.all( menuIds.map(async (menuId) => { const numArray = Array.isArray(order[menuId]) ? order[menuId] : [order[menuId]]; nums[menuId] = numArray.reduce((sum, current) => { return sum + current; }, 0); const path = `restaurants/${restaurantId}/menus/${menuId}/orderTotal/${date}`; totalRef[menuId] = db.doc(path); totals[menuId] = (await transaction.get(totalRef[menuId])).data(); }) ); const userLogPath = `restaurants/${restaurantId}/userLog/${customerUid}`; const userLogRef = db.doc(userLogPath); const userLog = (await transaction.get(userLogRef)).data(); // Write!! await Promise.all( menuIds.map(async (menuId) => { const num = nums[menuId]; const total = totals[menuId]; if (!total) { const addData = { uid: ownerUid, restaurantId, menuId, date, count: num, }; await transaction.set(totalRef[menuId], addData); } else { const count = positive ? total.count + num : total.count - num; const updateData = { count, }; await transaction.update(totalRef[menuId], updateData); } }) ); if (!userLog) { const data = { uid: customerUid, counter: positive ? 1 : 0, cancelCounter: positive ? 0 : 1, currentOrder: timePlaced, // lastOrder: timePlaced, restaurantId, ownerUid, }; await transaction.set(userLogRef, data); } else { const counter = userLog.counter + (positive ? 1 : 0); const cancelCounter = userLog.cancelCounter + (positive ? 0 : 1); const updateData = { counter, cancelCounter, currentOrder: timePlaced, lastOrder: userLog.currentOrder || timePlaced, }; await transaction.update(userLogRef, updateData); } }; // This function is called by users to place orders without paying // export const place = async (db: admin.firestore.Firestore, data: any, context: functions.https.CallableContext) => { export const place = async (db, data: any, context: functions.https.CallableContext | Context) => { const customerUid = utils.validate_auth(context); const { restaurantId, orderId, tip, sendSMS, timeToPickup, lng, memo } = data; const _tip = Number(tip) || 0; utils.validate_params({ restaurantId, orderId }); // tip, sendSMS and lng are optinoal const timePlaced = (timeToPickup && new admin.firestore.Timestamp(timeToPickup.seconds, timeToPickup.nanoseconds)) || admin.firestore.FieldValue.serverTimestamp(); try { const restaurantData = await utils.get_restaurant(db, restaurantId); const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`); const result = await db.runTransaction(async (transaction) => { const order = (await transaction.get(orderRef)).data(); if (!order) { throw new functions.https.HttpsError("invalid-argument", "This order does not exist."); } order.id = orderId; if (customerUid !== order.uid) { throw new functions.https.HttpsError("permission-denied", "The user is not the owner of this order."); } if (order.status !== order_status.validation_ok) { throw new functions.https.HttpsError("failed-precondition", "The order has been already placed or canceled"); } const multiple = utils.getStripeRegion().multiple; // 100 for USD, 1 for JPY const roundedTip = Math.round(_tip * multiple) / multiple; // transaction for stock orderTotal await updateOrderTotalDataAndUserLog(db, transaction, customerUid, order.order, restaurantId, restaurantData.uid, timePlaced, true); // customerUid transaction.update(orderRef, { status: order_status.order_placed, totalCharge: order.total + _tip, tip: roundedTip, sendSMS: sendSMS || false, updatedAt: admin.firestore.Timestamp.now(), orderPlacedAt: admin.firestore.Timestamp.now(), timePlaced, memo: memo || "", }); Object.assign(order, { totalCharge: order.total + _tip, tip }); return { success: true, order }; }); await notifyNewOrderToRestaurant(db, restaurantId, result.order, restaurantData.restaurantName, lng); return result; } catch (error) { throw utils.process_error(error); } }; // This function is called by admins (restaurant operators) to update the status of order export const update = async (db: admin.firestore.Firestore, data: any, context: functions.https.CallableContext) => { const ownerUid = utils.validate_admin_auth(context); const { restaurantId, orderId, status, lng, timezone, timeEstimated } = data; utils.validate_params({ restaurantId, orderId, status, timezone }); // lng, timeEstimated is optional try { const restaurantDoc = await db.doc(`restaurants/${restaurantId}`).get(); const restaurant = restaurantDoc.data() || {}; if (restaurant.uid !== ownerUid) { throw new functions.https.HttpsError("permission-denied", "The user does not have an authority to perform this operation."); } const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`); let msgKey: string | undefined = undefined; const result = await db.runTransaction(async (transaction) => { const order = (await transaction.get(orderRef)).data(); if (!order) { throw new functions.https.HttpsError("invalid-argument", "This order does not exist."); } order.id = orderId; const possible_transition = possible_transitions[order.status]; if (!possible_transition[status]) { throw new functions.https.HttpsError("failed-precondition", "It is not possible to change state from the current state.", order.status); } if (status === order_status.order_canceled && order.payment && order.payment.stripe) { throw new functions.https.HttpsError("permission-denied", "Paid order can not be cancele like this", status); } if ( (order.status === order_status.ready_to_pickup || order.status === order_status.order_accepted) && order.payment && order.payment.stripe && order.payment && order.payment.stripe === "pending" ) { throw new functions.https.HttpsError("permission-denied", "Paid order can not be change like this", status); } if (status === order_status.order_accepted) { msgKey = "msg_order_accepted"; } if (status === order_status.ready_to_pickup) { if (order && order.timeEstimated) { const diffDay = (moment().toDate().getTime() - order.timeEstimated.toDate().getTime()) / 1000 / 3600 / 24; console.log("timeEstimated_diff_days = " + String(diffDay)); if (diffDay < 1) { msgKey = "msg_cooking_completed"; } } } // everything are ok const updateTimeKey = timeEventMapping[order_status_keys[status]]; const updateData: any = { status, updatedAt: admin.firestore.Timestamp.now(), [updateTimeKey]: admin.firestore.Timestamp.now(), }; if (status === order_status.order_accepted) { updateData.timeEstimated = timeEstimated ? new admin.firestore.Timestamp(timeEstimated.seconds, timeEstimated.nanoseconds) : order.timePlaced; order.timeEstimated = updateData.timeEstimated; } await transaction.update(orderRef, updateData); return { success: true, order }; }); const orderData = result.order; if (orderData.sendSMS && msgKey) { const params = {}; if (status === order_status.order_accepted) { params["time"] = moment(orderData.timeEstimated.toDate()).tz(timezone).locale("ja").format("LLL"); console.log("timeEstimated", params["time"]); } await sendMessageToCustomer(db, lng, msgKey, restaurant.restaurantName, orderData, restaurantId, orderId, params); } return result; } catch (error) { throw utils.process_error(error); } }; // for wasOrderCreated const getOptionPrice = (selectedOptionsRaw, menu, multiple) => { return selectedOptionsRaw.reduce((tmpPrice, selectedOpt, key) => { const opt = menu.itemOptionCheckbox[key].split(","); if (opt.length === 1) { if (selectedOpt) { return tmpPrice + Math.round(utils.optionPrice(opt[0]) * multiple) / multiple; } } else { return tmpPrice + Math.round(utils.optionPrice(opt[selectedOpt]) * multiple) / multiple; } return tmpPrice; }, 0); }; export const createNewOrderData = async (restaurantRef, orderRef, orderData, multiple) => { const menuIds = Object.keys(orderData.order); const menuObj = await utils.getMenuObj(restaurantRef, menuIds); // ret const newOrderData = {}; const newItems = {}; const newPrices = {}; let food_sub_total = 0; let alcohol_sub_total = 0; // end of ret if ( menuIds.some((menuId) => { return menuObj[menuId] === undefined; }) ) { return orderRef.update("status", order_status.error); } menuIds.map((menuId) => { const menu = menuObj[menuId]; const prices: number[] = []; const newOrder: number[] = []; const numArray = Array.isArray(orderData.order[menuId]) ? orderData.order[menuId] : [orderData.order[menuId]]; numArray.map((num, orderKey) => { if (!Number.isInteger(num)) { throw new Error("invalid number: not integer"); } if (num < 0) { throw new Error("invalid number: negative number"); } if (num === 0) { return; } const price = menu.price + getOptionPrice(orderData.rawOptions[menuId][orderKey], menu, multiple); newOrder.push(num); prices.push(price * num); }); newPrices[menuId] = prices; newOrderData[menuId] = newOrder; const total = prices.reduce((sum, price) => sum + price, 0); if (menu.tax === "alcohol") { alcohol_sub_total += total; } else { food_sub_total += total; } const menuItem: any = { price: menu.price, itemName: menu.itemName, itemPhoto: menu.itemPhoto, images: menu.images, itemAliasesName: menu.itemAliasesName, category1: menu.category1, category2: menu.category2, tax: menu.tax, }; newItems[menuId] = utils.filterData(menuItem); }); return { newOrderData, newItems, newPrices, food_sub_total, alcohol_sub_total, }; }; export const orderAccounting = (restaurantData, food_sub_total, alcohol_sub_total, multiple) => { // tax rate const inclusiveTax = restaurantData.inclusiveTax || false; const alcoholTax = restaurantData.alcoholTax || 0; const foodTax = restaurantData.foodTax || 0; // calculate price. const sub_total = food_sub_total + alcohol_sub_total; if (sub_total === 0) { throw new Error("invalid order: total 0 "); } if (inclusiveTax) { const food_tax = Math.round(food_sub_total * (1 - 1 / (1 + foodTax / 100)) * multiple) / multiple; const alcohol_tax = Math.round(alcohol_sub_total * (1 - 1 / (1 + alcoholTax / 100)) * multiple) / multiple; const tax = food_tax + alcohol_tax; return { tax, inclusiveTax, sub_total, total: sub_total, food_sub_total: food_sub_total - food_tax, food_tax, alcohol_sub_total: alcohol_sub_total - alcohol_tax, alcohol_tax, }; } else { const food_tax = Math.round(((food_sub_total * foodTax) / 100) * multiple) / multiple; const alcohol_tax = Math.round(((alcohol_sub_total * alcoholTax) / 100) * multiple) / multiple; const tax = food_tax + alcohol_tax; const total = sub_total + tax; return { tax, inclusiveTax, sub_total, total, food_sub_total, food_tax, alcohol_sub_total, alcohol_tax, }; } }; // export const wasOrderCreated = async (db, snapshot, context) => { export const wasOrderCreated = async (db, data: any, context) => { const customerUid = utils.validate_auth(context); const { restaurantId, orderId } = data; utils.validate_params({ restaurantId, orderId }); const restaurantRef = db.doc(`restaurants/${restaurantId}`); const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`); try { const restaurantDoc = await restaurantRef.get(); if (!restaurantDoc.exists) { return orderRef.update("status", order_status.error); } const restaurantData = restaurantDoc.data(); if (restaurantData.deletedFlag || !restaurantData.publicFlag) { return orderRef.update("status", order_status.error); } const order = await orderRef.get(); if (!order) { throw new functions.https.HttpsError("invalid-argument", "This order does not exist."); } const orderData = order.data(); if (!orderData || !orderData.status || orderData.status !== order_status.new_order || !orderData.uid || orderData.uid !== customerUid) { console.log("invalid order:" + String(orderId)); throw new functions.https.HttpsError("invalid-argument", "This order does not exist."); } const multiple = utils.getStripeRegion().multiple; //100 for USD, 1 for JPY const { newOrderData, newItems, newPrices, food_sub_total, alcohol_sub_total } = await createNewOrderData(restaurantRef, orderRef, orderData, multiple); // Atomically increment the orderCount of the restaurant let orderCount = 0; await db.runTransaction(async (tr) => { // We need to read restaurantData again for this transaction const trRestaurantData = (await tr.get(restaurantRef)).data(); if (trRestaurantData) { orderCount = trRestaurantData.orderCount || 0; await tr.update(restaurantRef, { orderCount: (orderCount + 1) % 1000000, }); } }); const accountingResult = orderAccounting(restaurantData, food_sub_total, alcohol_sub_total, multiple); await createCustomer(db, customerUid, context.auth.token.phone_number); return orderRef.update({ order: newOrderData, menuItems: newItems, // Clone of ordered menu items (simplified) prices: newPrices, status: order_status.validation_ok, number: orderCount, sub_total: accountingResult.sub_total, tax: accountingResult.tax, inclusiveTax: accountingResult.inclusiveTax, total: accountingResult.total, accounting: { food: { revenue: accountingResult.food_sub_total, tax: accountingResult.food_tax, }, alcohol: { revenue: accountingResult.alcohol_sub_total, tax: accountingResult.alcohol_tax, }, }, }); } catch (e) { console.log(e); return orderRef.update("status", order_status.error); } };
the_stack
import BaseClient from "./BaseClient"; import { Callback, ClientOptions, DefaultResponse, FilteringParameters, } from "./models"; import { CreateDomainRequest, CreateServerRequest, CreateSignatureRequest, DomainDetails, Domains, Server, ServerFilteringParameters, Servers, SignatureDetails, Signatures, TemplatesPush, TemplatesPushRequest, UpdateDomainRequest, UpdateServerRequest, UpdateSignatureRequest, } from "./models"; export default class AccountClient extends BaseClient { /** * Create a new AccountClient * @param accountToken The account token that should be used with requests. * @param configOptions Various options to customize client behavior. */ constructor(accountToken: string, configOptions?: ClientOptions.Configuration) { super(accountToken, ClientOptions.DefaultHeaderNames.ACCOUNT_TOKEN, configOptions); } /** * Retrieve a list of Servers. * * @param filter - An optional filter for which data is retrieved. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getServers(filter: ServerFilteringParameters = new ServerFilteringParameters(), callback?: Callback<Servers>): Promise<Servers> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/servers", filter, callback); } /** * Retrieve a single server by ID. * * @param id - The ID of the Server for which you wish to retrieve details. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getServer(id: number, callback?: Callback<Server>): Promise<Server> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/servers/${id}`, {}, callback); } /** * Create a new Server. * * @param options - The options to be used to create new Server. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createServer(options: CreateServerRequest, callback?: Callback<Server>): Promise<Server> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/servers", options, callback); } /** * Modify the Server associated with this Client. * * @param id - The ID of the Server you wish to update. * @param options - The options to be used to create new Server. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public editServer(id: number, options: UpdateServerRequest, callback?: Callback<Server>): Promise<Server> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, `/servers/${id}`, options, callback); } /** * Modify the Server associated with this Client. * * @param id - The ID of the Domain you wish to delete. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public deleteServer(id: number, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.DELETE, `/servers/${id}`, {}, callback); } /** * Retrieve a batch of Domains. * * @param filter - An optional filter for which data is retrieved. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getDomains(filter: FilteringParameters = new FilteringParameters(), callback?: Callback<Domains>): Promise<Domains> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/domains", filter, callback); } /** * Retrieve a single Domain by ID. * * @param id - The ID of the Domain for which you wish to retrieve details. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getDomain(id: number, callback?: Callback<DomainDetails>): Promise<DomainDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/domains/${id}`, {}, callback); } /** * Create a new Domain. * * @param options - The options to be used to create new Domain. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createDomain(options: CreateDomainRequest, callback?: Callback<DomainDetails>): Promise<DomainDetails> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/domains/", options, callback); } /** * Update a Domain. * * @param id - The ID of the Domain you wish to update. * @param domain - The values on the Domain you wish to update. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public editDomain(id: number, options: UpdateDomainRequest, callback?: Callback<DomainDetails>): Promise<DomainDetails> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, `/domains/${id}`, options, callback); } /** * Delete a Domain. * * @param id - The ID of the Domain you wish to delete. * @param options - The options to be used in create Domain. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public deleteDomain(id: number, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.DELETE, `/domains/${id}`, {}, callback); } /** * Trigger Domain DKIM key verification. * * @param id - The ID of the Domain you wish to trigger DKIM verification for. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public verifyDomainDKIM(id: number, callback?: Callback<DomainDetails>): Promise<DomainDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.PUT, `/domains/${id}/verifyDKIM`, {}, callback); } /** * Trigger Domain DKIM key verification. * * @param id - The ID of the Domain you wish to trigger DKIM verification for. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public verifyDomainReturnPath(id: number, callback?: Callback<DomainDetails>): Promise<DomainDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.PUT, `/domains/${id}/verifyReturnPath`, {}, callback); } /** * Trigger Domain DKIM key verification. * * @param id - The ID of the Domain you wish to trigger DKIM verification for. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public verifyDomainSPF(id: number, callback?: Callback<DomainDetails>): Promise<DomainDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.PUT, `/domains/${id}/verifySPF`, {}, callback); } /** * Trigger Domain DKIM key verification. * * @param id - The ID of the Domain you wish to trigger DKIM verification for. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public rotateDomainDKIM(id: number, callback?: Callback<DomainDetails>): Promise<DomainDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.PUT, `/domains/${id}/rotateDKIM`, {}, callback); } /** * Retrieve a single Sender Signature by ID. * * @param id - The ID of the Sender Signature for which you wish to retrieve details. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getSenderSignature(id: number, callback?: Callback<SignatureDetails>): Promise<SignatureDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/senders/${id}`, {}, callback); } /** * Retrieve a batch of Sender Signatures. * * @param filter - An optional filter for which data is retrieved. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getSenderSignatures(filter: FilteringParameters = new FilteringParameters(), callback?: Callback<Signatures>): Promise<Signatures> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/senders", filter, callback); } /** * Create a new Sender Signature. * * @param options - The options to be used to create new Sender Signature. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createSenderSignature(options: CreateSignatureRequest, callback?: Callback<SignatureDetails>): Promise<SignatureDetails> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/senders/", options, callback); } /** * Update a Sender Signature. * * @param id - The ID of the Sender Signature for which you wish to update. * @param options - The values on the Sender Signature you wish to update. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public editSenderSignature(id: number, options: UpdateSignatureRequest, callback?: Callback<SignatureDetails>): Promise<SignatureDetails> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, `/senders/${id}`, options, callback); } /** * Delete a Domain. * * @param id - The ID of the Domain you wish to delete. * @param options - The options to be used in create Domain. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public deleteSenderSignature(id: number, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.DELETE, `/senders/${id}`, {}, callback); } /** * Request a new confirmation email to be sent to the email address associated with a Sender Signature. * * @param id - The ID of the Sender Signature. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public resendSenderSignatureConfirmation(id: number, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.POST, `/senders/${id}/resend`, {}, callback); } /** * Request that the SPF records for Sender Signature be verified. * * @param id - The ID of the Sender Signature. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public verifySenderSignatureSPF(id: number, callback?: Callback<SignatureDetails>): Promise<SignatureDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.POST, `/senders/${id}/verifySpf`, {}, callback); } /** * Request that the SPF records for Sender Signature be verified. * * @param id - The ID of the Sender Signature. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public requestNewDKIMForSenderSignature(id: number, callback?: Callback<SignatureDetails>): Promise<SignatureDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.POST, `/senders/${id}/requestNewDkim`, {}, callback); } /** * Request a push of templates from one server to another. * * @param options - details for pushing templates from one place to another. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public pushTemplates(options: TemplatesPushRequest, callback?: Callback<TemplatesPush>): Promise<TemplatesPush> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, "/templates/push", options, callback); } }
the_stack
import {expect} from 'chai' import {queryToTable, queryToFromFluxResult} from '../../src' // @influxdata/influxdb-client uses node transport in tests (tests run in node), therefore nock is used to mock HTTP import nock from 'nock' import {Readable} from 'stream' import {InfluxDB} from '@influxdata/influxdb-client' import {newTable} from './newTable' const url = 'http://test' const queryApi = new InfluxDB({url}).getQueryApi('whatever') describe('queryToTable', () => { beforeEach(() => { nock.disableNetConnect() }) afterEach(() => { nock.cleanAll() nock.enableNetConnect() }) it('can parse a Flux CSV with mismatched schemas', async () => { const CSV = `#group,false,false,true,true,false,true,true,true,true,true #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,double,string,string,string,string #default,_result,,,,,,,,, ,result,table,_start,_stop,_time,_value,_field,_measurement,cpu,host ,,0,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:33Z,10,usage_guest,cpu,cpu-total,oox4k.local ,,1,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:43Z,20,usage_guest,cpu,cpu-total,oox4k.local #group,false,false,true,true,false,true,true,true,true,true #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,string,string,string,string,string #default,_result,,,,,,,,, ,result,table,_start,_stop,_time,_value,_field,_measurement,cpu,host ,,2,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:33Z,thirty,usage_guest,cpu,cpu0,oox4k.local #group,false,false,true,true,false,true,true,true,true,true #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,string,string,string,string,string #default,_result,,,,,,,,, ,result,table,_start,_stop,_time,_value,_field,_measurement,cpu,host ,,3,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:43Z,fourty,usage_guest,cpu,cpu0,oox4k.local` nock(url) .post(/.*/) .reply(200, CSV) const table = await queryToTable(queryApi, 'ignored', newTable) expect(table.getColumn('result', 'string')).deep.equals([ '_result', '_result', '_result', '_result', ]) expect(table.getColumn('_start', 'time')).deep.equals([ 1549064312524, 1549064312524, 1549064312524, 1549064312524, ]) expect(table.getColumn('_stop', 'time')).deep.equals([ 1549064342524, 1549064342524, 1549064342524, 1549064342524, ]) expect(table.getColumn('_time', 'time')).deep.equals([ 1549064313000, 1549064323000, 1549064313000, 1549064323000, ]) expect(table.getColumn('_value (number)', 'number')).deep.equals([ 10, 20, undefined, undefined, ]) expect(table.getColumn('_value (string)', 'string')).deep.equals([ undefined, undefined, 'thirty', 'fourty', ]) expect(table.getColumn('_field', 'string')).deep.equals([ 'usage_guest', 'usage_guest', 'usage_guest', 'usage_guest', ]) expect(table.getColumn('_measurement', 'string')).deep.equals([ 'cpu', 'cpu', 'cpu', 'cpu', ]) expect(table.getColumn('cpu', 'string')).deep.equals([ 'cpu-total', 'cpu-total', 'cpu0', 'cpu0', ]) expect(table.getColumn('host', 'string')).deep.equals([ 'oox4k.local', 'oox4k.local', 'oox4k.local', 'oox4k.local', ]) expect(table.getColumn('table', 'number')).deep.equals([0, 1, 2, 3]) expect(table.getColumnName('_value (number)')).deep.equals('_value') expect(table.getColumnName('_value (string)')).deep.equals('_value') }) it('uses the default annotation to fill in empty values', async () => { const CSV = `#group,false,false,true,true,true,true,false #datatype,string,unsignedLong,string,string,boolean,long,dateTime:RFC3339 #default,_result,,,cpu,false,6,1970-01-01T00:00:00.001000Z ,result,table,a,b,c,d,time ,,1,usage_guest,,true,,1970-01-01T00:00:00.002000Z ,,1,usage_guest,,,,` nock(url) .post(/.*/) .reply(200, CSV) const actual = await queryToTable(queryApi, 'ignored', newTable) expect(actual.getColumn('result')).deep.equals(['_result', '_result']) expect(actual.getColumn('a')).deep.equals(['usage_guest', 'usage_guest']) expect(actual.getColumn('b')).deep.equals(['cpu', 'cpu']) expect(actual.getColumn('c')).deep.equals([true, false]) expect(actual.getColumn('d')).deep.equals([6, 6]) expect(actual.getColumn('time')).deep.equals([2, 1]) }) it('parses empty numeric values as null', async () => { const CSV = `#group,false,false,true,true,false,true,true,true,true,true #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,double,string,string,string,string #default,_result,,,,,,,,, ,result,table,_start,_stop,_time,_value,_field,_measurement,cpu,host ,,0,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:33Z,10,usage_guest,cpu,cpu-total,oox4k.local ,,1,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:43Z,,usage_guest,cpu,cpu-total,oox4k.local` nock(url) .post(/.*/) .reply(200, CSV) const table = await queryToTable(queryApi, 'ignored', newTable) expect(table.getColumn('_value')).deep.equals([10, null]) }) it('handles newlines inside string values', async () => { const CSV = `#group,false,false,false,false #datatype,string,long,string,long #default,_result,,, ,result,table,message,value ,,0,howdy,5 ,,0,"hello there",5 ,,0,hi,6 #group,false,false,false,false #datatype,string,long,string,long #default,_result,,, ,result,table,message,value ,,1,howdy,5 ,,1,"hello there",5 ,,1,hi,6` nock(url) .post(/.*/) .reply(200, CSV) const table = await queryToTable(queryApi, 'ignored', newTable) expect(table.getColumn('value')).deep.equals([5, 5, 6, 5, 5, 6]) expect(table.getColumn('message')).deep.equals([ 'howdy', 'hello\n\nthere', 'hi', 'howdy', 'hello\n\nthere', 'hi', ]) }) describe('tableOptions', () => { ;[[1, 1]].forEach(([length, wants]) => { it(`uses default maxTableLength ${length}`, async () => { const CSV = `#group,false #datatype,long #default, ,result ,1` nock(url) .post(/.*/) .reply(200, CSV) const actual = await queryToTable(queryApi, 'ignored', newTable, { maxTableLength: length, }) expect(actual.getColumn('result')?.length).deep.equals(wants) }) }) ;[ [0, undefined], [1, 1], [undefined, 3 /* because the default is higher */], ].forEach(([length, wants]) => { it(`uses custom maxTableLength ${length}`, async () => { const CSV = `#group,false #datatype,long #default, ,result ,1 ,2 ,3` nock(url) .post(/.*/) .reply(200, CSV) const actual = await queryToTable(queryApi, 'ignored', newTable, { maxTableLength: length, }) expect(actual.getColumn('result')?.length).deep.equals(wants) }) }) it(`uses custom accept filter`, async () => { const CSV = `#group,false #datatype,long #default, ,result ,1 ,2 ,3` nock(url) .post(/.*/) .reply(200, CSV) const actual = await queryToTable(queryApi, 'ignored', newTable, { accept: (row: string[]) => row[0] === '2', maxTableLength: 2, }) expect(actual.getColumn('result')).deep.equals([2]) }) it(`uses custom accept filters`, async () => { const CSV = `#group,false #datatype,long #default, ,result ,1 ,2 ,3` nock(url) .post(/.*/) .reply(200, CSV) const actual = await queryToTable(queryApi, 'ignored', newTable, { accept: [ (row: string[]): boolean => Number(row[0]) < 3, (row: string[]): boolean => row[0] !== '1', ], }) expect(actual.getColumn('result')).deep.equals([2]) }) it(`uses custom accept filters and maxTableLength`, async () => { const CSV = `#group,false #datatype,long #default, ,result ,1 ,2 ,3` nock(url) .post(/.*/) .reply(200, CSV) const actual = await queryToTable(queryApi, 'ignored', newTable, { maxTableLength: 1, accept: (row: string[]) => Number(row[0]) > 1, }) expect(actual.getColumn('result')).deep.equals([2]) }) it(`uses custom columns`, async () => { const CSV = `#group,false #datatype,long #default, ,result ,1 ,2 ,3` nock(url) .post(/.*/) .reply(200, CSV) const actual = await queryToTable(queryApi, 'ignored', newTable, { columns: ['a'], }) expect(actual.getColumn('result')).is.null }) it(`handles server error`, async () => { nock(url) .post(/.*/) .reply(500, 'not ok') await queryToTable(queryApi, 'ignored', newTable) .then(() => { expect.fail('must not succeed') }) .catch(e => { expect(e) .property('statusCode') .to.equal(500) }) }) it(`handles client abort error with success`, async () => { const chunks = `#group,false #datatype,long #default, ,result ,1 ,2 ,3 `.split('\n') let chunkIndex = 0 let res: any nock(url) .post(/.*/) .reply((_uri, _requestBody) => [ 200, new Readable({ read(): any { if (chunkIndex === chunks.length) { res.emit('aborted') return } this.push(chunks[chunkIndex] + '\n') chunkIndex++ }, }), { 'X-Whatever': (_req: any, _res: any, _body: any): string => { res = _res return '1' }, }, ]) const actual = await queryToTable(queryApi, 'ignored', newTable) expect(actual.getColumn('result')).deep.equals([1, 2, 3]) }) }) }) describe('queryToFromFluxResult', () => { beforeEach(() => { nock.disableNetConnect() }) afterEach(() => { nock.cleanAll() nock.enableNetConnect() }) it('returns a group key union', async () => { const CSV = `#group,true,false,false,true #datatype,string,string,string,string #default,,,, ,a,b,c,d ,1,2,3,4 #group,false,false,true,false #datatype,string,string,string,string #default,,,, ,a,b,c,d ,1,2,3,4` nock(url) .post(/.*/) .reply(200, CSV) const {fluxGroupKeyUnion} = await queryToFromFluxResult( queryApi, 'ignored', newTable ) expect(fluxGroupKeyUnion).deep.equals(['a', 'c', 'd']) }) })
the_stack
import { ChildProcess, fork, spawn, SpawnOptions } from 'child_process'; import * as path from 'path'; import { MongoBinary, MongoBinaryOpts } from './MongoBinary'; import debug from 'debug'; import { assertion, uriTemplate, isNullOrUndefined, killProcess, ManagerBase, checkBinaryPermissions, } from './utils'; import { lt } from 'semver'; import { EventEmitter } from 'events'; import { MongoClient, MongoClientOptions, MongoNetworkError } from 'mongodb'; import { KeyFileMissingError, StartBinaryFailedError } from './errors'; // ignore the nodejs warning for coverage /* istanbul ignore next */ if (lt(process.version, '12.22.0')) { console.warn('Using NodeJS below 12.22.0'); } const log = debug('MongoMS:MongoInstance'); export type StorageEngine = 'devnull' | 'ephemeralForTest' | 'mmapv1' | 'wiredTiger'; /** * Overwrite replica member-specific configuration * * @see {@link https://docs.mongodb.com/manual/reference/replica-configuration/#replica-set-configuration-document-example} * * @example * ```ts * { * priority: 2, * buildIndexes: false, * votes: 2, * } * ``` */ export interface ReplicaMemberConfig { /** * A boolean that identifies an arbiter. * @defaultValue `false` - A value of `true` indicates that the member is an arbiter. */ arbiterOnly?: boolean; /** * A boolean that indicates whether the mongod builds indexes on this member. * You can only set this value when adding a member to a replica set. * @defaultValue `true` */ buildIndexes?: boolean; /** * The replica set hides this instance and does not include the member in the output of `db.hello()` or `hello`. * @defaultValue `true` */ hidden?: boolean; /** * A number that indicates the relative eligibility of a member to become a primary. * Specify higher values to make a member more eligible to become primary, and lower values to make the member less eligible. * @defaultValue 1.0 for primary/secondary; 0 for arbiters. */ priority?: number; /** * A tags document contains user-defined tag field and value pairs for the replica set member. * @defaultValue `null` * @example * ```ts * { "<tag1>": "<string1>", "<tag2>": "<string2>",... } * ``` */ tags?: any; /** * Mongodb 4.x only - The number of seconds "behind" the primary that this replica set member should "lag". * For mongodb 5.x, use `secondaryDelaySecs` instead. * @see {@link https://docs.mongodb.com/v4.4/tutorial/configure-a-delayed-replica-set-member/} * @defaultValue 0 */ slaveDelay?: number; /** * Mongodb 5.x only - The number of seconds "behind" the primary that this replica set member should "lag". * @defaultValue 0 */ secondaryDelaySecs?: number; /** * The number of votes a server will cast in a replica set election. * The number of votes each member has is either 1 or 0, and arbiters always have exactly 1 vote. * @defaultValue 1 */ votes?: number; } export interface MongoMemoryInstanceOptsBase { /** * Extra Arguments to add */ args?: string[]; /** * Set which port to use * Adds "--port" * @default from get-port */ port?: number; /** * Set which storage path to use * Adds "--" * @default TmpDir */ dbPath?: string; /** * Set which Storage Engine to use * Adds "--storageEngine" * @default "ephemeralForTest" */ storageEngine?: StorageEngine; /** * Set the Replica-Member-Config * Only has a effect when started with "MongoMemoryReplSet" */ replicaMemberConfig?: ReplicaMemberConfig; } export interface MongoMemoryInstanceOpts extends MongoMemoryInstanceOptsBase { /** * Set which parameter will be used * true -> "--auth" * false -> "--noauth" * @default false */ auth?: boolean; /** * Currently unused option * @default undefined */ dbName?: string; /** * for binding to all IP addresses set it to `::,0.0.0.0`, by default '127.0.0.1' * Adds "--bind_ip" * @default undefined */ ip?: string; /** * Set that this instance is part of a replset * Adds "--replSet" * @default undefined */ replSet?: string; /** * Location for the "--keyfile" argument * Only has an effect when "auth" is enabled and is a replset * Adds "--keyfile" * @default undefined */ keyfileLocation?: string; } export enum MongoInstanceEvents { instanceReplState = 'instanceReplState', instancePrimary = 'instancePrimary', instanceReady = 'instanceReady', instanceSTDOUT = 'instanceSTDOUT', instanceSTDERR = 'instanceSTDERR', instanceClosed = 'instanceClosed', /** Only Raw Error (emitted by mongodProcess) */ instanceRawError = 'instanceRawError', /** Raw Errors and Custom Errors */ instanceError = 'instanceError', killerLaunched = 'killerLaunched', instanceLaunched = 'instanceLaunched', instanceStarted = 'instanceStarted', } export interface MongodOpts { /** instance options */ instance: MongoMemoryInstanceOpts; /** mongo binary options */ binary: MongoBinaryOpts; /** child process spawn options */ spawn: SpawnOptions; } export interface MongoInstance extends EventEmitter { // Overwrite EventEmitter's definitions (to provide at least the event names) emit(event: MongoInstanceEvents, ...args: any[]): boolean; on(event: MongoInstanceEvents, listener: (...args: any[]) => void): this; once(event: MongoInstanceEvents, listener: (...args: any[]) => void): this; } /** * MongoDB Instance Handler Class * This Class starts & stops the "mongod" process directly and handles stdout, sterr and close events */ export class MongoInstance extends EventEmitter implements ManagerBase { // Mark these values as "readonly" & "Readonly" because modifying them after starting will have no effect // readonly is required otherwise the property can still be changed on the root level instanceOpts: MongoMemoryInstanceOpts; readonly binaryOpts: Readonly<MongoBinaryOpts>; readonly spawnOpts: Readonly<SpawnOptions>; /** * Extra options to append to "mongoclient.connect" * Mainly used for authentication */ extraConnectionOptions?: MongoClientOptions; /** * The "mongod" Process reference */ mongodProcess?: ChildProcess; /** * The "mongo_killer" Process reference */ killerProcess?: ChildProcess; /** * This boolean is "true" if the instance is elected to be PRIMARY */ isInstancePrimary: boolean = false; /** * This boolean is "true" if the instance is successfully started */ isInstanceReady: boolean = false; /** * This boolean is "true" if the instance is part of an replset */ isReplSet: boolean = false; constructor(opts: Partial<MongodOpts>) { super(); this.instanceOpts = { ...opts.instance }; this.binaryOpts = { ...opts.binary }; this.spawnOpts = { ...opts.spawn }; this.on(MongoInstanceEvents.instanceReady, () => { this.isInstanceReady = true; this.debug('constructor: Instance is ready!'); }); this.on(MongoInstanceEvents.instanceError, async (err: string | Error) => { this.debug(`constructor: Instance has thrown an Error: ${err.toString()}`); this.isInstanceReady = false; this.isInstancePrimary = false; await this.stop(); }); } /** * Debug-log with template applied * @param msg The Message to log */ protected debug(msg: string, ...extra: unknown[]): void { const port = this.instanceOpts.port ?? 'unknown'; log(`Mongo[${port}]: ${msg}`, ...extra); } /** * Create an new instance an call method "start" * @param opts Options passed to the new instance */ static async create(opts: Partial<MongodOpts>): Promise<MongoInstance> { log('create: Called .create() method'); const instance = new this(opts); await instance.start(); return instance; } /** * Create an array of arguments for the mongod instance */ prepareCommandArgs(): string[] { this.debug('prepareCommandArgs'); assertion( !isNullOrUndefined(this.instanceOpts.port), new Error('"instanceOpts.port" is required to be set!') ); assertion( !isNullOrUndefined(this.instanceOpts.dbPath), new Error('"instanceOpts.dbPath" is required to be set!') ); const result: string[] = []; result.push('--port', this.instanceOpts.port.toString()); result.push('--dbpath', this.instanceOpts.dbPath); // "!!" converts the value to an boolean (double-invert) so that no "falsy" values are added if (!!this.instanceOpts.replSet) { this.isReplSet = true; result.push('--replSet', this.instanceOpts.replSet); } if (!!this.instanceOpts.storageEngine) { result.push('--storageEngine', this.instanceOpts.storageEngine); } if (!!this.instanceOpts.ip) { result.push('--bind_ip', this.instanceOpts.ip); } if (this.instanceOpts.auth) { result.push('--auth'); if (this.isReplSet) { assertion(!isNullOrUndefined(this.instanceOpts.keyfileLocation), new KeyFileMissingError()); result.push('--keyFile', this.instanceOpts.keyfileLocation); } } else { result.push('--noauth'); } const final = result.concat(this.instanceOpts.args ?? []); this.debug('prepareCommandArgs: final argument array:' + JSON.stringify(final)); return final; } /** * Create the mongod process * @fires MongoInstance#instanceStarted */ async start(): Promise<void> { this.debug('start'); this.isInstancePrimary = false; this.isInstanceReady = false; this.isReplSet = false; const launch: Promise<void> = new Promise((res, rej) => { this.once(MongoInstanceEvents.instanceReady, res); this.once(MongoInstanceEvents.instanceError, rej); this.once(MongoInstanceEvents.instanceClosed, () => { rej(new Error('Instance Exited before being ready and without throwing an error!')); }); }); const mongoBin = await MongoBinary.getPath(this.binaryOpts); await checkBinaryPermissions(mongoBin); this.debug('start: Starting Processes'); this.mongodProcess = this._launchMongod(mongoBin); // This assertion is here because somewhere between nodejs 12 and 16 the types for "childprocess.pid" changed to include "| undefined" // it is tested and a error is thrown in "this_launchMongod", but typescript somehow does not see this yet as of 4.3.5 assertion( !isNullOrUndefined(this.mongodProcess.pid), new Error('MongoD Process failed to spawn') ); this.killerProcess = this._launchKiller(process.pid, this.mongodProcess.pid); await launch; this.emit(MongoInstanceEvents.instanceStarted); this.debug('start: Processes Started'); } /** * Shutdown all related processes (Mongod Instance & Killer Process) */ async stop(): Promise<boolean> { this.debug('stop'); if (!this.mongodProcess && !this.killerProcess) { this.debug('stop: nothing to shutdown, returning'); return false; } if (!isNullOrUndefined(this.mongodProcess)) { // try to run "shutdown" before running "killProcess" (gracefull "SIGINT") // using this, otherwise on windows nodejs will handle "SIGINT" & "SIGTERM" & "SIGKILL" the same (instant exit) if (this.isReplSet) { let con: MongoClient | undefined; try { this.debug('stop: trying shutdownServer'); const port = this.instanceOpts.port; const ip = this.instanceOpts.ip; assertion( !isNullOrUndefined(port), new Error('Cannot shutdown replset gracefully, no "port" is provided') ); assertion( !isNullOrUndefined(ip), new Error('Cannot shutdown replset gracefully, no "ip" is provided') ); con = await MongoClient.connect(uriTemplate(ip, port, 'admin'), { useNewUrlParser: true, useUnifiedTopology: true, ...this.extraConnectionOptions, }); const admin = con.db('admin'); // just to ensure it is actually the "admin" database // "timeoutSecs" is set to "1" otherwise it will take at least "10" seconds to stop (very long tests) await admin.command({ shutdown: 1, force: true, timeoutSecs: 1 }); } catch (err) { // Quote from MongoDB Documentation (https://docs.mongodb.com/manual/reference/command/replSetStepDown/#client-connections): // > Starting in MongoDB 4.2, replSetStepDown command no longer closes all client connections. // > In MongoDB 4.0 and earlier, replSetStepDown command closes all client connections during the step down. // so error "MongoNetworkError: connection 1 to 127.0.0.1:41485 closed" will get thrown below 4.2 if ( !( err instanceof MongoNetworkError && /^connection \d+ to [\d.]+:\d+ closed$/i.test(err.message) ) ) { console.warn(err); } } finally { if (!isNullOrUndefined(con)) { // even if it errors out, somehow the connection stays open await con.close(); } } } await killProcess(this.mongodProcess, 'mongodProcess', this.instanceOpts.port); this.mongodProcess = undefined; // reset reference to the childProcess for "mongod" } else { this.debug('stop: mongodProcess: nothing to shutdown, skipping'); } if (!isNullOrUndefined(this.killerProcess)) { await killProcess(this.killerProcess, 'killerProcess', this.instanceOpts.port); this.killerProcess = undefined; // reset reference to the childProcess for "mongo_killer" } else { this.debug('stop: killerProcess: nothing to shutdown, skipping'); } this.debug('stop: Instance Finished Shutdown'); return true; } /** * Actually launch mongod * @param mongoBin The binary to run * @fires MongoInstance#instanceLaunched */ _launchMongod(mongoBin: string): ChildProcess { this.debug('_launchMongod: Launching Mongod Process'); const childProcess = spawn(path.resolve(mongoBin), this.prepareCommandArgs(), { ...this.spawnOpts, stdio: 'pipe', // ensure that stdio is always an pipe, regardless of user input }); childProcess.stderr?.on('data', this.stderrHandler.bind(this)); childProcess.stdout?.on('data', this.stdoutHandler.bind(this)); childProcess.on('close', this.closeHandler.bind(this)); childProcess.on('error', this.errorHandler.bind(this)); if (isNullOrUndefined(childProcess.pid)) { throw new StartBinaryFailedError(path.resolve(mongoBin)); } this.emit(MongoInstanceEvents.instanceLaunched); return childProcess; } /** * Spawn an seperate process to kill the parent and the mongod instance to ensure "mongod" gets stopped in any case * @param parentPid Parent nodejs process * @param childPid Mongod process to kill * @fires MongoInstance#killerLaunched */ _launchKiller(parentPid: number, childPid: number): ChildProcess { this.debug( `_launchKiller: Launching Killer Process (parent: ${parentPid}, child: ${childPid})` ); // spawn process which kills itself and mongo process if current process is dead const killer = fork( path.resolve(__dirname, '../../scripts/mongo_killer.js'), [parentPid.toString(), childPid.toString()], { detached: true, stdio: 'ignore', // stdio cannot be done with an detached process cross-systems and without killing the fork on parent termination } ); killer.unref(); // dont force an exit on the fork when parent is exiting this.emit(MongoInstanceEvents.killerLaunched); return killer; } /** * Event "error" handler * @param err The Error to handle * @fires MongoInstance#instanceRawError * @fires MongoInstance#instanceError */ errorHandler(err: string): void { this.emit(MongoInstanceEvents.instanceRawError, err); this.emit(MongoInstanceEvents.instanceError, err); } /** * Write the CLOSE event to the debug function * @param code The Exit code to handle * @fires MongoInstance#instanceClosed */ closeHandler(code: number, signal: string): void { // check if the platform is windows, if yes check if the code is not "12" or "0" otherwise just check code is not "0" // because for mongodb any event on windows (like SIGINT / SIGTERM) will result in an code 12 // https://docs.mongodb.com/manual/reference/exit-codes/#12 if ((process.platform === 'win32' && code != 12 && code != 0) || code != 0) { this.debug('closeHandler: Mongod instance closed with an non-0 (or non 12 on windows) code!'); } this.debug(`closeHandler: "${code}" "${signal}"`); this.emit(MongoInstanceEvents.instanceClosed, code, signal); } /** * Write STDERR to debug function * @param message The STDERR line to write * @fires MongoInstance#instanceSTDERR */ stderrHandler(message: string | Buffer): void { this.debug(`stderrHandler: ""${message.toString()}""`); // denoting the STDERR string with double quotes, because the stdout might also use quotes this.emit(MongoInstanceEvents.instanceSTDERR, message); } /** * Write STDOUT to debug function and process some special messages * @param message The STDOUT line to write/parse * @fires MongoInstance#instanceSTDOUT * @fires MongoInstance#instanceReady * @fires MongoInstance#instanceError * @fires MongoInstance#instancePrimary * @fires MongoInstance#instanceReplState */ stdoutHandler(message: string | Buffer): void { const line: string = message.toString().trim(); // trimming to remove extra new lines and spaces around the message this.debug(`stdoutHandler: ""${line}""`); // denoting the STDOUT string with double quotes, because the stdout might also use quotes this.emit(MongoInstanceEvents.instanceSTDOUT, line); // dont use "else if", because input can be multiple lines and match multiple things if (/waiting for connections/i.test(line)) { this.emit(MongoInstanceEvents.instanceReady); } if (/address already in use/i.test(line)) { this.emit( MongoInstanceEvents.instanceError, `Port "${this.instanceOpts.port}" already in use` ); } if (/mongod instance already running/i.test(line)) { this.emit(MongoInstanceEvents.instanceError, 'Mongod already running'); } if (/permission denied/i.test(line)) { this.emit(MongoInstanceEvents.instanceError, 'Mongod permission denied'); } // Cannot fix CodeQL warning, without a example output of what to expect if (/Data directory .*? not found/i.test(line)) { this.emit(MongoInstanceEvents.instanceError, 'Data directory not found'); } if (/CURL_OPENSSL_3['\s]+not found/i.test(line)) { this.emit( MongoInstanceEvents.instanceError, 'libcurl3 is not available on your system. Mongod requires it and cannot be started without it.\n' + 'You should manually install libcurl3 or try to use an newer version of MongoDB\n' ); } if (/CURL_OPENSSL_4['\s]+not found/i.test(line)) { this.emit( MongoInstanceEvents.instanceError, 'libcurl4 is not available on your system. Mongod requires it and cannot be started without it.\n' + 'You need to manually install libcurl4\n' ); } if (/lib[\w-.]+(?=: cannot open shared object)/i.test(line)) { const lib = line.match(/(lib[\w-.]+)(?=: cannot open shared object)/i)?.[1].toLocaleLowerCase() ?? 'unknown'; this.emit( MongoInstanceEvents.instanceError, `Instance Failed to start because an library file is missing: "${lib}"` ); } if (/\*\*\*aborting after/i.test(line)) { this.emit(MongoInstanceEvents.instanceError, 'Mongod internal error'); } // this case needs to be infront of "transition to primary complete", otherwise it might reset "isInstancePrimary" to "false" if (/transition to \w+ from \w+/i.test(line)) { const state = /transition to (\w+) from \w+/i.exec(line)?.[1] ?? 'UNKNOWN'; this.emit(MongoInstanceEvents.instanceReplState, state); if (state !== 'PRIMARY') { this.isInstancePrimary = false; } } if (/transition to primary complete; database writes are now permitted/i.test(line)) { this.isInstancePrimary = true; this.debug('stdoutHandler: emitting "instancePrimary"'); this.emit(MongoInstanceEvents.instancePrimary); } } } export default MongoInstance;
the_stack
import { relative, dirname } from "path"; export interface IPosition { file?: string, column: number, line: number } /** Matches [0-9] */ export function characterIsNumber(char: string) { const charCode = char.charCodeAt(0); return 48 <= charCode && charCode <= 57; } /** * These are settings for rendering out js which are constant throughout the project */ export interface IRenderSettings { minify: boolean, indent: number, scriptLanguage: ScriptLanguages, columnWidth: number, moduleFormat: ModuleFormat, includeExtensionsInImports: boolean, comments: boolean | "docstring" | "info", } export interface IParseSettings { comments: boolean } export enum ModuleFormat { ESM = "esm", CJS = "cjs" } export enum ScriptLanguages { Javascript, Typescript, Rust } /** * These are settings for rendering out js which are dependant on the context of rendering */ export interface IRenderOptions { inline: boolean } export const defaultRenderSettings = Object.freeze<IRenderSettings>({ scriptLanguage: ScriptLanguages.Javascript, minify: false, indent: 4, columnWidth: 80, moduleFormat: ModuleFormat.ESM, includeExtensionsInImports: false, comments: true, }); export const defaultParseSettings = Object.freeze<IParseSettings>({ comments: true }); export function makeRenderSettings(partialSettings: Partial<IRenderSettings>): IRenderSettings { return { ...defaultRenderSettings, ...partialSettings }; } export interface IRenderable { render(settings: IRenderSettings, options?: Partial<IRenderOptions>): string; } /** * Represents a token * @typedef TokenType an enum represents tokens */ export interface Token<TokenType> { type: TokenType, value?: string, line: number, column: number, } export interface ITokenReaderSettings<TokenType> { reverse: Map<TokenType, string>, tokenLengths?: Map<TokenType, number>, combinations?: TokenReaderCombineMap<TokenType>, file?: string | null, // The filename } export interface ITokenizationSettings { file?: string | null, lineOffset?: number, columnOffset?: number, } type TokenReaderCombineMap<TokenType> = Map<TokenType, Array<[Array<TokenType>, TokenType]>>; /** * Creates a combination map suitable for a token reader. * Mainly used to produce the structure the token reader uses once. * @param collapse [[token1, token2, ...], finalToken] */ export function createCombineMap<TokenType>( collapse: Array<[Array<TokenType>, TokenType]> ): TokenReaderCombineMap<TokenType> { const combinationMap: TokenReaderCombineMap<TokenType> = new Map(); for (const [tokens, resolve] of collapse) { const lastChar = tokens[tokens.length - 1]; if (combinationMap.has(lastChar)) { combinationMap.get(lastChar)!.push([tokens, resolve]); } else { combinationMap.set(lastChar, [[tokens, resolve]]); } } return combinationMap; } /** * A token reader and handler * @typedef TokenType the token type to read */ export class TokenReader<TokenType> { filename: string | null; private _tokens: Array<Token<TokenType>> = []; private _readHead = 0; private _reverse: Map<TokenType, string>; private _lengths?: Map<TokenType, number>; // Only necessary if a combination map has primitive token with a length greater than 1 private _combine: Map<TokenType, Array<[TokenType[], TokenType]>>; // Maps a token which is the start of a sequence to a array of map of a sequence to a final token // Used for assuring combining tokens happen if they are immediate private _lastInsertPoint: number = 0; /** * @param collapse A map of a sequence of tokens to a respective "grouped" token e.g assign + greater than is collapsed to arrow function * @param file A associate file from where the tokens originated (optional) * @param reverse Token reader settings */ constructor(settings: ITokenReaderSettings<TokenType>) { if (settings.combinations) this._combine = this._combine = settings.combinations; if (settings.file) this.filename = settings.file; if (settings.tokenLengths) this._lengths = settings.tokenLengths; this._reverse = settings.reverse; } /** Adds a new token. Method checks top of array to see if there is a combined token */ add(token: Token<TokenType>) { this._tokens.push(token); // Combination of tokens // Check whether there is a combination map associated under the reader, that the token being inserted may // lead to a combination AND that the position the token is being inserted to is // immediately after the previous (e.g no white space) if (this._combine) { if ( this._combine.has(token.type) && token.column === this._lastInsertPoint ) { combinations: for (const [set, final] of this._combine.get(token.type)!) { // Look backwards through the combination matching the end of the array up with set (the sequence of tokens taken to produce the final token) for (let i = 0; i < set.length; i++) { const match = this._tokens[this._tokens.length - set.length + i]; if (match === undefined || match.type !== set[i]) continue combinations; } let leftMostPosition: number; // Remove the original tokens for (let i = 0; i < set.length; i++) { leftMostPosition = this._tokens.pop()!.column; } // Add the new combined token this._tokens.push({ type: final, column: leftMostPosition!, line: token.line }); } } // Last insert point is to make sure combination only happens when the next token is incident with the // previous. As the column points to the start of the token the length must be used to found the column // at the end of the token this._lastInsertPoint = token.column + (token.value?.length ?? this._lengths?.get(token.type) ?? 1); } } /** Removes last token from top */ pop() { this._tokens.pop(); } /** * Returns the upcoming token without moving * @param offset how far to peek */ peek(offset = 1): Token<TokenType> | undefined { return this._tokens[this._readHead + offset]; } /** Returns what is on the top * @example num = 2 returns to the 3rd to last token from the top */ peekFromTop(num = 0): Token<TokenType> { return this._tokens[this._tokens.length - num - 1]; } /** Advances head and returns new token. TODO is this used? */ next(): Token<TokenType> { return this._tokens[++this._readHead]; } /** * Moves the read head forward * @param offset the number to move (defaults to 1) */ move(offset = 1): void { this._readHead += offset; } /** * Used to assert the current token matches something the parser expects * @param toMatch the token type the current token has to match */ expect(toMatch: TokenType) { if (this.current.type !== toMatch) { this.throwExpect(`Expected "${this._reverse.get(toMatch)}"`); } } /** * Throws a expect error. If in file will append filename and position of error * @param message Message saying what it parser was expecting */ throwExpect(message: string, top = false): never { const current = top ? this.top : this.current; message += ` received "${this._reverse.get(current.type)}"`; if (this.filename) { message += ` at ${this.filename}:${current.line}:${current.column}`; } throw new ParseError(message); } /** * Throws a parse error. If reader has associated file will append that to error message * @param message */ throwError(message: string = "Error"): never { if (this.filename) { message += ` in ${this.filename}:${this.current.line}:${this.current.type}`; } throw new ParseError(message); } /** runs this.expect(tokenType) on the current token and proceeds one step TODO better name @param toMatch the token type the current token has to match */ expectNext(toMatch: TokenType) { this.expect(toMatch); this.move(); } /** * Given a function this function runs through the token list and returns the token after the callback returns true. Does not move the actual read head. Used for looking ahead. TODO see object literal parsing. * STARTS AT CURRENT TOKEN * @returns the token type at which `cb` returns true and the distance from the current position * @param next a boolean to represent to return the token type ON the `cb` returning true or the next token */ run(cb: (token: TokenType) => boolean, next: boolean = false): [TokenType, number] { let iter = 0; // Start at the current and go until callback returns true for (let i = this._readHead; i < this.length; i++) { const result = cb.call(undefined, this._tokens[i].type); iter++; if (result) { return [this._tokens[next ? i + 1 : i].type, iter]; } } throw Error(`TokenReader.run ran function without finding`) } /** * Debugging function to print tokens */ printTable() { console.table(this._tokens.map(token => ({ ...token, typeName: this._reverse.get(token.type) }))) } /** * Returns the number of tokens in the reader */ get length() { return this._tokens.length; } /** * Returns the current token */ get current() { return this._tokens[this._readHead]; } /** * Returns the top token. Used during tokenization */ get top() { return this._tokens[this._tokens.length - 1]; } } export class ParseError extends Error { constructor(message: string) { super(message); this.name = "ParseError"; } } /** * Given the `importer` file wants to reference the `importee` file. It creates the path it would use to import it */ export function getImportPath(importer: string, importee: string) { let importPath = relative( dirname(importer.replace(/\\/g, "/")), importee.replace(/\\/g, "/") ); if (importPath[0] !== ".") { importPath = "./" + importPath; } return importPath.replace(/\\/g, "/"); }
the_stack
export namespace Enum { /** * */ export abstract class AbstractEnum { public value: string /** * */ constructor(value: string) { this.value = value } /** * */ toString(): string { return this.value } } /** * */ export class Command extends AbstractEnum { static readonly LOADBG = new Command('LOADBG') static readonly LOAD = new Command('LOAD') static readonly PLAY = new Command('PLAY') static readonly PAUSE = new Command('PAUSE') static readonly RESUME = new Command('RESUME') static readonly STOP = new Command('STOP') static readonly CLEAR = new Command('CLEAR') static readonly CALL = new Command('CALL') static readonly SWAP = new Command('SWAP') static readonly ADD = new Command('ADD') static readonly REMOVE = new Command('REMOVE') static readonly PRINT = new Command('PRINT') static readonly LOG_LEVEL = new Command('LOG LEVEL') static readonly LOG_CATEGORY = new Command('LOG CATEGORY') static readonly SET = new Command('SET') static readonly LOCK = new Command('LOCK') static readonly DATA_STORE = new Command('DATA STORE') static readonly DATA_RETRIEVE = new Command('DATA RETRIEVE') static readonly DATA_LIST = new Command('DATA LIST') static readonly DATA_REMOVE = new Command('DATA REMOVE') static readonly CG_ADD = new Command('CG ADD') static readonly CG_PLAY = new Command('CG PLAY') static readonly CG_STOP = new Command('CG STOP') static readonly CG_NEXT = new Command('CG NEXT') static readonly CG_REMOVE = new Command('CG REMOVE') static readonly CG_CLEAR = new Command('CG CLEAR') static readonly CG_UPDATE = new Command('CG UPDATE') static readonly CG_INVOKE = new Command('CG INVOKE') static readonly CG_INFO = new Command('CG INFO') static readonly MIXER_KEYER = new Command('MIXER KEYER') static readonly MIXER_CHROMA = new Command('MIXER CHROMA') static readonly MIXER_BLEND = new Command('MIXER BLEND') static readonly MIXER_OPACITY = new Command('MIXER OPACITY') static readonly MIXER_BRIGHTNESS = new Command('MIXER BRIGHTNESS') static readonly MIXER_SATURATION = new Command('MIXER SATURATION') static readonly MIXER_CONTRAST = new Command('MIXER CONTRAST') static readonly MIXER_LEVELS = new Command('MIXER LEVELS') static readonly MIXER_FILL = new Command('MIXER FILL') static readonly MIXER_CLIP = new Command('MIXER CLIP') static readonly MIXER_ANCHOR = new Command('MIXER ANCHOR') static readonly MIXER_CROP = new Command('MIXER CROP') static readonly MIXER_ROTATION = new Command('MIXER ROTATION') static readonly MIXER_PERSPECTIVE = new Command('MIXER PERSPECTIVE') static readonly MIXER_MIPMAP = new Command('MIXER MIPMAP') static readonly MIXER_VOLUME = new Command('MIXER VOLUME') static readonly MIXER_MASTERVOLUME = new Command('MIXER MASTERVOLUME') static readonly MIXER_STRAIGHT_ALPHA_OUTPUT = new Command('MIXER STRAIGHT_ALPHA_OUTPUT') static readonly MIXER_GRID = new Command('MIXER GRID') static readonly MIXER_COMMIT = new Command('MIXER COMMIT') static readonly MIXER_CLEAR = new Command('MIXER CLEAR') static readonly CHANNEL_GRID = new Command('CHANNEL_GRID') static readonly THUMBNAIL_LIST = new Command('THUMBNAIL LIST') static readonly THUMBNAIL_RETRIEVE = new Command('THUMBNAIL RETRIEVE') static readonly THUMBNAIL_GENERATE = new Command('THUMBNAIL GENERATE') static readonly THUMBNAIL_GENERATE_ALL = new Command('THUMBNAIL GENERATE_ALL') static readonly CINF = new Command('CINF') static readonly CLS = new Command('CLS') static readonly FLS = new Command('FLS') static readonly TLS = new Command('TLS') static readonly VERSION = new Command('VERSION') static readonly INFO = new Command('INFO') static readonly INFO_TEMPLATE = new Command('INFO TEMPLATE') static readonly INFO_CONFIG = new Command('INFO CONFIG') static readonly INFO_PATHS = new Command('INFO PATHS') static readonly INFO_SYSTEM = new Command('INFO SYSTEM') static readonly INFO_SERVER = new Command('INFO SERVER') static readonly INFO_QUEUES = new Command('INFO QUEUES') static readonly INFO_THREADS = new Command('INFO THREADS') static readonly INFO_DELAY = new Command('INFO DELAY') static readonly DIAG = new Command('DIAG') static readonly GL_INFO = new Command('GL INFO') static readonly GL_GC = new Command('GL GC') static readonly BYE = new Command('BYE') static readonly KILL = new Command('KILL') static readonly RESTART = new Command('RESTART') static readonly HELP = new Command('HELP') static readonly HELP_PRODUCER = new Command('HELP PRODUCER') static readonly HELP_CONSUMER = new Command('HELP CONSUMER') } /** * */ export class Producer extends AbstractEnum { static readonly FFMPEG = new Producer('FFmpeg Producer') static readonly DECKLINK = new Producer('Decklink Producer') static readonly HTML = new Producer('HTML Producer') static readonly PSD = new Producer('PSD Scene Producer') static readonly FLASH = new Producer('Flash Producer (.ft)') static readonly FLASH_CT = new Producer('Flash Producer (.ct)') static readonly FLASH_SWF = new Producer('Flash Producer (.swf)') static readonly IMAGE_SCROLL = new Producer('Image Scroll Producer') static readonly IMAGE = new Producer('Image Producer') static readonly REROUTE = new Producer('Reroute Producer') static readonly TEXT = new Producer('Text Producer') static readonly SCENE = new Producer('XML Scene Producer') static readonly COLOR = new Producer('Color Producer') } /** * */ export class Consumer extends AbstractEnum { static readonly FFMPEG = new Consumer('FFMpeg Consumer') static readonly STREAMING = new Consumer('Streaming Consumer') static readonly ADUIO = new Consumer('System Audio Consumer') static readonly BLUEFISH = new Consumer('Bluefish Consumer') static readonly DECKLINK = new Consumer('Decklink Consumer') static readonly SCREEN = new Consumer('Screen Consumer') static readonly IVGA = new Consumer('iVGA Consumer') static readonly IMAGE = new Consumer('Image Consumer') } /** * * */ export class Version extends AbstractEnum { static readonly SERVER = new Version('SERVER') static readonly FLASH = new Version('FLASH') static readonly TEMPLATEHOST = new Version('TEMPLATEHOST') static readonly CEF = new Version('CEF') } /** * * */ export class Lock extends AbstractEnum { static readonly ACQUIRE = new Lock('ACQUIRE') static readonly RELEASE = new Lock('RELEASE') static readonly CLEAR = new Lock('CLEAR') } /** * * */ export class LogCategory extends AbstractEnum { static readonly CALLTRACE = new LogCategory('CALLTRACE') static readonly COMMUNICATION = new LogCategory('COMMUNICATION') } /** * * */ export class Chroma extends AbstractEnum { static readonly NONE = new Chroma('NONE') static readonly GREEN = new Chroma('GREEN') static readonly BLUE = new Chroma('BLUE') } /** * * */ export class LogLevel extends AbstractEnum { static readonly TRACE = new LogLevel('TRACE') static readonly DEBUG = new LogLevel('DEBUG') static readonly INFO = new LogLevel('INFO') static readonly WARNING = new LogLevel('WARNING') static readonly ERROR = new LogLevel('ERROR') static readonly FATAL = new LogLevel('FATAL') // @todo: 2.1????? } /** * * */ export class Transition extends AbstractEnum { static readonly CUT = new Transition('CUT') static readonly MIX = new Transition('MIX') static readonly PUSH = new Transition('PUSH') static readonly WIPE = new Transition('WIPE') static readonly SLIDE = new Transition('SLIDE') static readonly STING = new Transition('STING') } /** * * */ export class Direction extends AbstractEnum { static readonly LEFT = new Direction('LEFT') static readonly RIGHT = new Direction('RIGHT') } /** * */ export class BlendMode extends AbstractEnum { static readonly NORMAL = new BlendMode('NORMAL') static readonly LIGHTEN = new BlendMode('LIGHTEN') static readonly DARKEN = new BlendMode('DARKEN') static readonly MULTIPLY = new BlendMode('MULTIPLY') static readonly AVERAGE = new BlendMode('AVERAGE') static readonly ADD = new BlendMode('ADD') static readonly SUBTRACT = new BlendMode('SUBTRACT') static readonly DIFFERENCE = new BlendMode('DIFFERENCE') static readonly NEGATION = new BlendMode('NEGATION') static readonly EXCLUSION = new BlendMode('EXCLUSION') static readonly SCREEN = new BlendMode('SCREEN') static readonly OVERLAY = new BlendMode('OVERLAY') static readonly SOFT_LIGHT = new BlendMode('SOFT LIGHT') static readonly HARD_LIGHT = new BlendMode('HARD LIGHT') static readonly COLOR_DODGE = new BlendMode('COLOR DODGE') static readonly COLOR_BURN = new BlendMode('COLOR BURN') static readonly LINEAR_DODGE = new BlendMode('LINEAR DODGE') static readonly LINEAR_BURN = new BlendMode('LINEAR BURN') static readonly LINEAR_LIGHT = new BlendMode('LINEAR LIGHT') static readonly VIVID_LIGHT = new BlendMode('VIVID LIGHT') static readonly PIN_LIGHT = new BlendMode('PIN LIGHT') static readonly HARD_MIX = new BlendMode('HARD MIX') static readonly REFLECT = new BlendMode('REFLECT') static readonly GLOW = new BlendMode('GLOW') static readonly PHOENIX = new BlendMode('PHOENIX') static readonly CONTRAST = new BlendMode('CONTRAST') static readonly SATURATION = new BlendMode('SATURATION') static readonly COLOR = new BlendMode('COLOR') static readonly LUMINOSITY = new BlendMode('LUMINOSITY') } /** * */ export class Ease extends AbstractEnum { static readonly LINEAR = new Ease('LINEAR') static readonly EASELINEAR = Ease.LINEAR static readonly NONE = new Ease('EASENONE') static readonly EASENONE = Ease.NONE static readonly IN_QUAD = new Ease('EASEINQUAD') static readonly EASEINQUAD = Ease.IN_QUAD static readonly OUT_QUAD = new Ease('EASEOUTQUAD') static readonly EASEOUTQUAD = Ease.OUT_QUAD static readonly IN_OUT_QUAD = new Ease('EASEINOUTQUAD') static readonly EASEINOUTQUAD = Ease.IN_OUT_QUAD static readonly OUT_IN_QUAD = new Ease('EASEOUTINQUAD') static readonly EASEOUTINQUAD = Ease.OUT_IN_QUAD static readonly IN_CUBIC = new Ease('EASEINCUBIC') static readonly EASEINCUBIC = Ease.IN_CUBIC static readonly OUT_CUBIC = new Ease('EASEOUTCUBIC') static readonly EASEOUTCUBIC = Ease.OUT_CUBIC static readonly IN_OUT_CUBIC = new Ease('EASEINOUTCUBIC') static readonly EASEINOUTCUBIC = Ease.IN_OUT_CUBIC static readonly OUT_IN_CUBIC = new Ease('EASEOUTINCUBIC') static readonly EASEOUTINCUBIC = Ease.OUT_IN_CUBIC static readonly IN_QUART = new Ease('EASEINQUART') static readonly EASEINQUART = Ease.IN_QUART static readonly OUT_QUART = new Ease('EASEOUTQUART') static readonly EASEOUTQUART = Ease.OUT_QUART static readonly IN_OUT_QUART = new Ease('EASEINOUTQUART') static readonly EASEINOUTQUART = Ease.IN_OUT_QUART static readonly OUT_IN_QUART = new Ease('EASEOUTINQUART') static readonly EASEOUTINQUART = Ease.OUT_IN_QUART static readonly IN_QUINT = new Ease('EASEINQUINT') static readonly EASEINQUINT = Ease.IN_QUINT static readonly OUT_QUINT = new Ease('EASEOUTQUINT') static readonly EASEOUTQUINT = Ease.OUT_QUINT static readonly IN_OUT_QUINT = new Ease('EASEINOUTQUINT') static readonly EASEINOUTQUINT = Ease.IN_OUT_QUINT static readonly OUT_IN_QUINT = new Ease('EASEOUTINQUINT') static readonly EASEOUTINQUINT = Ease.OUT_IN_QUINT static readonly IN_SINE = new Ease('EASEINSINE') static readonly EASEINSINE = Ease.IN_SINE static readonly OUT_SINE = new Ease('EASEOUTSINE') static readonly EASEOUTSINE = Ease.OUT_SINE static readonly IN_OUT_SINE = new Ease('EASEINOUTSINE') static readonly EASEINOUTSINE = Ease.IN_OUT_SINE static readonly OUT_IN_SINE = new Ease('EASEOUTINSINE') static readonly EASEOUTINSINE = Ease.OUT_IN_SINE static readonly IN_EXPO = new Ease('EASEINEXPO') static readonly EASEINEXPO = Ease.IN_EXPO static readonly OUT_EXPO = new Ease('EASEOUTEXPO') static readonly EASEOUTEXPO = Ease.OUT_EXPO static readonly IN_OUT_EXPO = new Ease('EASEINOUTEXPO') static readonly EASEINOUTEXPO = Ease.IN_OUT_EXPO static readonly OUT_IN_EXPO = new Ease('EASEOUTINEXPO') static readonly EASEOUTINEXPO = Ease.OUT_IN_EXPO static readonly IN_CIRC = new Ease('EASEINCIRC') static readonly EASEINCIRC = Ease.IN_CIRC static readonly OUT_CIRC = new Ease('EASEOUTCIRC') static readonly EASEOUTCIRC = Ease.OUT_CIRC static readonly IN_OUT_CIRC = new Ease('EASEINOUTCIRC') static readonly EASEINOUTCIRC = Ease.IN_OUT_CIRC static readonly OUT_IN_CIRC = new Ease('EASEOUTINCIRC') static readonly EASEOUTINCIRC = Ease.OUT_IN_CIRC static readonly IN_ELASTIC = new Ease('EASEINELASTIC') static readonly EASEINELASTIC = Ease.IN_ELASTIC static readonly OUT_ELASTIC = new Ease('EASEOUTELASTIC') static readonly EASEOUTELASTIC = Ease.OUT_ELASTIC static readonly IN_OUT_ELASTIC = new Ease('EASEINOUTELASTIC') static readonly EASEINOUTELASTIC = Ease.IN_OUT_ELASTIC static readonly OUT_IN_ELASTIC = new Ease('EASEOUTINELASTIC') static readonly EASEOUTINELASTIC = Ease.OUT_IN_ELASTIC static readonly IN_BACK = new Ease('EASEINBACK') static readonly EASEINBACK = Ease.IN_BACK static readonly OUT_BACK = new Ease('EASEOUTBACK') static readonly EASEOUTBACK = Ease.OUT_BACK static readonly IN_OUT_BACK = new Ease('EASEINOUTBACK') static readonly EASEINOUTBACK = Ease.IN_OUT_BACK static readonly OUT_IN_BACK = new Ease('EASEOUTINTBACK') static readonly EASEOUTINBACK = Ease.OUT_IN_BACK static readonly OUT_BOUNCE = new Ease('EASEOUTBOUNCE') static readonly EASEOUTBOUNCE = Ease.OUT_BOUNCE static readonly IN_BOUNCE = new Ease('EASEINBOUNCE') static readonly EASEINBOUNCE = Ease.IN_BOUNCE static readonly IN_OUT_BOUNCE = new Ease('EASEINOUTBOUNCE') static readonly EASEINOUTBOUNCE = Ease.IN_OUT_BOUNCE static readonly OUT_IN_BOUNCE = new Ease('EASEOUTINBOUNCE') static readonly EASEOUTINBOUNCE = Ease.OUT_IN_BOUNCE } /** * */ export class ChannelFormat extends AbstractEnum { static readonly INVALID = new ChannelFormat('invalid') static readonly PAL = new ChannelFormat('PAL') static readonly NTSC = new ChannelFormat('NTSC') static readonly SD_576P2500 = new ChannelFormat('576p2500') static readonly HD_720P2398 = new ChannelFormat('720p2398') static readonly HD_720P2400 = new ChannelFormat('720p2400') static readonly HD_720P2500 = new ChannelFormat('720p2500') static readonly HD_720P5000 = new ChannelFormat('720p5000') static readonly HD_720P2997 = new ChannelFormat('720p2997') static readonly HD_720P5994 = new ChannelFormat('720p5994') static readonly HD_720P3000 = new ChannelFormat('720p3000') static readonly HD_720P6000 = new ChannelFormat('720p6000') static readonly HD_1080P2398 = new ChannelFormat('1080p2398') static readonly HD_1080P2400 = new ChannelFormat('1080p2400') static readonly HD_1080I5000 = new ChannelFormat('1080i5000') static readonly HD_1080I5994 = new ChannelFormat('1080i5994') static readonly HD_1080I6000 = new ChannelFormat('1080i6000') static readonly HD_1080P2500 = new ChannelFormat('1080p2500') static readonly HD_1080P2997 = new ChannelFormat('1080p2997') static readonly HD_1080P3000 = new ChannelFormat('1080p3000') static readonly HD_1080P5000 = new ChannelFormat('1080p5000') static readonly HD_1080P5994 = new ChannelFormat('1080p5994') static readonly HD_1080P6000 = new ChannelFormat('1080p6000') static readonly UHD_1556P2398 = new ChannelFormat('1556p2398') static readonly UHD_1556P2400 = new ChannelFormat('1556p2400') static readonly UHD_1556P2500 = new ChannelFormat('1556p2500') static readonly DCI_1080P2398 = new ChannelFormat('dci1080p2398') static readonly DCI_1080P2400 = new ChannelFormat('dci1080p2400') static readonly DCI_1080P2500 = new ChannelFormat('dci1080p2500') static readonly UHD_2160P2398 = new ChannelFormat('2160p2398') static readonly UCH_2160P2400 = new ChannelFormat('2160p2400') static readonly UHD_2160P2500 = new ChannelFormat('2160p2500') static readonly UHD_2160P2997 = new ChannelFormat('2160p2997') static readonly UHD_2160P3000 = new ChannelFormat('2160p3000') static readonly UHD_2160P5000 = new ChannelFormat('2160p5000') static readonly UHD_2160P5994 = new ChannelFormat('2160p5994') static readonly UHD_2160P6000 = new ChannelFormat('2160p6000') static readonly DCI_2160P2398 = new ChannelFormat('dci2160p2398') static readonly DCI_2160P2400 = new ChannelFormat('dci2160p2400') static readonly DCI_2160P2500 = new ChannelFormat('dci2160p2500') } /** * */ export class ChannelLayout extends AbstractEnum { } }
the_stack
import { test } from 'tap' import { Client, errors } from '../../../' import { connection } from '../../utils' import FakeTimers from '@sinonjs/fake-timers' test('Basic', async t => { const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [{ status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 1 }) const result = await m.search( { index: 'test' }, { query: { match: { foo: 'bar' } } } ) t.same(result.body, { status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }) t.same(result.documents, [ { one: 'one' }, { two: 'two' }, { three: 'three' } ]) t.teardown(() => m.stop()) }) test('Multiple searches (inside async iterator)', t => { t.plan(4) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [{ status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }, { status: 200, hits: { hits: [ { _source: { four: 'four' } }, { _source: { five: 'five' } }, { _source: { six: 'six' } } ] } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 2 }) m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .then(result => { t.same(result.body, { status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }) t.same(result.documents, [ { one: 'one' }, { two: 'two' }, { three: 'three' } ]) }) .catch(t.error) m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .then(result => { t.same(result.body, { status: 200, hits: { hits: [ { _source: { four: 'four' } }, { _source: { five: 'five' } }, { _source: { six: 'six' } } ] } }) t.same(result.documents, [ { four: 'four' }, { five: 'five' }, { six: 'six' } ]) }) .catch(t.error) t.teardown(() => m.stop()) }) test('Multiple searches (async iterator exits)', t => { t.plan(4) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [{ status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }, { status: 200, hits: { hits: [ { _source: { four: 'four' } }, { _source: { five: 'five' } }, { _source: { six: 'six' } } ] } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() m.search({ index: 'test' }, { query: {} }) .then(result => { t.same(result.body, { status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }) t.same(result.documents, [ { one: 'one' }, { two: 'two' }, { three: 'three' } ]) }) .catch(t.error) m.search({ index: 'test' }, { query: {} }) .then(result => { t.same(result.body, { status: 200, hits: { hits: [ { _source: { four: 'four' } }, { _source: { five: 'five' } }, { _source: { six: 'six' } } ] } }) t.same(result.documents, [ { four: 'four' }, { five: 'five' }, { six: 'six' } ]) }) .catch(t.error) setImmediate(() => m.stop()) }) test('Stop a msearch processor (promises)', async t => { const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: {} } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 1 }) m.stop() try { await m.search( { index: 'test' }, { query: { match: { foo: 'bar' } } } ) } catch (err: any) { t.equal(err.message, 'The msearch processor has been stopped') } t.teardown(() => m.stop()) }) test('Bad header', t => { t.plan(1) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: {} } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() // @ts-expect-error m.search(null, { query: { match: { foo: 'bar' } } }) .catch(err => { t.equal(err.message, 'The header should be an object') }) t.teardown(() => m.stop()) }) test('Bad body', t => { t.plan(1) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: {} } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() // @ts-expect-error m.search({ index: 'test' }, null) .catch(err => { t.equal(err.message, 'The body should be an object') }) t.teardown(() => m.stop()) }) test('Retry on 429', async t => { let count = 0 const MockConnection = connection.buildMockConnection({ onRequest (params) { if (count++ === 0) { return { body: { responses: [{ status: 429, error: {} }] } } } else { return { body: { responses: [{ status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }] } } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 1, wait: 10 }) const result = await m.search( { index: 'test' }, { query: { match: { foo: 'bar' } } } ) t.same(result.body, { status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }) t.same(result.documents, [ { one: 'one' }, { two: 'two' }, { three: 'three' } ]) t.teardown(() => m.stop()) }) test('Single search errors', async t => { const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [{ status: 400, error: { foo: 'bar' } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 1 }) try { await m.search( { index: 'test' }, { query: { match: { foo: 'bar' } } } ) } catch (err: any) { t.ok(err instanceof errors.ResponseError) } t.teardown(() => m.stop()) }) test('Entire msearch fails', t => { t.plan(2) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { statusCode: 500, body: { status: 500, error: { foo: 'bar' } } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 1 }) m.search({ index: 'test' }, { query: {} }) .catch(err => { t.ok(err instanceof errors.ResponseError) }) m.search({ index: 'test' }, { query: {} }) .catch(err => { t.ok(err instanceof errors.ResponseError) }) t.teardown(() => m.stop()) }) test('Resolves the msearch helper', t => { t.plan(1) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: {} } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() m.stop() m.then( () => t.pass('called'), e => t.fail('Should not fail') ) m.catch(e => t.fail('Should not fail')) }) test('Stop the msearch helper with an error', t => { t.plan(3) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: {} } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() m.stop(new Error('kaboom')) m.then( () => t.fail('Should fail'), err => t.equal(err.message, 'kaboom') ) m.catch(err => t.equal(err.message, 'kaboom')) m.search({ index: 'test' }, { query: {} }) .catch(err => { t.equal(err.message, 'kaboom') }) }) test('Multiple searches (concurrency = 1)', t => { t.plan(4) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [{ status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 1, concurrency: 1 }) m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .then(result => { t.same(result.body, { status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }) t.same(result.documents, [ { one: 'one' }, { two: 'two' }, { three: 'three' } ]) }) .catch(t.error) m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .then(result => { t.same(result.body, { status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }) t.same(result.documents, [ { one: 'one' }, { two: 'two' }, { three: 'three' } ]) }) .catch(t.error) t.teardown(() => m.stop()) }) test('Flush interval', t => { t.plan(2) const clock = FakeTimers.install({ toFake: ['setTimeout', 'clearTimeout'] }) t.teardown(() => clock.uninstall()) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [{ status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }, { status: 200, hits: { hits: [ { _source: { four: 'four' } }, { _source: { five: 'five' } }, { _source: { six: 'six' } } ] } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .then(result => { t.equal(result.documents.length, 3) }) m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .then(result => { t.equal(result.documents.length, 3) }) setImmediate(clock.next) t.teardown(() => m.stop()) }) test('Flush interval - early stop', t => { t.plan(2) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [{ status: 200, hits: { hits: [ { _source: { one: 'one' } }, { _source: { two: 'two' } }, { _source: { three: 'three' } } ] } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .then(result => { t.equal(result.documents.length, 3) }) setImmediate(() => { m.search({ index: 'test' }, { query: { match: { foo: 'bar' } } }) .catch(err => { t.ok(err instanceof errors.ConfigurationError) }) }) m.stop() }) test('Stop should resolve the helper', t => { t.plan(1) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() setImmediate(m.stop) m.then(() => t.pass('Called')) .catch(() => t.fail('Should not fail')) }) test('Stop should resolve the helper (error)', t => { t.plan(3) const MockConnection = connection.buildMockConnection({ onRequest (params) { return { body: { responses: [] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch() setImmediate(m.stop, new Error('kaboom')) m.then(() => t.fail('Should not fail')) .catch(err => t.equal(err.message, 'kaboom')) m.catch(err => t.equal(err.message, 'kaboom')) m.then(() => t.fail('Should not fail'), err => t.equal(err.message, 'kaboom')) }) test('Should use req options', async t => { t.plan(1) const MockConnection = connection.buildMockConnection({ onRequest (params) { t.match(params.headers, { foo: 'bar' }) return { body: { responses: [{ status: 200, hits: { hits: [] } }] } } } }) const client = new Client({ node: 'http://localhost:9200', Connection: MockConnection }) const m = client.helpers.msearch({ operations: 1 }, { headers: { foo: 'bar' } }) await m.search( { index: 'test' }, { query: { match: { foo: 'bar' } } } ) t.teardown(() => m.stop()) })
the_stack
import { GuildMember, integer, Internal, snowflake, timestamp, User } from '.' /** https://discord.com/developers/docs/resources/channel#channel-object-channel-structure */ export interface Channel { /** the id of this channel */ id: snowflake /** the type of channel */ type: integer /** the id of the guild (may be missing for some channel objects received over gateway guild dispatches) */ guild_id?: snowflake /** sorting position of the channel */ position?: integer /** explicit permission overwrites for members and roles */ permission_overwrites?: Overwrite[] /** the name of the channel (1-100 characters) */ name?: string /** the channel topic (0-1024 characters) */ topic?: string /** whether the channel is nsfw */ nsfw?: boolean /** the id of the last message sent in this channel (may not point to an existing or valid message) */ last_message_id?: snowflake /** the bitrate (in bits) of the voice channel */ bitrate?: integer /** the user limit of the voice channel */ user_limit?: integer /** amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages or manage_channel, are unaffected */ rate_limit_per_user?: integer /** the recipients of the DM */ recipients?: User[] /** icon hash */ icon?: string /** id of the creator of the group DM or thread */ owner_id?: snowflake /** application id of the group DM creator if it is bot-created */ application_id?: snowflake /** for guild channels: id of the parent category for a channel (each parent category can contain up to 50 channels), for threads: id of the text channel this thread was created */ parent_id?: snowflake /** when the last pinned message was pinned. This may be null in events such as GUILD_CREATE when a message is not pinned. */ last_pin_timestamp?: timestamp /** voice region id for the voice channel, automatic when set to null */ rtc_region?: string /** the camera video quality mode of the voice channel, 1 when not present */ video_quality_mode?: integer /** an approximate count of messages in a thread, stops counting at 50 */ message_count?: integer /** an approximate count of users in a thread, stops counting at 50 */ member_count?: integer /** thread-specific fields not needed by other channels */ thread_metadata?: ThreadMetadata /** thread member object for the current user, if they have joined the thread, only included on certain API endpoints */ member?: ThreadMember /** default duration for newly created threads, in minutes, to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 */ default_auto_archive_duration?: integer /** computed permissions for the invoking user in the channel, including overwrites, only included when part of the resolved data received on a slash command interaction */ permissions?: string } /** https://discord.com/developers/docs/resources/channel#channel-object-channel-types */ export enum ChannelType { /** a text channel within a server */ GUILD_TEXT = 0, /** a direct message between users */ DM = 1, /** a voice channel within a server */ GUILD_VOICE = 2, /** a direct message between multiple users */ GROUP_DM = 3, /** an organizational category that contains up to 50 channels */ GUILD_CATEGORY = 4, /** a channel that users can follow and crosspost into their own server */ GUILD_NEWS = 5, /** a channel in which game developers can sell their game on Discord */ GUILD_STORE = 6, /** a temporary sub-channel within a GUILD_NEWS channel */ GUILD_NEWS_THREAD = 10, /** a temporary sub-channel within a GUILD_TEXT channel */ GUILD_PUBLIC_THREAD = 11, /** a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission */ GUILD_PRIVATE_THREAD = 12, /** a voice channel for hosting events with an audience */ GUILD_STAGE_VOICE = 13, } /** https://discord.com/developers/docs/resources/channel#followed-channel-object-followed-channel-structure */ export interface FollowedChannel { /** source channel id */ channel_id: snowflake /** created target webhook id */ webhook_id: snowflake } /** https://discord.com/developers/docs/resources/channel#overwrite-object-overwrite-structure */ export interface Overwrite { /** role or user id */ id: snowflake /** either 0 (role) or 1 (member) */ type: integer /** permission bit set */ allow: string /** permission bit set */ deny: string } /** https://discord.com/developers/docs/resources/channel#thread-metadata-object-thread-metadata-structure */ export interface ThreadMetadata { /** whether the thread is archived */ archived: boolean /** duration in minutes to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 */ auto_archive_duration: integer /** timestamp when the thread's archive status was last changed, used for calculating recent activity */ archive_timestamp: timestamp /** whether the thread is locked; when a thread is locked, only users with MANAGE_THREADS can unarchive it */ locked: boolean /** whether non-moderators can add other non-moderators to a thread; only available on private threads */ invitable?: boolean } /** https://discord.com/developers/docs/resources/channel#thread-member-object-thread-member-structure */ export interface ThreadMember { /** the id of the thread */ id?: snowflake /** the id of the user */ user_id?: snowflake /** the time the current user last joined the thread */ join_timestamp: timestamp /** any user-thread settings, currently only used for notifications */ flags: integer } /** https://discord.com/developers/docs/resources/channel#allowed-mentions-object-allowed-mention-types */ export enum AllowedMentionType { /** Controls role mentions */ ROLE_MENTIONS = 'roles', /** Controls user mentions */ USER_MENTIONS = 'users', /** Controls @everyone and @here mentions */ EVERYONE_MENTIONS = 'everyone', } /** https://discord.com/developers/docs/resources/channel#allowed-mentions-object-allowed-mentions-structure */ export interface AllowedMentions { /** An array of allowed mention types to parse from the content. */ parse: AllowedMentionType[] /** Array of role_ids to mention (Max size of 100) */ roles: snowflake[] /** Array of user_ids to mention (Max size of 100) */ users: snowflake[] /** For replies, whether to mention the author of the message being replied to (default false) */ replied_user: boolean } export interface ChannelCreateEvent extends Channel {} export interface ChannelUpdateEvent extends Channel {} export interface ChannelDeleteEvent extends Channel {} /** https://discord.com/developers/docs/topics/gateway#channel-pins-update-channel-pins-update-event-fields */ export interface ChannelPinsUpdateEvent { /** the id of the guild */ guild_id?: snowflake /** the id of the channel */ channel_id: snowflake /** the time at which the most recent pinned message was pinned */ last_pin_timestamp?: timestamp } /** https://discord.com/developers/docs/topics/gateway#thread-list-sync-thread-list-sync-event-fields */ export interface ThreadListSyncEvent { /** the id of the guild */ guild_id: snowflake /** the parent channel ids whose threads are being synced. If omitted, then threads were synced for the entire guild. This array may contain channel_ids that have no active threads as well, so you know to clear that data. */ channel_ids?: snowflake[] /** all active threads in the given channels that the current user can access */ threads: Channel[] /** all thread member objects from the synced threads for the current user, indicating which threads the current user has been added to */ members: ThreadMember[] } export interface ThreadMemberUpdateEvent extends ThreadMember {} /** https://discord.com/developers/docs/topics/gateway#thread-members-update-thread-members-update-event-fields */ export interface ThreadMembersUpdateEvent { /** the id of the thread */ id: snowflake /** the id of the guild */ guild_id: snowflake /** the approximate number of members in the thread, capped at 50 */ member_count: integer /** the users who were added to the thread */ added_members?: ThreadMember[] /** the id of the users who were removed from the thread */ removed_member_ids?: snowflake[] } /** https://discord.com/developers/docs/topics/gateway#typing-start-typing-start-event-fields */ export interface TypingStartEvent { /** id of the channel */ channel_id: snowflake /** id of the guild */ guild_id?: snowflake /** id of the user */ user_id: snowflake /** unix time (in seconds) of when the user started typing */ timestamp: integer /** the member who started typing if this happened in a guild */ member?: GuildMember } declare module './gateway' { interface GatewayEvents { /** new guild channel created */ CHANNEL_CREATE: ChannelCreateEvent /** channel was updated */ CHANNEL_UPDATE: ChannelUpdateEvent /** channel was deleted */ CHANNEL_DELETE: ChannelDeleteEvent /** message was pinned or unpinned */ CHANNEL_PINS_UPDATE: ChannelPinsUpdateEvent /** sent when gaining access to a channel, contains all active threads in that channel */ THREAD_LIST_SYNC: ThreadListSyncEvent /** thread member for the current user was updated */ THREAD_MEMBER_UPDATE: ThreadMemberUpdateEvent /** some user(s) were added to or removed from a thread */ THREAD_MEMBERS_UPDATE: ThreadMembersUpdateEvent /** user started typing in a channel */ TYPING_START: TypingStartEvent } } export interface ChannelPosition { /** channel id */ channel_id: snowflake /** sorting position of the channel */ position?: integer /** syncs the permission overwrites with the new parent, if moving to a new category */ lock_permissions?: boolean /** the new parent ID for the channel that is moved */ parent_id?: snowflake } declare module './internal' { interface Internal { /** https://discord.com/developers/docs/resources/guild#get-guild-channels */ getGuildChannels(guild_id: snowflake): Promise<Channel[]> /** https://discord.com/developers/docs/resources/guild#create-guild-channel */ createGuildChannel(guild_id: snowflake, options: Partial<Channel>): Promise<Channel> /** https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions */ modifyGuildChannelPositions(guild_id: snowflake, positions: ChannelPosition[]): Promise<void> } } Internal.define({ '/guilds/{guild.id}/channels': { GET: 'getGuildChannels', POST: 'createGuildChannel', PATCH: 'modifyGuildChannelPositions', }, }) declare module './internal' { interface Internal { /** https://discord.com/developers/docs/resources/channel#get-channel */ getChannel(channel_id: string): Promise<Channel> /** https://discord.com/developers/docs/resources/channel#modify-channel */ modifyChannel(channel_id: string, data: Partial<Channel>): Promise<Channel> /** https://discord.com/developers/docs/resources/channel#deleteclose-channel */ deleteChannel(channel_id: string): Promise<Channel> } } Internal.define({ '/channels/{channel.id}': { GET: 'getChannel', PATCH: 'modifyChannel', DELETE: 'deleteChannel', }, '/channels/{channel.id}/permissions/{overwrite.id}': { PUT: 'editChannelPermissions', DELETE: 'deleteChannelPermission', }, '/channels/{channel.id}/invites': { GET: 'getChannelInvites', POST: 'createChannelInvite', }, '/channels/{channel.id}/followers': { POST: 'followNewsChannel', }, '/channels/{channel.id}/typing': { POST: 'triggerTypingIndicator', }, '/channels/{channel.id}/pins': { GET: 'getPinnedMessages', }, '/channels/{channel.id}/pins/{message.id}': { PUT: 'pinMessage', DELETE: 'unpinMessage', }, '/channels/{channel.id}/recipients/{user.id}': { PUT: 'groupDMAddRecipient', DELETE: 'groupDMRemoveRecipient', }, '/channels/{channel.id}/messages/{message.id}/threads': { POST: 'startThreadwithMessage', }, '/channels/{channel.id}/threads': { POST: 'startThreadwithoutMessage', }, '/channels/{channel.id}/thread-members/@me': { PUT: 'joinThread', DELETE: 'leaveThread', }, '/channels/{channel.id}/thread-members/{user.id}': { PUT: 'addThreadMember', DELETE: 'removeThreadMember', GET: 'getThreadMember', }, '/channels/{channel.id}/thread-members': { GET: 'listThreadMembers', }, '/channels/{channel.id}/threads/active': { GET: 'listActiveThreads', }, '/channels/{channel.id}/threads/archived/public': { GET: 'listPublicArchivedThreads', }, '/channels/{channel.id}/threads/archived/private': { GET: 'listPrivateArchivedThreads', }, '/channels/{channel.id}/users/@me/threads/archived/private': { GET: 'listJoinedPrivateArchivedThreads', }, })
the_stack
import {Component, OnDestroy, OnInit} from '@angular/core'; import _countBy from 'lodash/countBy'; import _difference from 'lodash/difference'; import _groupBy from 'lodash/groupBy'; import _isEmpty from 'lodash/isEmpty'; import _map from 'lodash/map'; import _uniqBy from 'lodash/uniqBy'; import {catchError, takeUntil} from 'rxjs/operators'; import {BanguminUserService} from '../../shared/services/bangumin/bangumin-user.service'; import {AccumulatedMeanDataSchema, BangumiStatsService} from '../../shared/services/bangumi/bangumi-stats.service'; import {ActivatedRoute} from '@angular/router'; import {SubjectType} from '../../shared/enums/subject-type.enum'; import {CollectionStatusId} from '../../shared/enums/collection-status-id'; import {FormBuilder, FormGroup} from '@angular/forms'; import {forkJoin, Subject, throwError} from 'rxjs'; import {BangumiUserService} from '../../shared/services/bangumi/bangumi-user.service'; import {BangumiUser} from '../../shared/models/BangumiUser'; import {TitleService} from '../../shared/services/page/title.service'; import {TranslateService} from '@ngx-translate/core'; import {RecordSchema} from '../../shared/models/stats/record-schema'; import {curveBasis} from 'd3-shape'; import {PageState} from '../../shared/enums/page-state.enum'; @Component({ selector: 'app-profile-stats', templateUrl: './profile-statistics.component.html', styleUrls: ['./profile-statistics.component.scss'] }) export class ProfileStatisticsComponent implements OnInit, OnDestroy { pageState = PageState.InLoading; colorScheme = BangumiStatsService.colorScheme; lineCurveType = curveBasis; scoreVsCountData; // if user has no record under some subject type, that type won't be included userCurrentSubjectTypeList; // all subject types on Bangumi readonly allValidSubjectTypeList: string[] = Object.keys(SubjectType).filter(k => isNaN(Number(k))); // if user has no status record(i.e. user never drops subject), that status won't be included collectionStatusList; // all collection status types on Bangumi readonly allValidCollectionStatusList: string[] = Object.keys(CollectionStatusId).filter(k => isNaN(Number(k))); selectedTypeListForscoreVsCount; accumulatedMeanData: AccumulatedMeanDataSchema[] = []; countByTypeDataTranslated; // mean, median, stdDev descStatData; targetUserId: string; targetUser: BangumiUser; // raw data - CONST! targetUserStatsArr: RecordSchema[]; descStatFilterFormGroup: FormGroup; accumulatedMeanFilterFormGroup: FormGroup; scoreVsCountFilterFormGroup: FormGroup; localTranslatedSubjectType; lastUpdateTime: number; private ngUnsubscribe: Subject<void> = new Subject<void>(); constructor( private activatedRoute: ActivatedRoute, private bangumiUserService: BangumiUserService, private banguminUserService: BanguminUserService, private bangumiStatsService: BangumiStatsService, private formBuilder: FormBuilder, private titleService: TitleService, private translateService: TranslateService ) { } ngOnDestroy(): void { // unsubscribe, we can also first() in subscription this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } get PageState() { return PageState; } pieTooltipVariables({data}) { const pieSegmentName = data.name; const pieSegmentValue = data.value; return {pieSegmentName, pieSegmentValue}; } formatDateToSimpleString(addedAt: Date) { return BangumiStatsService.formatDateToSimpleString(addedAt); } getLastUpdateTime() { return this.bangumiStatsService.getLastUpdateTime(this.lastUpdateTime); } /** * Get count of score for a user until a specific pointTime */ getScoringCountUntil(accumulatedMeanData: AccumulatedMeanDataSchema[], lineType: string, pointTime: Date) { return BangumiStatsService.getScoringCountUntil(accumulatedMeanData, lineType, pointTime); } calendarAxisTickFormatting(addedAt: Date) { return BangumiStatsService.formatDateToSimpleString(addedAt); } formatStateData(percentage) { return BangumiStatsService.formatFloatingPoint(percentage); } ngOnInit() { this.activatedRoute.params .subscribe(params => { this.SetClassMemberInitialValue(); this.targetUserId = params['userId']; this.getUserProfile(this.targetUserId); forkJoin([ this.translateService.get('common.category'), this.bangumiStatsService.getUserStats(this.targetUserId).pipe( catchError(error => { if (error && error.status === 404) { this.pageState = PageState.DoesNotExist; } return throwError(error); }) ) ]).subscribe(response => { if (response[0]) { this.localTranslatedSubjectType = response[0]; } if (response[1]) { const res = response[1]; const defaultArr = res.stats as RecordSchema[]; this.lastUpdateTime = res.lastModified; // cache stats array if (_isEmpty(defaultArr)) { // user stats is empty, we don't need to proceed this.targetUserStatsArr = undefined; // reset value this.pageState = PageState.DoesNotExist; return; } this.targetUserStatsArr = res.stats; this.countByTypeDataTranslated = _map(_countBy(defaultArr, 'subjectType'), (val, key) => ({name: this.localTranslatedSubjectType[SubjectType[key]], value: val})); const countByTypeDataRaw = _map(_countBy(defaultArr, 'subjectType'), (val, key) => ({name: SubjectType[key], value: val})); // initialize filter list value this.userCurrentSubjectTypeList = countByTypeDataRaw.map(typeData => typeData['name']); this.collectionStatusList = _uniqBy(defaultArr, 'collectionStatus').map( row => CollectionStatusId[row['collectionStatus']] ); // initialize filter form groups this.descStatFilterFormGroup.get('subjectTypeSelect').setValue(this.userCurrentSubjectTypeList); this.descStatFilterFormGroup.get('stateSelect').setValue(this.collectionStatusList); this.accumulatedMeanFilterFormGroup.get('subjectTypeSelect').setValue(this.userCurrentSubjectTypeList); this.accumulatedMeanFilterFormGroup.get('stateSelect').setValue(this.collectionStatusList); this.scoreVsCountFilterFormGroup.get('subjectTypeSelect').setValue(this.userCurrentSubjectTypeList); this.scoreVsCountFilterFormGroup.get('stateSelect').setValue(this.collectionStatusList); this.initDescStat(); this.initScoreVsCount(); this.initAccumulatedMean(); } }); }); } private initAccumulatedMean() { // initialize the chart with all types const selectedTypeListForAccumulatedMean = this.accumulatedMeanFilterFormGroup.value.subjectTypeSelect; this.refreshAccumulatedMean(this.targetUserStatsArr, selectedTypeListForAccumulatedMean); // edit the chart on change of subjectType selection // use formControl.valueChanges instead of selectionChange since we want to modify the chart minimally, // i.e. instead of re-filtering the whole array with selectedList, only add/remove target subjectType from the chart. this.accumulatedMeanFilterFormGroup.controls['subjectTypeSelect'].valueChanges .pipe( takeUntil(this.ngUnsubscribe) ) .subscribe(newVal => { const oldVal = this.accumulatedMeanFilterFormGroup.value.subjectTypeSelect; const changedSubjectType = (newVal.length > oldVal.length) ? _difference(newVal, oldVal)[0] as string : _difference(oldVal, newVal)[0] as string; // User selects a new value if (newVal.length > oldVal.length) { const currentStateList = this.accumulatedMeanFilterFormGroup.value.stateSelect; const thisTypeArr = this.targetUserStatsArr .filter((stat) => (SubjectType[stat.subjectType] === changedSubjectType && currentStateList.includes(CollectionStatusId[stat.collectionStatus]))); this.calculatedAccumulatedMeanPoints(thisTypeArr, changedSubjectType); } else { // User deselects a value const newArr = this.accumulatedMeanData.filter((row) => { // convert changed type into user's language for comparison return row.name !== this.localTranslatedSubjectType[changedSubjectType]; }); this.accumulatedMeanData = [...newArr]; } }); // edit the chart on change of collection status selection this.accumulatedMeanFilterFormGroup.controls['stateSelect'].valueChanges .pipe( takeUntil(this.ngUnsubscribe) ) .subscribe(newStateList => { const newArr = this.targetUserStatsArr .filter(stat => newStateList.includes(CollectionStatusId[stat.collectionStatus])); this.refreshAccumulatedMean(newArr, this.accumulatedMeanFilterFormGroup.value.subjectTypeSelect); }); } private refreshAccumulatedMean(newAccumulatedMeanData, selectedTypeList) { this.accumulatedMeanData = []; const arr = newAccumulatedMeanData .filter(stat => selectedTypeList.includes(SubjectType[stat.subjectType])); const arrByType = _groupBy(arr, (row) => { return SubjectType[row.subjectType]; }); Object.keys(arrByType).forEach((type) => { this.calculatedAccumulatedMeanPoints(arrByType[type], type); }); } private initScoreVsCount() { const arr = this.filterBySubjectTypeAndState( this.scoreVsCountFilterFormGroup.value.subjectTypeSelect, this.scoreVsCountFilterFormGroup.value.stateSelect ); this.groupAndCountByRate(arr); // edit the chart on change of subjectType selection this.scoreVsCountFilterFormGroup.controls['subjectTypeSelect'].valueChanges .pipe( takeUntil(this.ngUnsubscribe) ) .subscribe(newTypeList => { const newArr = this.filterBySubjectTypeAndState( newTypeList, this.scoreVsCountFilterFormGroup.value.stateSelect ); this.groupAndCountByRate(newArr); }); // edit the chart on change of collection status selection this.scoreVsCountFilterFormGroup.controls['stateSelect'].valueChanges .pipe( takeUntil(this.ngUnsubscribe) ) .subscribe(newStateList => { const newArr = this.filterBySubjectTypeAndState( this.scoreVsCountFilterFormGroup.value.subjectTypeSelect, newStateList ); this.groupAndCountByRate(newArr); }); } private filterBySubjectTypeAndState(subjectTypeList, stateList) { return this.targetUserStatsArr.filter(stat => { return subjectTypeList.includes(SubjectType[stat.subjectType]) && stateList.includes(CollectionStatusId[stat.collectionStatus]); }); } private initDescStat() { const arr = this.filterBySubjectTypeAndState( this.descStatFilterFormGroup.value.subjectTypeSelect, this.descStatFilterFormGroup.value.stateSelect ); this.refreshDescStat(arr); // edit the number cards on change of subjectType selection this.descStatFilterFormGroup.controls['subjectTypeSelect'].valueChanges .pipe( takeUntil(this.ngUnsubscribe) ) .subscribe(newTypeList => { const newArr = this.filterBySubjectTypeAndState( newTypeList, this.descStatFilterFormGroup.value.stateSelect ); this.refreshDescStat(newArr); }); // edit the number cards on change of collection status selection this.descStatFilterFormGroup.controls['stateSelect'].valueChanges .pipe( takeUntil(this.ngUnsubscribe) ) .subscribe(newStateList => { const newArr = this.filterBySubjectTypeAndState( this.descStatFilterFormGroup.value.subjectTypeSelect, newStateList ); this.refreshDescStat(newArr); }); } private groupAndCountByRate(newScoreVsCountData) { this.scoreVsCountData = this.bangumiStatsService.groupAndCountByRate(newScoreVsCountData); } private initStatsFormGroup() { this.descStatFilterFormGroup = this.formBuilder.group( { subjectTypeSelect: [[]], stateSelect: [[]] } ); this.accumulatedMeanFilterFormGroup = this.formBuilder.group( { subjectTypeSelect: [[]], stateSelect: [[]] } ); this.scoreVsCountFilterFormGroup = this.formBuilder.group( { subjectTypeSelect: [[]], stateSelect: [[]] } ); } private calculatedAccumulatedMeanPoints(allRecords: { collectionStatus: number, addDate: number, addedAt: Date, rate: number }[], type: string) { const accumulatedMeanPoints = BangumiStatsService.calculateAccumulatedMean(allRecords); if (!_isEmpty(accumulatedMeanPoints)) { this.accumulatedMeanData = [...this.accumulatedMeanData, {name: this.localTranslatedSubjectType[type], series: accumulatedMeanPoints}]; } } private refreshDescStat(subjectStat: any[]) { this.bangumiStatsService.calculateDescriptiveChartData(subjectStat).subscribe(descStatData => { this.descStatData = descStatData; }); } private SetClassMemberInitialValue() { // TODO: change how these values are reset if user switches to a different profile this.scoreVsCountData = undefined; this.userCurrentSubjectTypeList = undefined; this.collectionStatusList = undefined; this.selectedTypeListForscoreVsCount = undefined; this.accumulatedMeanData = []; this.countByTypeDataTranslated = undefined; this.descStatData = undefined; this.targetUserId = undefined; this.targetUser = undefined; this.targetUserStatsArr = undefined; this.descStatFilterFormGroup = undefined; this.accumulatedMeanFilterFormGroup = undefined; this.scoreVsCountFilterFormGroup = undefined; this.localTranslatedSubjectType = undefined; this.lastUpdateTime = undefined; this.ngUnsubscribe.next(); this.pageState = PageState.InLoading; this.targetUserStatsArr = undefined; // reset value this.selectedTypeListForscoreVsCount = this.userCurrentSubjectTypeList; this.initStatsFormGroup(); } private getUserProfile(userId: string) { this.bangumiUserService.getUserInfoFromHttp(userId) .pipe( catchError(error => { if (error && error.status === 404) { this.pageState = PageState.DoesNotExist; } return throwError(error); }) ) .subscribe(bangumiUser => { this.targetUser = bangumiUser; this.titleService.setTitleByTranslationLabel('statistics.headline', {name: this.targetUser.nickname}); }); } }
the_stack
import { Constants } from '../constants'; import { Scope } from '../scope/scope'; import { Component } from './component'; import { ComponentInstance } from './component.instance'; export class CapivaraInstance { /** * @name capivara.components * @description Armazena os componentes criados */ public scopes; public components; public $watchers; public version; public LAST_SCOPE_ID = 0; public core; public DOMMutation; constructor() { this.DOMMutation = window['MutationObserver'] || window['WebKitMutationObserver'] || window['MozMutationObserver']; this.version = '3.10.1'; this.components = {}; this.scopes = []; this.$watchers = []; if (!Element.prototype.hasOwnProperty('getAttributeStartingWith')) { Object.defineProperty(Element.prototype, 'getAttributeStartingWith', { value: function hasAttributeStartingWith(attr) { return Array.from(this.attributes).filter((attributeNode: any) => { return attributeNode.nodeName.indexOf(attr) === 0; }); }, configurable: true, }); } if (!Element.prototype.hasOwnProperty('hasAttributeStartingWith')) { Object.defineProperty(Element.prototype, 'hasAttributeStartingWith', { value: function hasAttributeStartingWith(attr) { return this.getAttributeStartingWith(attr).length > 0; }, configurable: true, }); } if (document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement['doScroll']) ) { setTimeout(() => { this.createListeners(); this.createComponents(); }); } else { document.addEventListener("DOMContentLoaded", (event) => { this.createListeners(); this.createComponents(); }); } } public createComponents() { Object.keys(this.components).forEach((componentName) => { const elms: any = document.querySelectorAll(componentName) || []; Array.from(elms).forEach((elm) => { this.constroyIfComponent(elm); }); }); } public hasRepeat(elm) { return elm && elm.classList && elm.classList.contains('binding-repeat'); } public constroyIfComponent(addedNode, forceCreated?) { const component = this.components[addedNode.nodeName]; if (component && (forceCreated || !addedNode.created)) { addedNode.created = true; component.createNewInstance(addedNode).create(); } if (addedNode.children && (forceCreated || !this.hasRepeat(addedNode))) { (Array.from(addedNode.children) || []).forEach((child) => { this.constroyIfComponent(child, forceCreated); }); } } public destroyIfComponent(removedNode) { removedNode.created = false; if (removedNode['$instance'] && !removedNode['$instance'].destroyed) { removedNode['$instance'].destroy(); } if (removedNode.children) { (Array.from(removedNode.children) || []).forEach((child) => this.destroyIfComponent(child)); } } public onMutation(mutations) { (mutations || []).forEach((mutation) => { if (mutation.type === 'childList') { ((mutation && mutation.addedNodes && mutation.addedNodes.forEach) ? mutation.addedNodes : []).forEach((addedNode) => { this.constroyIfComponent(addedNode); }); ((mutation && mutation.removedNodes && mutation.removedNodes.forEach) ? mutation.removedNodes : []).forEach((removedNode) => { this.destroyIfComponent(removedNode); }); } }); } public createListeners() { if (this.DOMMutation) { const observer = new this.DOMMutation((mutations) => this.onMutation(mutations)); observer.observe(document.body, { attributes: false, childList: true, subtree: true, characterData: false, }); } } /** * @name capivara.component * @description Registra um novo componente capivara */ public component(componentName, config) { if (window["capivara"].components[componentName]) { console.error("A registered component with this name already exists."); return; } window["capivara"].components[componentName.toUpperCase()] = new Component(componentName, config); } /** * @name capivara.componentBuilder * @description Faz a inicialização de um componente. */ public componentBuilder(hashName) { return new Promise((resp) => { let elms = window["capivara"].isElement(hashName) ? [hashName] : Array.from(document.querySelectorAll("[\\#" + hashName + "]")); if (elms.length === 0) { console.error("CapivaraJS did not find its component with the hash " + hashName); } let instance; const findElementAndCreateInstance = () => { elms = window["capivara"].isElement(hashName) ? [hashName] : Array.from(document.querySelectorAll("[\\#" + hashName + "]")); (elms || []).forEach((elm) => { const component = window["capivara"].components[elm.nodeName]; if (!component) { console.error("We did not find a registered entry under the name: " + elm.nodeName); return; } if (!instance) { instance = elm['$instance']; } }); return instance; }; setTimeout(() => { const componentInstance = findElementAndCreateInstance(); resp(componentInstance); }); }); } /** * @name capivara.controller * @description Cria um novo controller para fazer manipulação de um determinado elemento. */ public controller(elm, callback) { new ComponentInstance(elm, { controller: callback }).create(); } /** * @name capivara,isArray * @description Verifica se um valor é um Array. */ public isArray(value) { return Array.isArray(value) || value instanceof Array; } /** * @name capivara,isObject * @description Verifica se um valor é um Objeto. */ public isObject(value) { return value !== null && typeof value === "object"; } public isObjectConstructor(obj) { if (!obj) { return false; } return obj.__proto__.constructor.name === 'Object'; } /** * @name capivara,isDate * @description Verifica se um valor é uma Data. */ public isDate(value) { return toString.call(value) === "[object Date]"; } /** * @name capivara,isElement * @description Verifica se um valor é um NodeElement. */ public isElement(value) { return !!(value && (value.nodeName // We are a direct element. || (value.prop && value.attr && value.find))); } /** * @name capivara,isFunction * @description Verifica se um valor é uma função. */ public isFunction(value) { return typeof value === "function"; } /** * @name capivara,isNumber * @description Verifica se um valor é um número. */ public isNumber(value) { return typeof value === "number"; } /** * @name capivara,isString * @description Verifica se um valor é uma string. */ public isString(value) { return typeof value === "string"; } /** * @name capivara,merge * @description Faz a junção de objetos em um único objeto. */ public merge(...args) { return (Object.assign as any)(...args); } /** * @name capivara,copy * @description Faz a copia de um objeto para que seja criada a referência. */ public copy(value) { return Object.assign(value); } /** * @name capivara,replaceAll * @description Faz a devida alteração em todas as ocorrências */ public replaceAll(str, needle, replacement) { return str.split(needle).join(replacement); } /** * @name capivara.constants * @description Modifica o nome das diretivas que são criadas pelo capivara. */ public constants(obj) { Object.keys(obj).forEach((key) => { if (Constants[key]) { Constants[key] = obj[key]; } }); } public $on(evtName, callback) { window["capivara"].$watchers.push({ evtName, callback }); } public $emit(evtName, ...args) { window["capivara"] .$watchers .filter((watcher) => watcher.evtName === evtName) .forEach((watcher) => { watcher.callback(...args); }); } public simpleCompare(a, b) { return a === b || (a !== a && b !== b); } public isRegExp(value) { return toString.call(value) === '[object RegExp]'; } public isDefined(value) { return typeof value !== 'undefined'; } public isWindow(value) { return value && value.window === value; } public isScope(value) { return value instanceof Scope; } public equals(o1, o2) { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if (o1 !== o1 && o2 !== o2) { return true; } /* tslint:disable */ let t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 === t2 && t1 === 'object') { if (this.isArray(o1)) { if (!this.isArray(o2)) { return false }; if ((length = o1.length) === o2.length) { for (key = 0; key < length; key++) { if (!this.equals(o1[key], o2[key])) return false; } return true; } } else if (this.isDate(o1)) { if (!this.isDate(o2)) return false; return this.simpleCompare(o1.getTime(), o2.getTime()); } else if (this.isRegExp(o1)) { if (!this.isRegExp(o2)) return false; return o1.toString() === o2.toString(); } else { if (this.isScope(o1) || this.isScope(o2) || this.isWindow(o1) || this.isWindow(o2) || this.isArray(o2) || this.isDate(o2) || this.isRegExp(o2)) return false; keySet = Object.create(null); for (key in o1) { if (key.charAt(0) === '$' || this.isFunction(o1[key])) continue; if (!this.equals(o1[key], o2[key])) return false; keySet[key] = true; } for (key in o2) { if (!(key in keySet) && key.charAt(0) !== '$' && this.isDefined(o2[key]) && !this.isFunction(o2[key])) return false; } return true; } } return false; } }
the_stack
import Long from "long"; import _m0 from "protobufjs/minimal"; import { Timestamp } from "../google/protobuf/timestamp"; import { Notification, ChannelMessage, Rpc } from "../api/api"; import { BoolValue, Int32Value, StringValue, } from "../google/protobuf/wrappers"; export const protobufPackage = "nakama.realtime"; /** The realtime protocol for Nakama server. */ /** An envelope for a realtime message. */ export interface Envelope { cid: string; message?: | { $case: "channel"; channel: Channel } | { $case: "channel_join"; channel_join: ChannelJoin } | { $case: "channel_leave"; channel_leave: ChannelLeave } | { $case: "channel_message"; channel_message: ChannelMessage } | { $case: "channel_message_ack"; channel_message_ack: ChannelMessageAck } | { $case: "channel_message_send"; channel_message_send: ChannelMessageSend; } | { $case: "channel_message_update"; channel_message_update: ChannelMessageUpdate; } | { $case: "channel_message_remove"; channel_message_remove: ChannelMessageRemove; } | { $case: "channel_presence_event"; channel_presence_event: ChannelPresenceEvent; } | { $case: "error"; error: Error } | { $case: "match"; match: Match } | { $case: "match_create"; match_create: MatchCreate } | { $case: "match_data"; match_data: MatchData } | { $case: "match_data_send"; match_data_send: MatchDataSend } | { $case: "match_join"; match_join: MatchJoin } | { $case: "match_leave"; match_leave: MatchLeave } | { $case: "match_presence_event"; match_presence_event: MatchPresenceEvent; } | { $case: "matchmaker_add"; matchmaker_add: MatchmakerAdd } | { $case: "matchmaker_matched"; matchmaker_matched: MatchmakerMatched } | { $case: "matchmaker_remove"; matchmaker_remove: MatchmakerRemove } | { $case: "matchmaker_ticket"; matchmaker_ticket: MatchmakerTicket } | { $case: "notifications"; notifications: Notifications } | { $case: "rpc"; rpc: Rpc } | { $case: "status"; status: Status } | { $case: "status_follow"; status_follow: StatusFollow } | { $case: "status_presence_event"; status_presence_event: StatusPresenceEvent; } | { $case: "status_unfollow"; status_unfollow: StatusUnfollow } | { $case: "status_update"; status_update: StatusUpdate } | { $case: "stream_data"; stream_data: StreamData } | { $case: "stream_presence_event"; stream_presence_event: StreamPresenceEvent; } | { $case: "ping"; ping: Ping } | { $case: "pong"; pong: Pong } | { $case: "party"; party: Party } | { $case: "party_create"; party_create: PartyCreate } | { $case: "party_join"; party_join: PartyJoin } | { $case: "party_leave"; party_leave: PartyLeave } | { $case: "party_promote"; party_promote: PartyPromote } | { $case: "party_leader"; party_leader: PartyLeader } | { $case: "party_accept"; party_accept: PartyAccept } | { $case: "party_remove"; party_remove: PartyRemove } | { $case: "party_close"; party_close: PartyClose } | { $case: "party_join_request_list"; party_join_request_list: PartyJoinRequestList; } | { $case: "party_join_request"; party_join_request: PartyJoinRequest } | { $case: "party_matchmaker_add"; party_matchmaker_add: PartyMatchmakerAdd; } | { $case: "party_matchmaker_remove"; party_matchmaker_remove: PartyMatchmakerRemove; } | { $case: "party_matchmaker_ticket"; party_matchmaker_ticket: PartyMatchmakerTicket; } | { $case: "party_data"; party_data: PartyData } | { $case: "party_data_send"; party_data_send: PartyDataSend } | { $case: "party_presence_event"; party_presence_event: PartyPresenceEvent; }; } /** A realtime chat channel. */ export interface Channel { /** The ID of the channel. */ id: string; /** The users currently in the channel. */ presences: UserPresence[]; /** A reference to the current user's presence in the channel. */ self?: UserPresence; /** 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; } /** Join operation for a realtime chat channel. */ export interface ChannelJoin { /** The user ID to DM with, group ID to chat with, or room channel name to join. */ target: string; /** The type of the chat channel. */ type: number; /** Whether messages sent on this channel should be persistent. */ persistence?: boolean; /** Whether the user should appear in the channel's presence list and events. */ hidden?: boolean; } /** The type of chat channel. */ export enum ChannelJoin_Type { /** TYPE_UNSPECIFIED - Default case. Assumed as ROOM type. */ TYPE_UNSPECIFIED = 0, /** ROOM - A room which anyone can join to chat. */ ROOM = 1, /** DIRECT_MESSAGE - A private channel for 1-on-1 chat. */ DIRECT_MESSAGE = 2, /** GROUP - A channel for group chat. */ GROUP = 3, UNRECOGNIZED = -1, } export function channelJoin_TypeFromJSON(object: any): ChannelJoin_Type { switch (object) { case 0: case "TYPE_UNSPECIFIED": return ChannelJoin_Type.TYPE_UNSPECIFIED; case 1: case "ROOM": return ChannelJoin_Type.ROOM; case 2: case "DIRECT_MESSAGE": return ChannelJoin_Type.DIRECT_MESSAGE; case 3: case "GROUP": return ChannelJoin_Type.GROUP; case -1: case "UNRECOGNIZED": default: return ChannelJoin_Type.UNRECOGNIZED; } } export function channelJoin_TypeToJSON(object: ChannelJoin_Type): string { switch (object) { case ChannelJoin_Type.TYPE_UNSPECIFIED: return "TYPE_UNSPECIFIED"; case ChannelJoin_Type.ROOM: return "ROOM"; case ChannelJoin_Type.DIRECT_MESSAGE: return "DIRECT_MESSAGE"; case ChannelJoin_Type.GROUP: return "GROUP"; default: return "UNKNOWN"; } } /** Leave a realtime channel. */ export interface ChannelLeave { /** The ID of the channel to leave. */ channel_id: string; } /** A receipt reply from a channel message send operation. */ export interface ChannelMessageAck { /** The channel the message was sent to. */ channel_id: string; /** The unique ID assigned to the message. */ message_id: string; /** The code representing a message type or category. */ code?: number; /** Username of the message sender. */ username: 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; } /** Send a message to a realtime channel. */ export interface ChannelMessageSend { /** The channel to sent to. */ channel_id: string; /** Message content. */ content: string; } /** Update a message previously sent to a realtime channel. */ export interface ChannelMessageUpdate { /** The channel the message was sent to. */ channel_id: string; /** The ID assigned to the message to update. */ message_id: string; /** New message content. */ content: string; } /** Remove a message previously sent to a realtime channel. */ export interface ChannelMessageRemove { /** The channel the message was sent to. */ channel_id: string; /** The ID assigned to the message to update. */ message_id: string; } /** A set of joins and leaves on a particular channel. */ export interface ChannelPresenceEvent { /** The channel identifier this event is for. */ channel_id: string; /** Presences joining the channel as part of this event, if any. */ joins: UserPresence[]; /** Presences leaving the channel as part of this event, if any. */ leaves: UserPresence[]; /** 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 logical error which may occur on the server. */ export interface Error { /** The error code which should be one of "Error.Code" enums. */ code: number; /** A message in English to help developers debug the response. */ message: string; /** Additional error details which may be different for each response. */ context: { [key: string]: string }; } /** The selection of possible error codes. */ export enum Error_Code { /** RUNTIME_EXCEPTION - An unexpected result from the server. */ RUNTIME_EXCEPTION = 0, /** UNRECOGNIZED_PAYLOAD - The server received a message which is not recognised. */ UNRECOGNIZED_PAYLOAD = 1, /** MISSING_PAYLOAD - A message was expected but contains no content. */ MISSING_PAYLOAD = 2, /** BAD_INPUT - Fields in the message have an invalid format. */ BAD_INPUT = 3, /** MATCH_NOT_FOUND - The match id was not found. */ MATCH_NOT_FOUND = 4, /** MATCH_JOIN_REJECTED - The match join was rejected. */ MATCH_JOIN_REJECTED = 5, /** RUNTIME_FUNCTION_NOT_FOUND - The runtime function does not exist on the server. */ RUNTIME_FUNCTION_NOT_FOUND = 6, /** RUNTIME_FUNCTION_EXCEPTION - The runtime function executed with an error. */ RUNTIME_FUNCTION_EXCEPTION = 7, UNRECOGNIZED = -1, } export function error_CodeFromJSON(object: any): Error_Code { switch (object) { case 0: case "RUNTIME_EXCEPTION": return Error_Code.RUNTIME_EXCEPTION; case 1: case "UNRECOGNIZED_PAYLOAD": return Error_Code.UNRECOGNIZED_PAYLOAD; case 2: case "MISSING_PAYLOAD": return Error_Code.MISSING_PAYLOAD; case 3: case "BAD_INPUT": return Error_Code.BAD_INPUT; case 4: case "MATCH_NOT_FOUND": return Error_Code.MATCH_NOT_FOUND; case 5: case "MATCH_JOIN_REJECTED": return Error_Code.MATCH_JOIN_REJECTED; case 6: case "RUNTIME_FUNCTION_NOT_FOUND": return Error_Code.RUNTIME_FUNCTION_NOT_FOUND; case 7: case "RUNTIME_FUNCTION_EXCEPTION": return Error_Code.RUNTIME_FUNCTION_EXCEPTION; case -1: case "UNRECOGNIZED": default: return Error_Code.UNRECOGNIZED; } } export function error_CodeToJSON(object: Error_Code): string { switch (object) { case Error_Code.RUNTIME_EXCEPTION: return "RUNTIME_EXCEPTION"; case Error_Code.UNRECOGNIZED_PAYLOAD: return "UNRECOGNIZED_PAYLOAD"; case Error_Code.MISSING_PAYLOAD: return "MISSING_PAYLOAD"; case Error_Code.BAD_INPUT: return "BAD_INPUT"; case Error_Code.MATCH_NOT_FOUND: return "MATCH_NOT_FOUND"; case Error_Code.MATCH_JOIN_REJECTED: return "MATCH_JOIN_REJECTED"; case Error_Code.RUNTIME_FUNCTION_NOT_FOUND: return "RUNTIME_FUNCTION_NOT_FOUND"; case Error_Code.RUNTIME_FUNCTION_EXCEPTION: return "RUNTIME_FUNCTION_EXCEPTION"; default: return "UNKNOWN"; } } export interface Error_ContextEntry { key: string; value: string; } /** A realtime match. */ export interface Match { /** The match unique ID. */ match_id: string; /** True if it's an server-managed authoritative match, false otherwise. */ authoritative: boolean; /** Match label, if any. */ label?: string; /** The number of users currently in the match. */ size: number; /** The users currently in the match. */ presences: UserPresence[]; /** A reference to the current user's presence in the match. */ self?: UserPresence; } /** Create a new realtime match. */ export interface MatchCreate {} /** Realtime match data received from the server. */ export interface MatchData { /** The match unique ID. */ match_id: string; /** A reference to the user presence that sent this data, if any. */ presence?: UserPresence; /** Op code value. */ op_code: number; /** Data payload, if any. */ data: Uint8Array; /** True if this data was delivered reliably, false otherwise. */ reliable: boolean; } /** Send realtime match data to the server. */ export interface MatchDataSend { /** The match unique ID. */ match_id: string; /** Op code value. */ op_code: number; /** Data payload, if any. */ data: Uint8Array; /** List of presences in the match to deliver to, if filtering is required. Otherwise deliver to everyone in the match. */ presences: UserPresence[]; /** True if the data should be sent reliably, false otherwise. */ reliable: boolean; } /** Join an existing realtime match. */ export interface MatchJoin { id?: | { $case: "match_id"; match_id: string } | { $case: "token"; token: string }; /** An optional set of key-value metadata pairs to be passed to the match handler, if any. */ metadata: { [key: string]: string }; } export interface MatchJoin_MetadataEntry { key: string; value: string; } /** Leave a realtime match. */ export interface MatchLeave { /** The match unique ID. */ match_id: string; } /** A set of joins and leaves on a particular realtime match. */ export interface MatchPresenceEvent { /** The match unique ID. */ match_id: string; /** User presences that have just joined the match. */ joins: UserPresence[]; /** User presences that have just left the match. */ leaves: UserPresence[]; } /** Start a new matchmaking process. */ export interface MatchmakerAdd { /** Minimum total user count to match together. */ min_count: number; /** Maximum total user count to match together. */ max_count: number; /** Filter query used to identify suitable users. */ query: string; /** String properties. */ string_properties: { [key: string]: string }; /** Numeric properties. */ numeric_properties: { [key: string]: number }; } export interface MatchmakerAdd_StringPropertiesEntry { key: string; value: string; } export interface MatchmakerAdd_NumericPropertiesEntry { key: string; value: number; } /** A successful matchmaking result. */ export interface MatchmakerMatched { /** The matchmaking ticket that has completed. */ ticket: string; id?: | { $case: "match_id"; match_id: string } | { $case: "token"; token: string }; /** The users that have been matched together, and information about their matchmaking data. */ users: MatchmakerMatched_MatchmakerUser[]; /** A reference to the current user and their properties. */ self?: MatchmakerMatched_MatchmakerUser; } export interface MatchmakerMatched_MatchmakerUser { /** User info. */ presence?: UserPresence; /** Party identifier, if this user was matched as a party member. */ party_id: string; /** String properties. */ string_properties: { [key: string]: string }; /** Numeric properties. */ numeric_properties: { [key: string]: number }; } export interface MatchmakerMatched_MatchmakerUser_StringPropertiesEntry { key: string; value: string; } export interface MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry { key: string; value: number; } /** Cancel an existing ongoing matchmaking process. */ export interface MatchmakerRemove { /** The ticket to cancel. */ ticket: string; } /** A ticket representing a new matchmaking process. */ export interface MatchmakerTicket { /** The ticket that can be used to cancel matchmaking. */ ticket: string; } /** A collection of zero or more notifications. */ export interface Notifications { /** Collection of notifications. */ notifications: Notification[]; } /** Incoming information about a party. */ export interface Party { /** Unique party identifier. */ party_id: string; /** Open flag. */ open: boolean; /** Maximum number of party members. */ max_size: number; /** Self. */ self?: UserPresence; /** Leader. */ leader?: UserPresence; /** All current party members. */ presences: UserPresence[]; } /** Create a party. */ export interface PartyCreate { /** Whether or not the party will require join requests to be approved by the party leader. */ open: boolean; /** Maximum number of party members. */ max_size: number; } /** Join a party, or request to join if the party is not open. */ export interface PartyJoin { /** Party ID to join. */ party_id: string; } /** Leave a party. */ export interface PartyLeave { /** Party ID to leave. */ party_id: string; } /** Promote a new party leader. */ export interface PartyPromote { /** Party ID to promote a new leader for. */ party_id: string; /** The presence of an existing party member to promote as the new leader. */ presence?: UserPresence; } /** Announcement of a new party leader. */ export interface PartyLeader { /** Party ID to announce the new leader for. */ party_id: string; /** The presence of the new party leader. */ presence?: UserPresence; } /** Accept a request to join. */ export interface PartyAccept { /** Party ID to accept a join request for. */ party_id: string; /** The presence to accept as a party member. */ presence?: UserPresence; } /** Kick a party member, or decline a request to join. */ export interface PartyRemove { /** Party ID to remove/reject from. */ party_id: string; /** The presence to remove or reject. */ presence?: UserPresence; } /** End a party, kicking all party members and closing it. */ export interface PartyClose { /** Party ID to close. */ party_id: string; } /** Request a list of pending join requests for a party. */ export interface PartyJoinRequestList { /** Party ID to get a list of join requests for. */ party_id: string; } /** Incoming notification for one or more new presences attempting to join the party. */ export interface PartyJoinRequest { /** Party ID these presences are attempting to join. */ party_id: string; /** Presences attempting to join. */ presences: UserPresence[]; } /** Begin matchmaking as a party. */ export interface PartyMatchmakerAdd { /** Party ID. */ party_id: string; /** Minimum total user count to match together. */ min_count: number; /** Maximum total user count to match together. */ max_count: number; /** Filter query used to identify suitable users. */ query: string; /** String properties. */ string_properties: { [key: string]: string }; /** Numeric properties. */ numeric_properties: { [key: string]: number }; } export interface PartyMatchmakerAdd_StringPropertiesEntry { key: string; value: string; } export interface PartyMatchmakerAdd_NumericPropertiesEntry { key: string; value: number; } /** Cancel a party matchmaking process using a ticket. */ export interface PartyMatchmakerRemove { /** Party ID. */ party_id: string; /** The ticket to cancel. */ ticket: string; } /** A response from starting a new party matchmaking process. */ export interface PartyMatchmakerTicket { /** Party ID. */ party_id: string; /** The ticket that can be used to cancel matchmaking. */ ticket: string; } /** Incoming party data delivered from the server. */ export interface PartyData { /** The party ID. */ party_id: string; /** A reference to the user presence that sent this data, if any. */ presence?: UserPresence; /** Op code value. */ op_code: number; /** Data payload, if any. */ data: Uint8Array; } /** Send data to a party. */ export interface PartyDataSend { /** Party ID to send to. */ party_id: string; /** Op code value. */ op_code: number; /** Data payload, if any. */ data: Uint8Array; } /** Presence update for a particular party. */ export interface PartyPresenceEvent { /** The party ID. */ party_id: string; /** User presences that have just joined the party. */ joins: UserPresence[]; /** User presences that have just left the party. */ leaves: UserPresence[]; } /** Application-level heartbeat and connection check. */ export interface Ping {} /** Application-level heartbeat and connection check response. */ export interface Pong {} /** A snapshot of statuses for some set of users. */ export interface Status { /** User statuses. */ presences: UserPresence[]; } /** Start receiving status updates for some set of users. */ export interface StatusFollow { /** User IDs to follow. */ user_ids: string[]; /** Usernames to follow. */ usernames: string[]; } /** A batch of status updates for a given user. */ export interface StatusPresenceEvent { /** New statuses for the user. */ joins: UserPresence[]; /** Previous statuses for the user. */ leaves: UserPresence[]; } /** Stop receiving status updates for some set of users. */ export interface StatusUnfollow { /** Users to unfollow. */ user_ids: string[]; } /** Set the user's own status. */ export interface StatusUpdate { /** Status string to set, if not present the user will appear offline. */ status?: string; } /** Represents identifying information for a stream. */ export interface Stream { /** Mode identifies the type of stream. */ mode: number; /** Subject is the primary identifier, if any. */ subject: string; /** Subcontext is a secondary identifier, if any. */ subcontext: string; /** The label is an arbitrary identifying string, if the stream has one. */ label: string; } /** A data message delivered over a stream. */ export interface StreamData { /** The stream this data message relates to. */ stream?: Stream; /** The sender, if any. */ sender?: UserPresence; /** Arbitrary contents of the data message. */ data: string; /** True if this data was delivered reliably, false otherwise. */ reliable: boolean; } /** A set of joins and leaves on a particular stream. */ export interface StreamPresenceEvent { /** The stream this event relates to. */ stream?: Stream; /** Presences joining the stream as part of this event, if any. */ joins: UserPresence[]; /** Presences leaving the stream as part of this event, if any. */ leaves: UserPresence[]; } /** A user session associated to a stream, usually through a list operation or a join/leave event. */ export interface UserPresence { /** The user this presence belongs to. */ user_id: string; /** A unique session ID identifying the particular connection, because the user may have many. */ session_id: string; /** The username for display purposes. */ username: string; /** Whether this presence generates persistent data/messages, if applicable for the stream type. */ persistence: boolean; /** A user-set status message for this stream, if applicable. */ status?: string; } const baseEnvelope: object = { cid: "" }; export const Envelope = { encode( message: Envelope, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.cid !== "") { writer.uint32(10).string(message.cid); } if (message.message?.$case === "channel") { Channel.encode( message.message.channel, writer.uint32(18).fork() ).ldelim(); } if (message.message?.$case === "channel_join") { ChannelJoin.encode( message.message.channel_join, writer.uint32(26).fork() ).ldelim(); } if (message.message?.$case === "channel_leave") { ChannelLeave.encode( message.message.channel_leave, writer.uint32(34).fork() ).ldelim(); } if (message.message?.$case === "channel_message") { ChannelMessage.encode( message.message.channel_message, writer.uint32(42).fork() ).ldelim(); } if (message.message?.$case === "channel_message_ack") { ChannelMessageAck.encode( message.message.channel_message_ack, writer.uint32(50).fork() ).ldelim(); } if (message.message?.$case === "channel_message_send") { ChannelMessageSend.encode( message.message.channel_message_send, writer.uint32(58).fork() ).ldelim(); } if (message.message?.$case === "channel_message_update") { ChannelMessageUpdate.encode( message.message.channel_message_update, writer.uint32(66).fork() ).ldelim(); } if (message.message?.$case === "channel_message_remove") { ChannelMessageRemove.encode( message.message.channel_message_remove, writer.uint32(74).fork() ).ldelim(); } if (message.message?.$case === "channel_presence_event") { ChannelPresenceEvent.encode( message.message.channel_presence_event, writer.uint32(82).fork() ).ldelim(); } if (message.message?.$case === "error") { Error.encode(message.message.error, writer.uint32(90).fork()).ldelim(); } if (message.message?.$case === "match") { Match.encode(message.message.match, writer.uint32(98).fork()).ldelim(); } if (message.message?.$case === "match_create") { MatchCreate.encode( message.message.match_create, writer.uint32(106).fork() ).ldelim(); } if (message.message?.$case === "match_data") { MatchData.encode( message.message.match_data, writer.uint32(114).fork() ).ldelim(); } if (message.message?.$case === "match_data_send") { MatchDataSend.encode( message.message.match_data_send, writer.uint32(122).fork() ).ldelim(); } if (message.message?.$case === "match_join") { MatchJoin.encode( message.message.match_join, writer.uint32(130).fork() ).ldelim(); } if (message.message?.$case === "match_leave") { MatchLeave.encode( message.message.match_leave, writer.uint32(138).fork() ).ldelim(); } if (message.message?.$case === "match_presence_event") { MatchPresenceEvent.encode( message.message.match_presence_event, writer.uint32(146).fork() ).ldelim(); } if (message.message?.$case === "matchmaker_add") { MatchmakerAdd.encode( message.message.matchmaker_add, writer.uint32(154).fork() ).ldelim(); } if (message.message?.$case === "matchmaker_matched") { MatchmakerMatched.encode( message.message.matchmaker_matched, writer.uint32(162).fork() ).ldelim(); } if (message.message?.$case === "matchmaker_remove") { MatchmakerRemove.encode( message.message.matchmaker_remove, writer.uint32(170).fork() ).ldelim(); } if (message.message?.$case === "matchmaker_ticket") { MatchmakerTicket.encode( message.message.matchmaker_ticket, writer.uint32(178).fork() ).ldelim(); } if (message.message?.$case === "notifications") { Notifications.encode( message.message.notifications, writer.uint32(186).fork() ).ldelim(); } if (message.message?.$case === "rpc") { Rpc.encode(message.message.rpc, writer.uint32(194).fork()).ldelim(); } if (message.message?.$case === "status") { Status.encode(message.message.status, writer.uint32(202).fork()).ldelim(); } if (message.message?.$case === "status_follow") { StatusFollow.encode( message.message.status_follow, writer.uint32(210).fork() ).ldelim(); } if (message.message?.$case === "status_presence_event") { StatusPresenceEvent.encode( message.message.status_presence_event, writer.uint32(218).fork() ).ldelim(); } if (message.message?.$case === "status_unfollow") { StatusUnfollow.encode( message.message.status_unfollow, writer.uint32(226).fork() ).ldelim(); } if (message.message?.$case === "status_update") { StatusUpdate.encode( message.message.status_update, writer.uint32(234).fork() ).ldelim(); } if (message.message?.$case === "stream_data") { StreamData.encode( message.message.stream_data, writer.uint32(242).fork() ).ldelim(); } if (message.message?.$case === "stream_presence_event") { StreamPresenceEvent.encode( message.message.stream_presence_event, writer.uint32(250).fork() ).ldelim(); } if (message.message?.$case === "ping") { Ping.encode(message.message.ping, writer.uint32(258).fork()).ldelim(); } if (message.message?.$case === "pong") { Pong.encode(message.message.pong, writer.uint32(266).fork()).ldelim(); } if (message.message?.$case === "party") { Party.encode(message.message.party, writer.uint32(274).fork()).ldelim(); } if (message.message?.$case === "party_create") { PartyCreate.encode( message.message.party_create, writer.uint32(282).fork() ).ldelim(); } if (message.message?.$case === "party_join") { PartyJoin.encode( message.message.party_join, writer.uint32(290).fork() ).ldelim(); } if (message.message?.$case === "party_leave") { PartyLeave.encode( message.message.party_leave, writer.uint32(298).fork() ).ldelim(); } if (message.message?.$case === "party_promote") { PartyPromote.encode( message.message.party_promote, writer.uint32(306).fork() ).ldelim(); } if (message.message?.$case === "party_leader") { PartyLeader.encode( message.message.party_leader, writer.uint32(314).fork() ).ldelim(); } if (message.message?.$case === "party_accept") { PartyAccept.encode( message.message.party_accept, writer.uint32(322).fork() ).ldelim(); } if (message.message?.$case === "party_remove") { PartyRemove.encode( message.message.party_remove, writer.uint32(330).fork() ).ldelim(); } if (message.message?.$case === "party_close") { PartyClose.encode( message.message.party_close, writer.uint32(338).fork() ).ldelim(); } if (message.message?.$case === "party_join_request_list") { PartyJoinRequestList.encode( message.message.party_join_request_list, writer.uint32(346).fork() ).ldelim(); } if (message.message?.$case === "party_join_request") { PartyJoinRequest.encode( message.message.party_join_request, writer.uint32(354).fork() ).ldelim(); } if (message.message?.$case === "party_matchmaker_add") { PartyMatchmakerAdd.encode( message.message.party_matchmaker_add, writer.uint32(362).fork() ).ldelim(); } if (message.message?.$case === "party_matchmaker_remove") { PartyMatchmakerRemove.encode( message.message.party_matchmaker_remove, writer.uint32(370).fork() ).ldelim(); } if (message.message?.$case === "party_matchmaker_ticket") { PartyMatchmakerTicket.encode( message.message.party_matchmaker_ticket, writer.uint32(378).fork() ).ldelim(); } if (message.message?.$case === "party_data") { PartyData.encode( message.message.party_data, writer.uint32(386).fork() ).ldelim(); } if (message.message?.$case === "party_data_send") { PartyDataSend.encode( message.message.party_data_send, writer.uint32(394).fork() ).ldelim(); } if (message.message?.$case === "party_presence_event") { PartyPresenceEvent.encode( message.message.party_presence_event, writer.uint32(402).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Envelope { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseEnvelope } as Envelope; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.cid = reader.string(); break; case 2: message.message = { $case: "channel", channel: Channel.decode(reader, reader.uint32()), }; break; case 3: message.message = { $case: "channel_join", channel_join: ChannelJoin.decode(reader, reader.uint32()), }; break; case 4: message.message = { $case: "channel_leave", channel_leave: ChannelLeave.decode(reader, reader.uint32()), }; break; case 5: message.message = { $case: "channel_message", channel_message: ChannelMessage.decode(reader, reader.uint32()), }; break; case 6: message.message = { $case: "channel_message_ack", channel_message_ack: ChannelMessageAck.decode( reader, reader.uint32() ), }; break; case 7: message.message = { $case: "channel_message_send", channel_message_send: ChannelMessageSend.decode( reader, reader.uint32() ), }; break; case 8: message.message = { $case: "channel_message_update", channel_message_update: ChannelMessageUpdate.decode( reader, reader.uint32() ), }; break; case 9: message.message = { $case: "channel_message_remove", channel_message_remove: ChannelMessageRemove.decode( reader, reader.uint32() ), }; break; case 10: message.message = { $case: "channel_presence_event", channel_presence_event: ChannelPresenceEvent.decode( reader, reader.uint32() ), }; break; case 11: message.message = { $case: "error", error: Error.decode(reader, reader.uint32()), }; break; case 12: message.message = { $case: "match", match: Match.decode(reader, reader.uint32()), }; break; case 13: message.message = { $case: "match_create", match_create: MatchCreate.decode(reader, reader.uint32()), }; break; case 14: message.message = { $case: "match_data", match_data: MatchData.decode(reader, reader.uint32()), }; break; case 15: message.message = { $case: "match_data_send", match_data_send: MatchDataSend.decode(reader, reader.uint32()), }; break; case 16: message.message = { $case: "match_join", match_join: MatchJoin.decode(reader, reader.uint32()), }; break; case 17: message.message = { $case: "match_leave", match_leave: MatchLeave.decode(reader, reader.uint32()), }; break; case 18: message.message = { $case: "match_presence_event", match_presence_event: MatchPresenceEvent.decode( reader, reader.uint32() ), }; break; case 19: message.message = { $case: "matchmaker_add", matchmaker_add: MatchmakerAdd.decode(reader, reader.uint32()), }; break; case 20: message.message = { $case: "matchmaker_matched", matchmaker_matched: MatchmakerMatched.decode( reader, reader.uint32() ), }; break; case 21: message.message = { $case: "matchmaker_remove", matchmaker_remove: MatchmakerRemove.decode(reader, reader.uint32()), }; break; case 22: message.message = { $case: "matchmaker_ticket", matchmaker_ticket: MatchmakerTicket.decode(reader, reader.uint32()), }; break; case 23: message.message = { $case: "notifications", notifications: Notifications.decode(reader, reader.uint32()), }; break; case 24: message.message = { $case: "rpc", rpc: Rpc.decode(reader, reader.uint32()), }; break; case 25: message.message = { $case: "status", status: Status.decode(reader, reader.uint32()), }; break; case 26: message.message = { $case: "status_follow", status_follow: StatusFollow.decode(reader, reader.uint32()), }; break; case 27: message.message = { $case: "status_presence_event", status_presence_event: StatusPresenceEvent.decode( reader, reader.uint32() ), }; break; case 28: message.message = { $case: "status_unfollow", status_unfollow: StatusUnfollow.decode(reader, reader.uint32()), }; break; case 29: message.message = { $case: "status_update", status_update: StatusUpdate.decode(reader, reader.uint32()), }; break; case 30: message.message = { $case: "stream_data", stream_data: StreamData.decode(reader, reader.uint32()), }; break; case 31: message.message = { $case: "stream_presence_event", stream_presence_event: StreamPresenceEvent.decode( reader, reader.uint32() ), }; break; case 32: message.message = { $case: "ping", ping: Ping.decode(reader, reader.uint32()), }; break; case 33: message.message = { $case: "pong", pong: Pong.decode(reader, reader.uint32()), }; break; case 34: message.message = { $case: "party", party: Party.decode(reader, reader.uint32()), }; break; case 35: message.message = { $case: "party_create", party_create: PartyCreate.decode(reader, reader.uint32()), }; break; case 36: message.message = { $case: "party_join", party_join: PartyJoin.decode(reader, reader.uint32()), }; break; case 37: message.message = { $case: "party_leave", party_leave: PartyLeave.decode(reader, reader.uint32()), }; break; case 38: message.message = { $case: "party_promote", party_promote: PartyPromote.decode(reader, reader.uint32()), }; break; case 39: message.message = { $case: "party_leader", party_leader: PartyLeader.decode(reader, reader.uint32()), }; break; case 40: message.message = { $case: "party_accept", party_accept: PartyAccept.decode(reader, reader.uint32()), }; break; case 41: message.message = { $case: "party_remove", party_remove: PartyRemove.decode(reader, reader.uint32()), }; break; case 42: message.message = { $case: "party_close", party_close: PartyClose.decode(reader, reader.uint32()), }; break; case 43: message.message = { $case: "party_join_request_list", party_join_request_list: PartyJoinRequestList.decode( reader, reader.uint32() ), }; break; case 44: message.message = { $case: "party_join_request", party_join_request: PartyJoinRequest.decode( reader, reader.uint32() ), }; break; case 45: message.message = { $case: "party_matchmaker_add", party_matchmaker_add: PartyMatchmakerAdd.decode( reader, reader.uint32() ), }; break; case 46: message.message = { $case: "party_matchmaker_remove", party_matchmaker_remove: PartyMatchmakerRemove.decode( reader, reader.uint32() ), }; break; case 47: message.message = { $case: "party_matchmaker_ticket", party_matchmaker_ticket: PartyMatchmakerTicket.decode( reader, reader.uint32() ), }; break; case 48: message.message = { $case: "party_data", party_data: PartyData.decode(reader, reader.uint32()), }; break; case 49: message.message = { $case: "party_data_send", party_data_send: PartyDataSend.decode(reader, reader.uint32()), }; break; case 50: message.message = { $case: "party_presence_event", party_presence_event: PartyPresenceEvent.decode( reader, reader.uint32() ), }; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Envelope { const message = { ...baseEnvelope } as Envelope; if (object.cid !== undefined && object.cid !== null) { message.cid = String(object.cid); } if (object.channel !== undefined && object.channel !== null) { message.message = { $case: "channel", channel: Channel.fromJSON(object.channel), }; } if (object.channel_join !== undefined && object.channel_join !== null) { message.message = { $case: "channel_join", channel_join: ChannelJoin.fromJSON(object.channel_join), }; } if (object.channel_leave !== undefined && object.channel_leave !== null) { message.message = { $case: "channel_leave", channel_leave: ChannelLeave.fromJSON(object.channel_leave), }; } if ( object.channel_message !== undefined && object.channel_message !== null ) { message.message = { $case: "channel_message", channel_message: ChannelMessage.fromJSON(object.channel_message), }; } if ( object.channel_message_ack !== undefined && object.channel_message_ack !== null ) { message.message = { $case: "channel_message_ack", channel_message_ack: ChannelMessageAck.fromJSON( object.channel_message_ack ), }; } if ( object.channel_message_send !== undefined && object.channel_message_send !== null ) { message.message = { $case: "channel_message_send", channel_message_send: ChannelMessageSend.fromJSON( object.channel_message_send ), }; } if ( object.channel_message_update !== undefined && object.channel_message_update !== null ) { message.message = { $case: "channel_message_update", channel_message_update: ChannelMessageUpdate.fromJSON( object.channel_message_update ), }; } if ( object.channel_message_remove !== undefined && object.channel_message_remove !== null ) { message.message = { $case: "channel_message_remove", channel_message_remove: ChannelMessageRemove.fromJSON( object.channel_message_remove ), }; } if ( object.channel_presence_event !== undefined && object.channel_presence_event !== null ) { message.message = { $case: "channel_presence_event", channel_presence_event: ChannelPresenceEvent.fromJSON( object.channel_presence_event ), }; } if (object.error !== undefined && object.error !== null) { message.message = { $case: "error", error: Error.fromJSON(object.error) }; } if (object.match !== undefined && object.match !== null) { message.message = { $case: "match", match: Match.fromJSON(object.match) }; } if (object.match_create !== undefined && object.match_create !== null) { message.message = { $case: "match_create", match_create: MatchCreate.fromJSON(object.match_create), }; } if (object.match_data !== undefined && object.match_data !== null) { message.message = { $case: "match_data", match_data: MatchData.fromJSON(object.match_data), }; } if ( object.match_data_send !== undefined && object.match_data_send !== null ) { message.message = { $case: "match_data_send", match_data_send: MatchDataSend.fromJSON(object.match_data_send), }; } if (object.match_join !== undefined && object.match_join !== null) { message.message = { $case: "match_join", match_join: MatchJoin.fromJSON(object.match_join), }; } if (object.match_leave !== undefined && object.match_leave !== null) { message.message = { $case: "match_leave", match_leave: MatchLeave.fromJSON(object.match_leave), }; } if ( object.match_presence_event !== undefined && object.match_presence_event !== null ) { message.message = { $case: "match_presence_event", match_presence_event: MatchPresenceEvent.fromJSON( object.match_presence_event ), }; } if (object.matchmaker_add !== undefined && object.matchmaker_add !== null) { message.message = { $case: "matchmaker_add", matchmaker_add: MatchmakerAdd.fromJSON(object.matchmaker_add), }; } if ( object.matchmaker_matched !== undefined && object.matchmaker_matched !== null ) { message.message = { $case: "matchmaker_matched", matchmaker_matched: MatchmakerMatched.fromJSON( object.matchmaker_matched ), }; } if ( object.matchmaker_remove !== undefined && object.matchmaker_remove !== null ) { message.message = { $case: "matchmaker_remove", matchmaker_remove: MatchmakerRemove.fromJSON(object.matchmaker_remove), }; } if ( object.matchmaker_ticket !== undefined && object.matchmaker_ticket !== null ) { message.message = { $case: "matchmaker_ticket", matchmaker_ticket: MatchmakerTicket.fromJSON(object.matchmaker_ticket), }; } if (object.notifications !== undefined && object.notifications !== null) { message.message = { $case: "notifications", notifications: Notifications.fromJSON(object.notifications), }; } if (object.rpc !== undefined && object.rpc !== null) { message.message = { $case: "rpc", rpc: Rpc.fromJSON(object.rpc) }; } if (object.status !== undefined && object.status !== null) { message.message = { $case: "status", status: Status.fromJSON(object.status), }; } if (object.status_follow !== undefined && object.status_follow !== null) { message.message = { $case: "status_follow", status_follow: StatusFollow.fromJSON(object.status_follow), }; } if ( object.status_presence_event !== undefined && object.status_presence_event !== null ) { message.message = { $case: "status_presence_event", status_presence_event: StatusPresenceEvent.fromJSON( object.status_presence_event ), }; } if ( object.status_unfollow !== undefined && object.status_unfollow !== null ) { message.message = { $case: "status_unfollow", status_unfollow: StatusUnfollow.fromJSON(object.status_unfollow), }; } if (object.status_update !== undefined && object.status_update !== null) { message.message = { $case: "status_update", status_update: StatusUpdate.fromJSON(object.status_update), }; } if (object.stream_data !== undefined && object.stream_data !== null) { message.message = { $case: "stream_data", stream_data: StreamData.fromJSON(object.stream_data), }; } if ( object.stream_presence_event !== undefined && object.stream_presence_event !== null ) { message.message = { $case: "stream_presence_event", stream_presence_event: StreamPresenceEvent.fromJSON( object.stream_presence_event ), }; } if (object.ping !== undefined && object.ping !== null) { message.message = { $case: "ping", ping: Ping.fromJSON(object.ping) }; } if (object.pong !== undefined && object.pong !== null) { message.message = { $case: "pong", pong: Pong.fromJSON(object.pong) }; } if (object.party !== undefined && object.party !== null) { message.message = { $case: "party", party: Party.fromJSON(object.party) }; } if (object.party_create !== undefined && object.party_create !== null) { message.message = { $case: "party_create", party_create: PartyCreate.fromJSON(object.party_create), }; } if (object.party_join !== undefined && object.party_join !== null) { message.message = { $case: "party_join", party_join: PartyJoin.fromJSON(object.party_join), }; } if (object.party_leave !== undefined && object.party_leave !== null) { message.message = { $case: "party_leave", party_leave: PartyLeave.fromJSON(object.party_leave), }; } if (object.party_promote !== undefined && object.party_promote !== null) { message.message = { $case: "party_promote", party_promote: PartyPromote.fromJSON(object.party_promote), }; } if (object.party_leader !== undefined && object.party_leader !== null) { message.message = { $case: "party_leader", party_leader: PartyLeader.fromJSON(object.party_leader), }; } if (object.party_accept !== undefined && object.party_accept !== null) { message.message = { $case: "party_accept", party_accept: PartyAccept.fromJSON(object.party_accept), }; } if (object.party_remove !== undefined && object.party_remove !== null) { message.message = { $case: "party_remove", party_remove: PartyRemove.fromJSON(object.party_remove), }; } if (object.party_close !== undefined && object.party_close !== null) { message.message = { $case: "party_close", party_close: PartyClose.fromJSON(object.party_close), }; } if ( object.party_join_request_list !== undefined && object.party_join_request_list !== null ) { message.message = { $case: "party_join_request_list", party_join_request_list: PartyJoinRequestList.fromJSON( object.party_join_request_list ), }; } if ( object.party_join_request !== undefined && object.party_join_request !== null ) { message.message = { $case: "party_join_request", party_join_request: PartyJoinRequest.fromJSON( object.party_join_request ), }; } if ( object.party_matchmaker_add !== undefined && object.party_matchmaker_add !== null ) { message.message = { $case: "party_matchmaker_add", party_matchmaker_add: PartyMatchmakerAdd.fromJSON( object.party_matchmaker_add ), }; } if ( object.party_matchmaker_remove !== undefined && object.party_matchmaker_remove !== null ) { message.message = { $case: "party_matchmaker_remove", party_matchmaker_remove: PartyMatchmakerRemove.fromJSON( object.party_matchmaker_remove ), }; } if ( object.party_matchmaker_ticket !== undefined && object.party_matchmaker_ticket !== null ) { message.message = { $case: "party_matchmaker_ticket", party_matchmaker_ticket: PartyMatchmakerTicket.fromJSON( object.party_matchmaker_ticket ), }; } if (object.party_data !== undefined && object.party_data !== null) { message.message = { $case: "party_data", party_data: PartyData.fromJSON(object.party_data), }; } if ( object.party_data_send !== undefined && object.party_data_send !== null ) { message.message = { $case: "party_data_send", party_data_send: PartyDataSend.fromJSON(object.party_data_send), }; } if ( object.party_presence_event !== undefined && object.party_presence_event !== null ) { message.message = { $case: "party_presence_event", party_presence_event: PartyPresenceEvent.fromJSON( object.party_presence_event ), }; } return message; }, toJSON(message: Envelope): unknown { const obj: any = {}; message.cid !== undefined && (obj.cid = message.cid); message.message?.$case === "channel" && (obj.channel = message.message?.channel ? Channel.toJSON(message.message?.channel) : undefined); message.message?.$case === "channel_join" && (obj.channel_join = message.message?.channel_join ? ChannelJoin.toJSON(message.message?.channel_join) : undefined); message.message?.$case === "channel_leave" && (obj.channel_leave = message.message?.channel_leave ? ChannelLeave.toJSON(message.message?.channel_leave) : undefined); message.message?.$case === "channel_message" && (obj.channel_message = message.message?.channel_message ? ChannelMessage.toJSON(message.message?.channel_message) : undefined); message.message?.$case === "channel_message_ack" && (obj.channel_message_ack = message.message?.channel_message_ack ? ChannelMessageAck.toJSON(message.message?.channel_message_ack) : undefined); message.message?.$case === "channel_message_send" && (obj.channel_message_send = message.message?.channel_message_send ? ChannelMessageSend.toJSON(message.message?.channel_message_send) : undefined); message.message?.$case === "channel_message_update" && (obj.channel_message_update = message.message?.channel_message_update ? ChannelMessageUpdate.toJSON(message.message?.channel_message_update) : undefined); message.message?.$case === "channel_message_remove" && (obj.channel_message_remove = message.message?.channel_message_remove ? ChannelMessageRemove.toJSON(message.message?.channel_message_remove) : undefined); message.message?.$case === "channel_presence_event" && (obj.channel_presence_event = message.message?.channel_presence_event ? ChannelPresenceEvent.toJSON(message.message?.channel_presence_event) : undefined); message.message?.$case === "error" && (obj.error = message.message?.error ? Error.toJSON(message.message?.error) : undefined); message.message?.$case === "match" && (obj.match = message.message?.match ? Match.toJSON(message.message?.match) : undefined); message.message?.$case === "match_create" && (obj.match_create = message.message?.match_create ? MatchCreate.toJSON(message.message?.match_create) : undefined); message.message?.$case === "match_data" && (obj.match_data = message.message?.match_data ? MatchData.toJSON(message.message?.match_data) : undefined); message.message?.$case === "match_data_send" && (obj.match_data_send = message.message?.match_data_send ? MatchDataSend.toJSON(message.message?.match_data_send) : undefined); message.message?.$case === "match_join" && (obj.match_join = message.message?.match_join ? MatchJoin.toJSON(message.message?.match_join) : undefined); message.message?.$case === "match_leave" && (obj.match_leave = message.message?.match_leave ? MatchLeave.toJSON(message.message?.match_leave) : undefined); message.message?.$case === "match_presence_event" && (obj.match_presence_event = message.message?.match_presence_event ? MatchPresenceEvent.toJSON(message.message?.match_presence_event) : undefined); message.message?.$case === "matchmaker_add" && (obj.matchmaker_add = message.message?.matchmaker_add ? MatchmakerAdd.toJSON(message.message?.matchmaker_add) : undefined); message.message?.$case === "matchmaker_matched" && (obj.matchmaker_matched = message.message?.matchmaker_matched ? MatchmakerMatched.toJSON(message.message?.matchmaker_matched) : undefined); message.message?.$case === "matchmaker_remove" && (obj.matchmaker_remove = message.message?.matchmaker_remove ? MatchmakerRemove.toJSON(message.message?.matchmaker_remove) : undefined); message.message?.$case === "matchmaker_ticket" && (obj.matchmaker_ticket = message.message?.matchmaker_ticket ? MatchmakerTicket.toJSON(message.message?.matchmaker_ticket) : undefined); message.message?.$case === "notifications" && (obj.notifications = message.message?.notifications ? Notifications.toJSON(message.message?.notifications) : undefined); message.message?.$case === "rpc" && (obj.rpc = message.message?.rpc ? Rpc.toJSON(message.message?.rpc) : undefined); message.message?.$case === "status" && (obj.status = message.message?.status ? Status.toJSON(message.message?.status) : undefined); message.message?.$case === "status_follow" && (obj.status_follow = message.message?.status_follow ? StatusFollow.toJSON(message.message?.status_follow) : undefined); message.message?.$case === "status_presence_event" && (obj.status_presence_event = message.message?.status_presence_event ? StatusPresenceEvent.toJSON(message.message?.status_presence_event) : undefined); message.message?.$case === "status_unfollow" && (obj.status_unfollow = message.message?.status_unfollow ? StatusUnfollow.toJSON(message.message?.status_unfollow) : undefined); message.message?.$case === "status_update" && (obj.status_update = message.message?.status_update ? StatusUpdate.toJSON(message.message?.status_update) : undefined); message.message?.$case === "stream_data" && (obj.stream_data = message.message?.stream_data ? StreamData.toJSON(message.message?.stream_data) : undefined); message.message?.$case === "stream_presence_event" && (obj.stream_presence_event = message.message?.stream_presence_event ? StreamPresenceEvent.toJSON(message.message?.stream_presence_event) : undefined); message.message?.$case === "ping" && (obj.ping = message.message?.ping ? Ping.toJSON(message.message?.ping) : undefined); message.message?.$case === "pong" && (obj.pong = message.message?.pong ? Pong.toJSON(message.message?.pong) : undefined); message.message?.$case === "party" && (obj.party = message.message?.party ? Party.toJSON(message.message?.party) : undefined); message.message?.$case === "party_create" && (obj.party_create = message.message?.party_create ? PartyCreate.toJSON(message.message?.party_create) : undefined); message.message?.$case === "party_join" && (obj.party_join = message.message?.party_join ? PartyJoin.toJSON(message.message?.party_join) : undefined); message.message?.$case === "party_leave" && (obj.party_leave = message.message?.party_leave ? PartyLeave.toJSON(message.message?.party_leave) : undefined); message.message?.$case === "party_promote" && (obj.party_promote = message.message?.party_promote ? PartyPromote.toJSON(message.message?.party_promote) : undefined); message.message?.$case === "party_leader" && (obj.party_leader = message.message?.party_leader ? PartyLeader.toJSON(message.message?.party_leader) : undefined); message.message?.$case === "party_accept" && (obj.party_accept = message.message?.party_accept ? PartyAccept.toJSON(message.message?.party_accept) : undefined); message.message?.$case === "party_remove" && (obj.party_remove = message.message?.party_remove ? PartyRemove.toJSON(message.message?.party_remove) : undefined); message.message?.$case === "party_close" && (obj.party_close = message.message?.party_close ? PartyClose.toJSON(message.message?.party_close) : undefined); message.message?.$case === "party_join_request_list" && (obj.party_join_request_list = message.message?.party_join_request_list ? PartyJoinRequestList.toJSON(message.message?.party_join_request_list) : undefined); message.message?.$case === "party_join_request" && (obj.party_join_request = message.message?.party_join_request ? PartyJoinRequest.toJSON(message.message?.party_join_request) : undefined); message.message?.$case === "party_matchmaker_add" && (obj.party_matchmaker_add = message.message?.party_matchmaker_add ? PartyMatchmakerAdd.toJSON(message.message?.party_matchmaker_add) : undefined); message.message?.$case === "party_matchmaker_remove" && (obj.party_matchmaker_remove = message.message?.party_matchmaker_remove ? PartyMatchmakerRemove.toJSON(message.message?.party_matchmaker_remove) : undefined); message.message?.$case === "party_matchmaker_ticket" && (obj.party_matchmaker_ticket = message.message?.party_matchmaker_ticket ? PartyMatchmakerTicket.toJSON(message.message?.party_matchmaker_ticket) : undefined); message.message?.$case === "party_data" && (obj.party_data = message.message?.party_data ? PartyData.toJSON(message.message?.party_data) : undefined); message.message?.$case === "party_data_send" && (obj.party_data_send = message.message?.party_data_send ? PartyDataSend.toJSON(message.message?.party_data_send) : undefined); message.message?.$case === "party_presence_event" && (obj.party_presence_event = message.message?.party_presence_event ? PartyPresenceEvent.toJSON(message.message?.party_presence_event) : undefined); return obj; }, fromPartial(object: DeepPartial<Envelope>): Envelope { const message = { ...baseEnvelope } as Envelope; if (object.cid !== undefined && object.cid !== null) { message.cid = object.cid; } if ( object.message?.$case === "channel" && object.message?.channel !== undefined && object.message?.channel !== null ) { message.message = { $case: "channel", channel: Channel.fromPartial(object.message.channel), }; } if ( object.message?.$case === "channel_join" && object.message?.channel_join !== undefined && object.message?.channel_join !== null ) { message.message = { $case: "channel_join", channel_join: ChannelJoin.fromPartial(object.message.channel_join), }; } if ( object.message?.$case === "channel_leave" && object.message?.channel_leave !== undefined && object.message?.channel_leave !== null ) { message.message = { $case: "channel_leave", channel_leave: ChannelLeave.fromPartial(object.message.channel_leave), }; } if ( object.message?.$case === "channel_message" && object.message?.channel_message !== undefined && object.message?.channel_message !== null ) { message.message = { $case: "channel_message", channel_message: ChannelMessage.fromPartial( object.message.channel_message ), }; } if ( object.message?.$case === "channel_message_ack" && object.message?.channel_message_ack !== undefined && object.message?.channel_message_ack !== null ) { message.message = { $case: "channel_message_ack", channel_message_ack: ChannelMessageAck.fromPartial( object.message.channel_message_ack ), }; } if ( object.message?.$case === "channel_message_send" && object.message?.channel_message_send !== undefined && object.message?.channel_message_send !== null ) { message.message = { $case: "channel_message_send", channel_message_send: ChannelMessageSend.fromPartial( object.message.channel_message_send ), }; } if ( object.message?.$case === "channel_message_update" && object.message?.channel_message_update !== undefined && object.message?.channel_message_update !== null ) { message.message = { $case: "channel_message_update", channel_message_update: ChannelMessageUpdate.fromPartial( object.message.channel_message_update ), }; } if ( object.message?.$case === "channel_message_remove" && object.message?.channel_message_remove !== undefined && object.message?.channel_message_remove !== null ) { message.message = { $case: "channel_message_remove", channel_message_remove: ChannelMessageRemove.fromPartial( object.message.channel_message_remove ), }; } if ( object.message?.$case === "channel_presence_event" && object.message?.channel_presence_event !== undefined && object.message?.channel_presence_event !== null ) { message.message = { $case: "channel_presence_event", channel_presence_event: ChannelPresenceEvent.fromPartial( object.message.channel_presence_event ), }; } if ( object.message?.$case === "error" && object.message?.error !== undefined && object.message?.error !== null ) { message.message = { $case: "error", error: Error.fromPartial(object.message.error), }; } if ( object.message?.$case === "match" && object.message?.match !== undefined && object.message?.match !== null ) { message.message = { $case: "match", match: Match.fromPartial(object.message.match), }; } if ( object.message?.$case === "match_create" && object.message?.match_create !== undefined && object.message?.match_create !== null ) { message.message = { $case: "match_create", match_create: MatchCreate.fromPartial(object.message.match_create), }; } if ( object.message?.$case === "match_data" && object.message?.match_data !== undefined && object.message?.match_data !== null ) { message.message = { $case: "match_data", match_data: MatchData.fromPartial(object.message.match_data), }; } if ( object.message?.$case === "match_data_send" && object.message?.match_data_send !== undefined && object.message?.match_data_send !== null ) { message.message = { $case: "match_data_send", match_data_send: MatchDataSend.fromPartial( object.message.match_data_send ), }; } if ( object.message?.$case === "match_join" && object.message?.match_join !== undefined && object.message?.match_join !== null ) { message.message = { $case: "match_join", match_join: MatchJoin.fromPartial(object.message.match_join), }; } if ( object.message?.$case === "match_leave" && object.message?.match_leave !== undefined && object.message?.match_leave !== null ) { message.message = { $case: "match_leave", match_leave: MatchLeave.fromPartial(object.message.match_leave), }; } if ( object.message?.$case === "match_presence_event" && object.message?.match_presence_event !== undefined && object.message?.match_presence_event !== null ) { message.message = { $case: "match_presence_event", match_presence_event: MatchPresenceEvent.fromPartial( object.message.match_presence_event ), }; } if ( object.message?.$case === "matchmaker_add" && object.message?.matchmaker_add !== undefined && object.message?.matchmaker_add !== null ) { message.message = { $case: "matchmaker_add", matchmaker_add: MatchmakerAdd.fromPartial( object.message.matchmaker_add ), }; } if ( object.message?.$case === "matchmaker_matched" && object.message?.matchmaker_matched !== undefined && object.message?.matchmaker_matched !== null ) { message.message = { $case: "matchmaker_matched", matchmaker_matched: MatchmakerMatched.fromPartial( object.message.matchmaker_matched ), }; } if ( object.message?.$case === "matchmaker_remove" && object.message?.matchmaker_remove !== undefined && object.message?.matchmaker_remove !== null ) { message.message = { $case: "matchmaker_remove", matchmaker_remove: MatchmakerRemove.fromPartial( object.message.matchmaker_remove ), }; } if ( object.message?.$case === "matchmaker_ticket" && object.message?.matchmaker_ticket !== undefined && object.message?.matchmaker_ticket !== null ) { message.message = { $case: "matchmaker_ticket", matchmaker_ticket: MatchmakerTicket.fromPartial( object.message.matchmaker_ticket ), }; } if ( object.message?.$case === "notifications" && object.message?.notifications !== undefined && object.message?.notifications !== null ) { message.message = { $case: "notifications", notifications: Notifications.fromPartial(object.message.notifications), }; } if ( object.message?.$case === "rpc" && object.message?.rpc !== undefined && object.message?.rpc !== null ) { message.message = { $case: "rpc", rpc: Rpc.fromPartial(object.message.rpc), }; } if ( object.message?.$case === "status" && object.message?.status !== undefined && object.message?.status !== null ) { message.message = { $case: "status", status: Status.fromPartial(object.message.status), }; } if ( object.message?.$case === "status_follow" && object.message?.status_follow !== undefined && object.message?.status_follow !== null ) { message.message = { $case: "status_follow", status_follow: StatusFollow.fromPartial(object.message.status_follow), }; } if ( object.message?.$case === "status_presence_event" && object.message?.status_presence_event !== undefined && object.message?.status_presence_event !== null ) { message.message = { $case: "status_presence_event", status_presence_event: StatusPresenceEvent.fromPartial( object.message.status_presence_event ), }; } if ( object.message?.$case === "status_unfollow" && object.message?.status_unfollow !== undefined && object.message?.status_unfollow !== null ) { message.message = { $case: "status_unfollow", status_unfollow: StatusUnfollow.fromPartial( object.message.status_unfollow ), }; } if ( object.message?.$case === "status_update" && object.message?.status_update !== undefined && object.message?.status_update !== null ) { message.message = { $case: "status_update", status_update: StatusUpdate.fromPartial(object.message.status_update), }; } if ( object.message?.$case === "stream_data" && object.message?.stream_data !== undefined && object.message?.stream_data !== null ) { message.message = { $case: "stream_data", stream_data: StreamData.fromPartial(object.message.stream_data), }; } if ( object.message?.$case === "stream_presence_event" && object.message?.stream_presence_event !== undefined && object.message?.stream_presence_event !== null ) { message.message = { $case: "stream_presence_event", stream_presence_event: StreamPresenceEvent.fromPartial( object.message.stream_presence_event ), }; } if ( object.message?.$case === "ping" && object.message?.ping !== undefined && object.message?.ping !== null ) { message.message = { $case: "ping", ping: Ping.fromPartial(object.message.ping), }; } if ( object.message?.$case === "pong" && object.message?.pong !== undefined && object.message?.pong !== null ) { message.message = { $case: "pong", pong: Pong.fromPartial(object.message.pong), }; } if ( object.message?.$case === "party" && object.message?.party !== undefined && object.message?.party !== null ) { message.message = { $case: "party", party: Party.fromPartial(object.message.party), }; } if ( object.message?.$case === "party_create" && object.message?.party_create !== undefined && object.message?.party_create !== null ) { message.message = { $case: "party_create", party_create: PartyCreate.fromPartial(object.message.party_create), }; } if ( object.message?.$case === "party_join" && object.message?.party_join !== undefined && object.message?.party_join !== null ) { message.message = { $case: "party_join", party_join: PartyJoin.fromPartial(object.message.party_join), }; } if ( object.message?.$case === "party_leave" && object.message?.party_leave !== undefined && object.message?.party_leave !== null ) { message.message = { $case: "party_leave", party_leave: PartyLeave.fromPartial(object.message.party_leave), }; } if ( object.message?.$case === "party_promote" && object.message?.party_promote !== undefined && object.message?.party_promote !== null ) { message.message = { $case: "party_promote", party_promote: PartyPromote.fromPartial(object.message.party_promote), }; } if ( object.message?.$case === "party_leader" && object.message?.party_leader !== undefined && object.message?.party_leader !== null ) { message.message = { $case: "party_leader", party_leader: PartyLeader.fromPartial(object.message.party_leader), }; } if ( object.message?.$case === "party_accept" && object.message?.party_accept !== undefined && object.message?.party_accept !== null ) { message.message = { $case: "party_accept", party_accept: PartyAccept.fromPartial(object.message.party_accept), }; } if ( object.message?.$case === "party_remove" && object.message?.party_remove !== undefined && object.message?.party_remove !== null ) { message.message = { $case: "party_remove", party_remove: PartyRemove.fromPartial(object.message.party_remove), }; } if ( object.message?.$case === "party_close" && object.message?.party_close !== undefined && object.message?.party_close !== null ) { message.message = { $case: "party_close", party_close: PartyClose.fromPartial(object.message.party_close), }; } if ( object.message?.$case === "party_join_request_list" && object.message?.party_join_request_list !== undefined && object.message?.party_join_request_list !== null ) { message.message = { $case: "party_join_request_list", party_join_request_list: PartyJoinRequestList.fromPartial( object.message.party_join_request_list ), }; } if ( object.message?.$case === "party_join_request" && object.message?.party_join_request !== undefined && object.message?.party_join_request !== null ) { message.message = { $case: "party_join_request", party_join_request: PartyJoinRequest.fromPartial( object.message.party_join_request ), }; } if ( object.message?.$case === "party_matchmaker_add" && object.message?.party_matchmaker_add !== undefined && object.message?.party_matchmaker_add !== null ) { message.message = { $case: "party_matchmaker_add", party_matchmaker_add: PartyMatchmakerAdd.fromPartial( object.message.party_matchmaker_add ), }; } if ( object.message?.$case === "party_matchmaker_remove" && object.message?.party_matchmaker_remove !== undefined && object.message?.party_matchmaker_remove !== null ) { message.message = { $case: "party_matchmaker_remove", party_matchmaker_remove: PartyMatchmakerRemove.fromPartial( object.message.party_matchmaker_remove ), }; } if ( object.message?.$case === "party_matchmaker_ticket" && object.message?.party_matchmaker_ticket !== undefined && object.message?.party_matchmaker_ticket !== null ) { message.message = { $case: "party_matchmaker_ticket", party_matchmaker_ticket: PartyMatchmakerTicket.fromPartial( object.message.party_matchmaker_ticket ), }; } if ( object.message?.$case === "party_data" && object.message?.party_data !== undefined && object.message?.party_data !== null ) { message.message = { $case: "party_data", party_data: PartyData.fromPartial(object.message.party_data), }; } if ( object.message?.$case === "party_data_send" && object.message?.party_data_send !== undefined && object.message?.party_data_send !== null ) { message.message = { $case: "party_data_send", party_data_send: PartyDataSend.fromPartial( object.message.party_data_send ), }; } if ( object.message?.$case === "party_presence_event" && object.message?.party_presence_event !== undefined && object.message?.party_presence_event !== null ) { message.message = { $case: "party_presence_event", party_presence_event: PartyPresenceEvent.fromPartial( object.message.party_presence_event ), }; } return message; }, }; const baseChannel: object = { id: "", room_name: "", group_id: "", user_id_one: "", user_id_two: "", }; export const Channel = { encode( message: Channel, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } for (const v of message.presences) { UserPresence.encode(v!, writer.uint32(18).fork()).ldelim(); } if (message.self !== undefined) { UserPresence.encode(message.self, writer.uint32(26).fork()).ldelim(); } if (message.room_name !== "") { writer.uint32(34).string(message.room_name); } if (message.group_id !== "") { writer.uint32(42).string(message.group_id); } if (message.user_id_one !== "") { writer.uint32(50).string(message.user_id_one); } if (message.user_id_two !== "") { writer.uint32(58).string(message.user_id_two); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Channel { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannel } as Channel; message.presences = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.presences.push(UserPresence.decode(reader, reader.uint32())); break; case 3: message.self = UserPresence.decode(reader, reader.uint32()); break; case 4: message.room_name = reader.string(); break; case 5: message.group_id = reader.string(); break; case 6: message.user_id_one = reader.string(); break; case 7: message.user_id_two = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Channel { const message = { ...baseChannel } as Channel; message.presences = []; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromJSON(e)); } } if (object.self !== undefined && object.self !== null) { message.self = UserPresence.fromJSON(object.self); } 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: Channel): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); if (message.presences) { obj.presences = message.presences.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.presences = []; } message.self !== undefined && (obj.self = message.self ? UserPresence.toJSON(message.self) : undefined); 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<Channel>): Channel { const message = { ...baseChannel } as Channel; message.presences = []; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromPartial(e)); } } if (object.self !== undefined && object.self !== null) { message.self = UserPresence.fromPartial(object.self); } 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 baseChannelJoin: object = { target: "", type: 0 }; export const ChannelJoin = { encode( message: ChannelJoin, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.target !== "") { writer.uint32(10).string(message.target); } if (message.type !== 0) { writer.uint32(16).int32(message.type); } if (message.persistence !== undefined) { BoolValue.encode( { value: message.persistence! }, writer.uint32(26).fork() ).ldelim(); } if (message.hidden !== undefined) { BoolValue.encode( { value: message.hidden! }, writer.uint32(34).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ChannelJoin { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelJoin } as ChannelJoin; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.target = reader.string(); break; case 2: message.type = reader.int32(); break; case 3: message.persistence = BoolValue.decode(reader, reader.uint32()).value; break; case 4: message.hidden = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelJoin { const message = { ...baseChannelJoin } as ChannelJoin; if (object.target !== undefined && object.target !== null) { message.target = String(object.target); } if (object.type !== undefined && object.type !== null) { message.type = Number(object.type); } if (object.persistence !== undefined && object.persistence !== null) { message.persistence = Boolean(object.persistence); } if (object.hidden !== undefined && object.hidden !== null) { message.hidden = Boolean(object.hidden); } return message; }, toJSON(message: ChannelJoin): unknown { const obj: any = {}; message.target !== undefined && (obj.target = message.target); message.type !== undefined && (obj.type = message.type); message.persistence !== undefined && (obj.persistence = message.persistence); message.hidden !== undefined && (obj.hidden = message.hidden); return obj; }, fromPartial(object: DeepPartial<ChannelJoin>): ChannelJoin { const message = { ...baseChannelJoin } as ChannelJoin; if (object.target !== undefined && object.target !== null) { message.target = object.target; } if (object.type !== undefined && object.type !== null) { message.type = object.type; } if (object.persistence !== undefined && object.persistence !== null) { message.persistence = object.persistence; } if (object.hidden !== undefined && object.hidden !== null) { message.hidden = object.hidden; } return message; }, }; const baseChannelLeave: object = { channel_id: "" }; export const ChannelLeave = { encode( message: ChannelLeave, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.channel_id !== "") { writer.uint32(10).string(message.channel_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ChannelLeave { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelLeave } as ChannelLeave; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.channel_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelLeave { const message = { ...baseChannelLeave } as ChannelLeave; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = String(object.channel_id); } return message; }, toJSON(message: ChannelLeave): unknown { const obj: any = {}; message.channel_id !== undefined && (obj.channel_id = message.channel_id); return obj; }, fromPartial(object: DeepPartial<ChannelLeave>): ChannelLeave { const message = { ...baseChannelLeave } as ChannelLeave; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = object.channel_id; } return message; }, }; const baseChannelMessageAck: object = { channel_id: "", message_id: "", username: "", room_name: "", group_id: "", user_id_one: "", user_id_two: "", }; export const ChannelMessageAck = { encode( message: ChannelMessageAck, 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.username !== "") { writer.uint32(34).string(message.username); } 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.persistent !== undefined) { BoolValue.encode( { value: message.persistent! }, writer.uint32(58).fork() ).ldelim(); } if (message.room_name !== "") { writer.uint32(66).string(message.room_name); } if (message.group_id !== "") { writer.uint32(74).string(message.group_id); } if (message.user_id_one !== "") { writer.uint32(82).string(message.user_id_one); } if (message.user_id_two !== "") { writer.uint32(90).string(message.user_id_two); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ChannelMessageAck { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelMessageAck } as ChannelMessageAck; 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.username = reader.string(); 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.persistent = BoolValue.decode(reader, reader.uint32()).value; break; case 8: message.room_name = reader.string(); break; case 9: message.group_id = reader.string(); break; case 10: message.user_id_one = reader.string(); break; case 11: message.user_id_two = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelMessageAck { const message = { ...baseChannelMessageAck } as ChannelMessageAck; 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.username !== undefined && object.username !== null) { message.username = String(object.username); } 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: ChannelMessageAck): 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.username !== undefined && (obj.username = message.username); 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<ChannelMessageAck>): ChannelMessageAck { const message = { ...baseChannelMessageAck } as ChannelMessageAck; 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.username !== undefined && object.username !== null) { message.username = object.username; } 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 baseChannelMessageSend: object = { channel_id: "", content: "" }; export const ChannelMessageSend = { encode( message: ChannelMessageSend, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.channel_id !== "") { writer.uint32(10).string(message.channel_id); } if (message.content !== "") { writer.uint32(18).string(message.content); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ChannelMessageSend { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelMessageSend } as ChannelMessageSend; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.channel_id = reader.string(); break; case 2: message.content = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelMessageSend { const message = { ...baseChannelMessageSend } as ChannelMessageSend; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = String(object.channel_id); } if (object.content !== undefined && object.content !== null) { message.content = String(object.content); } return message; }, toJSON(message: ChannelMessageSend): unknown { const obj: any = {}; message.channel_id !== undefined && (obj.channel_id = message.channel_id); message.content !== undefined && (obj.content = message.content); return obj; }, fromPartial(object: DeepPartial<ChannelMessageSend>): ChannelMessageSend { const message = { ...baseChannelMessageSend } as ChannelMessageSend; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = object.channel_id; } if (object.content !== undefined && object.content !== null) { message.content = object.content; } return message; }, }; const baseChannelMessageUpdate: object = { channel_id: "", message_id: "", content: "", }; export const ChannelMessageUpdate = { encode( message: ChannelMessageUpdate, 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.content !== "") { writer.uint32(26).string(message.content); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ChannelMessageUpdate { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelMessageUpdate } as ChannelMessageUpdate; 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.content = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelMessageUpdate { const message = { ...baseChannelMessageUpdate } as ChannelMessageUpdate; 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.content !== undefined && object.content !== null) { message.content = String(object.content); } return message; }, toJSON(message: ChannelMessageUpdate): 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.content !== undefined && (obj.content = message.content); return obj; }, fromPartial(object: DeepPartial<ChannelMessageUpdate>): ChannelMessageUpdate { const message = { ...baseChannelMessageUpdate } as ChannelMessageUpdate; 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.content !== undefined && object.content !== null) { message.content = object.content; } return message; }, }; const baseChannelMessageRemove: object = { channel_id: "", message_id: "" }; export const ChannelMessageRemove = { encode( message: ChannelMessageRemove, 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); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ChannelMessageRemove { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelMessageRemove } as ChannelMessageRemove; 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; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelMessageRemove { const message = { ...baseChannelMessageRemove } as ChannelMessageRemove; 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); } return message; }, toJSON(message: ChannelMessageRemove): unknown { const obj: any = {}; message.channel_id !== undefined && (obj.channel_id = message.channel_id); message.message_id !== undefined && (obj.message_id = message.message_id); return obj; }, fromPartial(object: DeepPartial<ChannelMessageRemove>): ChannelMessageRemove { const message = { ...baseChannelMessageRemove } as ChannelMessageRemove; 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; } return message; }, }; const baseChannelPresenceEvent: object = { channel_id: "", room_name: "", group_id: "", user_id_one: "", user_id_two: "", }; export const ChannelPresenceEvent = { encode( message: ChannelPresenceEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.channel_id !== "") { writer.uint32(10).string(message.channel_id); } for (const v of message.joins) { UserPresence.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.leaves) { UserPresence.encode(v!, writer.uint32(26).fork()).ldelim(); } if (message.room_name !== "") { writer.uint32(34).string(message.room_name); } if (message.group_id !== "") { writer.uint32(42).string(message.group_id); } if (message.user_id_one !== "") { writer.uint32(50).string(message.user_id_one); } if (message.user_id_two !== "") { writer.uint32(58).string(message.user_id_two); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ChannelPresenceEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelPresenceEvent } as ChannelPresenceEvent; message.joins = []; message.leaves = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.channel_id = reader.string(); break; case 2: message.joins.push(UserPresence.decode(reader, reader.uint32())); break; case 3: message.leaves.push(UserPresence.decode(reader, reader.uint32())); break; case 4: message.room_name = reader.string(); break; case 5: message.group_id = reader.string(); break; case 6: message.user_id_one = reader.string(); break; case 7: message.user_id_two = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelPresenceEvent { const message = { ...baseChannelPresenceEvent } as ChannelPresenceEvent; message.joins = []; message.leaves = []; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = String(object.channel_id); } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromJSON(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromJSON(e)); } } 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: ChannelPresenceEvent): unknown { const obj: any = {}; message.channel_id !== undefined && (obj.channel_id = message.channel_id); if (message.joins) { obj.joins = message.joins.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.joins = []; } if (message.leaves) { obj.leaves = message.leaves.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.leaves = []; } 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<ChannelPresenceEvent>): ChannelPresenceEvent { const message = { ...baseChannelPresenceEvent } as ChannelPresenceEvent; message.joins = []; message.leaves = []; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = object.channel_id; } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromPartial(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromPartial(e)); } } 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 baseError: object = { code: 0, message: "" }; export const Error = { encode(message: Error, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.code !== 0) { writer.uint32(8).int32(message.code); } if (message.message !== "") { writer.uint32(18).string(message.message); } Object.entries(message.context).forEach(([key, value]) => { Error_ContextEntry.encode( { key: key as any, value }, writer.uint32(26).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Error { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseError } as Error; message.context = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.code = reader.int32(); break; case 2: message.message = reader.string(); break; case 3: const entry3 = Error_ContextEntry.decode(reader, reader.uint32()); if (entry3.value !== undefined) { message.context[entry3.key] = entry3.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Error { const message = { ...baseError } as Error; message.context = {}; if (object.code !== undefined && object.code !== null) { message.code = Number(object.code); } if (object.message !== undefined && object.message !== null) { message.message = String(object.message); } if (object.context !== undefined && object.context !== null) { Object.entries(object.context).forEach(([key, value]) => { message.context[key] = String(value); }); } return message; }, toJSON(message: Error): unknown { const obj: any = {}; message.code !== undefined && (obj.code = message.code); message.message !== undefined && (obj.message = message.message); obj.context = {}; if (message.context) { Object.entries(message.context).forEach(([k, v]) => { obj.context[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<Error>): Error { const message = { ...baseError } as Error; message.context = {}; if (object.code !== undefined && object.code !== null) { message.code = object.code; } if (object.message !== undefined && object.message !== null) { message.message = object.message; } if (object.context !== undefined && object.context !== null) { Object.entries(object.context).forEach(([key, value]) => { if (value !== undefined) { message.context[key] = String(value); } }); } return message; }, }; const baseError_ContextEntry: object = { key: "", value: "" }; export const Error_ContextEntry = { encode( message: Error_ContextEntry, 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): Error_ContextEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseError_ContextEntry } as Error_ContextEntry; 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): Error_ContextEntry { const message = { ...baseError_ContextEntry } as Error_ContextEntry; 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: Error_ContextEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial(object: DeepPartial<Error_ContextEntry>): Error_ContextEntry { const message = { ...baseError_ContextEntry } as Error_ContextEntry; 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 baseMatch: object = { match_id: "", authoritative: false, size: 0 }; 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); } for (const v of message.presences) { UserPresence.encode(v!, writer.uint32(42).fork()).ldelim(); } if (message.self !== undefined) { UserPresence.encode(message.self, writer.uint32(50).fork()).ldelim(); } 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; message.presences = []; 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.presences.push(UserPresence.decode(reader, reader.uint32())); break; case 6: message.self = UserPresence.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Match { const message = { ...baseMatch } as Match; message.presences = []; 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.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromJSON(e)); } } if (object.self !== undefined && object.self !== null) { message.self = UserPresence.fromJSON(object.self); } 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); if (message.presences) { obj.presences = message.presences.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.presences = []; } message.self !== undefined && (obj.self = message.self ? UserPresence.toJSON(message.self) : undefined); return obj; }, fromPartial(object: DeepPartial<Match>): Match { const message = { ...baseMatch } as Match; message.presences = []; 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.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromPartial(e)); } } if (object.self !== undefined && object.self !== null) { message.self = UserPresence.fromPartial(object.self); } return message; }, }; const baseMatchCreate: object = {}; export const MatchCreate = { encode(_: MatchCreate, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchCreate { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchCreate } as MatchCreate; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): MatchCreate { const message = { ...baseMatchCreate } as MatchCreate; return message; }, toJSON(_: MatchCreate): unknown { const obj: any = {}; return obj; }, fromPartial(_: DeepPartial<MatchCreate>): MatchCreate { const message = { ...baseMatchCreate } as MatchCreate; return message; }, }; const baseMatchData: object = { match_id: "", op_code: 0, reliable: false }; export const MatchData = { encode( message: MatchData, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.match_id !== "") { writer.uint32(10).string(message.match_id); } if (message.presence !== undefined) { UserPresence.encode(message.presence, writer.uint32(18).fork()).ldelim(); } if (message.op_code !== 0) { writer.uint32(24).int64(message.op_code); } if (message.data.length !== 0) { writer.uint32(34).bytes(message.data); } if (message.reliable === true) { writer.uint32(40).bool(message.reliable); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchData { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchData } as MatchData; message.data = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.match_id = reader.string(); break; case 2: message.presence = UserPresence.decode(reader, reader.uint32()); break; case 3: message.op_code = longToNumber(reader.int64() as Long); break; case 4: message.data = reader.bytes(); break; case 5: message.reliable = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchData { const message = { ...baseMatchData } as MatchData; message.data = new Uint8Array(); if (object.match_id !== undefined && object.match_id !== null) { message.match_id = String(object.match_id); } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromJSON(object.presence); } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = Number(object.op_code); } if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data); } if (object.reliable !== undefined && object.reliable !== null) { message.reliable = Boolean(object.reliable); } return message; }, toJSON(message: MatchData): unknown { const obj: any = {}; message.match_id !== undefined && (obj.match_id = message.match_id); message.presence !== undefined && (obj.presence = message.presence ? UserPresence.toJSON(message.presence) : undefined); message.op_code !== undefined && (obj.op_code = message.op_code); message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )); message.reliable !== undefined && (obj.reliable = message.reliable); return obj; }, fromPartial(object: DeepPartial<MatchData>): MatchData { const message = { ...baseMatchData } as MatchData; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = object.match_id; } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromPartial(object.presence); } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = object.op_code; } if (object.data !== undefined && object.data !== null) { message.data = object.data; } if (object.reliable !== undefined && object.reliable !== null) { message.reliable = object.reliable; } return message; }, }; const baseMatchDataSend: object = { match_id: "", op_code: 0, reliable: false }; export const MatchDataSend = { encode( message: MatchDataSend, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.match_id !== "") { writer.uint32(10).string(message.match_id); } if (message.op_code !== 0) { writer.uint32(16).int64(message.op_code); } if (message.data.length !== 0) { writer.uint32(26).bytes(message.data); } for (const v of message.presences) { UserPresence.encode(v!, writer.uint32(34).fork()).ldelim(); } if (message.reliable === true) { writer.uint32(40).bool(message.reliable); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchDataSend { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchDataSend } as MatchDataSend; message.presences = []; message.data = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.match_id = reader.string(); break; case 2: message.op_code = longToNumber(reader.int64() as Long); break; case 3: message.data = reader.bytes(); break; case 4: message.presences.push(UserPresence.decode(reader, reader.uint32())); break; case 5: message.reliable = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchDataSend { const message = { ...baseMatchDataSend } as MatchDataSend; message.presences = []; message.data = new Uint8Array(); if (object.match_id !== undefined && object.match_id !== null) { message.match_id = String(object.match_id); } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = Number(object.op_code); } if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data); } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromJSON(e)); } } if (object.reliable !== undefined && object.reliable !== null) { message.reliable = Boolean(object.reliable); } return message; }, toJSON(message: MatchDataSend): unknown { const obj: any = {}; message.match_id !== undefined && (obj.match_id = message.match_id); message.op_code !== undefined && (obj.op_code = message.op_code); message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )); if (message.presences) { obj.presences = message.presences.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.presences = []; } message.reliable !== undefined && (obj.reliable = message.reliable); return obj; }, fromPartial(object: DeepPartial<MatchDataSend>): MatchDataSend { const message = { ...baseMatchDataSend } as MatchDataSend; message.presences = []; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = object.match_id; } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = object.op_code; } if (object.data !== undefined && object.data !== null) { message.data = object.data; } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromPartial(e)); } } if (object.reliable !== undefined && object.reliable !== null) { message.reliable = object.reliable; } return message; }, }; const baseMatchJoin: object = {}; export const MatchJoin = { encode( message: MatchJoin, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.id?.$case === "match_id") { writer.uint32(10).string(message.id.match_id); } if (message.id?.$case === "token") { writer.uint32(18).string(message.id.token); } Object.entries(message.metadata).forEach(([key, value]) => { MatchJoin_MetadataEntry.encode( { key: key as any, value }, writer.uint32(26).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchJoin { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchJoin } as MatchJoin; message.metadata = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = { $case: "match_id", match_id: reader.string() }; break; case 2: message.id = { $case: "token", token: reader.string() }; break; case 3: const entry3 = MatchJoin_MetadataEntry.decode( reader, reader.uint32() ); if (entry3.value !== undefined) { message.metadata[entry3.key] = entry3.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchJoin { const message = { ...baseMatchJoin } as MatchJoin; message.metadata = {}; if (object.match_id !== undefined && object.match_id !== null) { message.id = { $case: "match_id", match_id: String(object.match_id) }; } if (object.token !== undefined && object.token !== null) { message.id = { $case: "token", token: String(object.token) }; } if (object.metadata !== undefined && object.metadata !== null) { Object.entries(object.metadata).forEach(([key, value]) => { message.metadata[key] = String(value); }); } return message; }, toJSON(message: MatchJoin): unknown { const obj: any = {}; message.id?.$case === "match_id" && (obj.match_id = message.id?.match_id); message.id?.$case === "token" && (obj.token = message.id?.token); obj.metadata = {}; if (message.metadata) { Object.entries(message.metadata).forEach(([k, v]) => { obj.metadata[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<MatchJoin>): MatchJoin { const message = { ...baseMatchJoin } as MatchJoin; message.metadata = {}; if ( object.id?.$case === "match_id" && object.id?.match_id !== undefined && object.id?.match_id !== null ) { message.id = { $case: "match_id", match_id: object.id.match_id }; } if ( object.id?.$case === "token" && object.id?.token !== undefined && object.id?.token !== null ) { message.id = { $case: "token", token: object.id.token }; } if (object.metadata !== undefined && object.metadata !== null) { Object.entries(object.metadata).forEach(([key, value]) => { if (value !== undefined) { message.metadata[key] = String(value); } }); } return message; }, }; const baseMatchJoin_MetadataEntry: object = { key: "", value: "" }; export const MatchJoin_MetadataEntry = { encode( message: MatchJoin_MetadataEntry, 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 ): MatchJoin_MetadataEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchJoin_MetadataEntry, } as MatchJoin_MetadataEntry; 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): MatchJoin_MetadataEntry { const message = { ...baseMatchJoin_MetadataEntry, } as MatchJoin_MetadataEntry; 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: MatchJoin_MetadataEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<MatchJoin_MetadataEntry> ): MatchJoin_MetadataEntry { const message = { ...baseMatchJoin_MetadataEntry, } as MatchJoin_MetadataEntry; 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 baseMatchLeave: object = { match_id: "" }; export const MatchLeave = { encode( message: MatchLeave, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.match_id !== "") { writer.uint32(10).string(message.match_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchLeave { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchLeave } as MatchLeave; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.match_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchLeave { const message = { ...baseMatchLeave } as MatchLeave; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = String(object.match_id); } return message; }, toJSON(message: MatchLeave): unknown { const obj: any = {}; message.match_id !== undefined && (obj.match_id = message.match_id); return obj; }, fromPartial(object: DeepPartial<MatchLeave>): MatchLeave { const message = { ...baseMatchLeave } as MatchLeave; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = object.match_id; } return message; }, }; const baseMatchPresenceEvent: object = { match_id: "" }; export const MatchPresenceEvent = { encode( message: MatchPresenceEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.match_id !== "") { writer.uint32(10).string(message.match_id); } for (const v of message.joins) { UserPresence.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.leaves) { UserPresence.encode(v!, writer.uint32(26).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchPresenceEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchPresenceEvent } as MatchPresenceEvent; message.joins = []; message.leaves = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.match_id = reader.string(); break; case 2: message.joins.push(UserPresence.decode(reader, reader.uint32())); break; case 3: message.leaves.push(UserPresence.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchPresenceEvent { const message = { ...baseMatchPresenceEvent } as MatchPresenceEvent; message.joins = []; message.leaves = []; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = String(object.match_id); } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromJSON(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromJSON(e)); } } return message; }, toJSON(message: MatchPresenceEvent): unknown { const obj: any = {}; message.match_id !== undefined && (obj.match_id = message.match_id); if (message.joins) { obj.joins = message.joins.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.joins = []; } if (message.leaves) { obj.leaves = message.leaves.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.leaves = []; } return obj; }, fromPartial(object: DeepPartial<MatchPresenceEvent>): MatchPresenceEvent { const message = { ...baseMatchPresenceEvent } as MatchPresenceEvent; message.joins = []; message.leaves = []; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = object.match_id; } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromPartial(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromPartial(e)); } } return message; }, }; const baseMatchmakerAdd: object = { min_count: 0, max_count: 0, query: "" }; export const MatchmakerAdd = { encode( message: MatchmakerAdd, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.min_count !== 0) { writer.uint32(8).int32(message.min_count); } if (message.max_count !== 0) { writer.uint32(16).int32(message.max_count); } if (message.query !== "") { writer.uint32(26).string(message.query); } Object.entries(message.string_properties).forEach(([key, value]) => { MatchmakerAdd_StringPropertiesEntry.encode( { key: key as any, value }, writer.uint32(34).fork() ).ldelim(); }); Object.entries(message.numeric_properties).forEach(([key, value]) => { MatchmakerAdd_NumericPropertiesEntry.encode( { key: key as any, value }, writer.uint32(42).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchmakerAdd { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerAdd } as MatchmakerAdd; message.string_properties = {}; message.numeric_properties = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.min_count = reader.int32(); break; case 2: message.max_count = reader.int32(); break; case 3: message.query = reader.string(); break; case 4: const entry4 = MatchmakerAdd_StringPropertiesEntry.decode( reader, reader.uint32() ); if (entry4.value !== undefined) { message.string_properties[entry4.key] = entry4.value; } break; case 5: const entry5 = MatchmakerAdd_NumericPropertiesEntry.decode( reader, reader.uint32() ); if (entry5.value !== undefined) { message.numeric_properties[entry5.key] = entry5.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchmakerAdd { const message = { ...baseMatchmakerAdd } as MatchmakerAdd; message.string_properties = {}; message.numeric_properties = {}; if (object.min_count !== undefined && object.min_count !== null) { message.min_count = Number(object.min_count); } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = Number(object.max_count); } if (object.query !== undefined && object.query !== null) { message.query = String(object.query); } if ( object.string_properties !== undefined && object.string_properties !== null ) { Object.entries(object.string_properties).forEach(([key, value]) => { message.string_properties[key] = String(value); }); } if ( object.numeric_properties !== undefined && object.numeric_properties !== null ) { Object.entries(object.numeric_properties).forEach(([key, value]) => { message.numeric_properties[key] = Number(value); }); } return message; }, toJSON(message: MatchmakerAdd): unknown { const obj: any = {}; message.min_count !== undefined && (obj.min_count = message.min_count); message.max_count !== undefined && (obj.max_count = message.max_count); message.query !== undefined && (obj.query = message.query); obj.string_properties = {}; if (message.string_properties) { Object.entries(message.string_properties).forEach(([k, v]) => { obj.string_properties[k] = v; }); } obj.numeric_properties = {}; if (message.numeric_properties) { Object.entries(message.numeric_properties).forEach(([k, v]) => { obj.numeric_properties[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<MatchmakerAdd>): MatchmakerAdd { const message = { ...baseMatchmakerAdd } as MatchmakerAdd; message.string_properties = {}; message.numeric_properties = {}; if (object.min_count !== undefined && object.min_count !== null) { message.min_count = object.min_count; } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = object.max_count; } if (object.query !== undefined && object.query !== null) { message.query = object.query; } if ( object.string_properties !== undefined && object.string_properties !== null ) { Object.entries(object.string_properties).forEach(([key, value]) => { if (value !== undefined) { message.string_properties[key] = String(value); } }); } if ( object.numeric_properties !== undefined && object.numeric_properties !== null ) { Object.entries(object.numeric_properties).forEach(([key, value]) => { if (value !== undefined) { message.numeric_properties[key] = Number(value); } }); } return message; }, }; const baseMatchmakerAdd_StringPropertiesEntry: object = { key: "", value: "" }; export const MatchmakerAdd_StringPropertiesEntry = { encode( message: MatchmakerAdd_StringPropertiesEntry, 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 ): MatchmakerAdd_StringPropertiesEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerAdd_StringPropertiesEntry, } as MatchmakerAdd_StringPropertiesEntry; 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): MatchmakerAdd_StringPropertiesEntry { const message = { ...baseMatchmakerAdd_StringPropertiesEntry, } as MatchmakerAdd_StringPropertiesEntry; 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: MatchmakerAdd_StringPropertiesEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<MatchmakerAdd_StringPropertiesEntry> ): MatchmakerAdd_StringPropertiesEntry { const message = { ...baseMatchmakerAdd_StringPropertiesEntry, } as MatchmakerAdd_StringPropertiesEntry; 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 baseMatchmakerAdd_NumericPropertiesEntry: object = { key: "", value: 0 }; export const MatchmakerAdd_NumericPropertiesEntry = { encode( message: MatchmakerAdd_NumericPropertiesEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== 0) { writer.uint32(17).double(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MatchmakerAdd_NumericPropertiesEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerAdd_NumericPropertiesEntry, } as MatchmakerAdd_NumericPropertiesEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.double(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchmakerAdd_NumericPropertiesEntry { const message = { ...baseMatchmakerAdd_NumericPropertiesEntry, } as MatchmakerAdd_NumericPropertiesEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = Number(object.value); } return message; }, toJSON(message: MatchmakerAdd_NumericPropertiesEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<MatchmakerAdd_NumericPropertiesEntry> ): MatchmakerAdd_NumericPropertiesEntry { const message = { ...baseMatchmakerAdd_NumericPropertiesEntry, } as MatchmakerAdd_NumericPropertiesEntry; 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 baseMatchmakerMatched: object = { ticket: "" }; export const MatchmakerMatched = { encode( message: MatchmakerMatched, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.ticket !== "") { writer.uint32(10).string(message.ticket); } if (message.id?.$case === "match_id") { writer.uint32(18).string(message.id.match_id); } if (message.id?.$case === "token") { writer.uint32(26).string(message.id.token); } for (const v of message.users) { MatchmakerMatched_MatchmakerUser.encode( v!, writer.uint32(34).fork() ).ldelim(); } if (message.self !== undefined) { MatchmakerMatched_MatchmakerUser.encode( message.self, writer.uint32(42).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchmakerMatched { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerMatched } as MatchmakerMatched; message.users = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ticket = reader.string(); break; case 2: message.id = { $case: "match_id", match_id: reader.string() }; break; case 3: message.id = { $case: "token", token: reader.string() }; break; case 4: message.users.push( MatchmakerMatched_MatchmakerUser.decode(reader, reader.uint32()) ); break; case 5: message.self = MatchmakerMatched_MatchmakerUser.decode( reader, reader.uint32() ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchmakerMatched { const message = { ...baseMatchmakerMatched } as MatchmakerMatched; message.users = []; if (object.ticket !== undefined && object.ticket !== null) { message.ticket = String(object.ticket); } if (object.match_id !== undefined && object.match_id !== null) { message.id = { $case: "match_id", match_id: String(object.match_id) }; } if (object.token !== undefined && object.token !== null) { message.id = { $case: "token", token: String(object.token) }; } if (object.users !== undefined && object.users !== null) { for (const e of object.users) { message.users.push(MatchmakerMatched_MatchmakerUser.fromJSON(e)); } } if (object.self !== undefined && object.self !== null) { message.self = MatchmakerMatched_MatchmakerUser.fromJSON(object.self); } return message; }, toJSON(message: MatchmakerMatched): unknown { const obj: any = {}; message.ticket !== undefined && (obj.ticket = message.ticket); message.id?.$case === "match_id" && (obj.match_id = message.id?.match_id); message.id?.$case === "token" && (obj.token = message.id?.token); if (message.users) { obj.users = message.users.map((e) => e ? MatchmakerMatched_MatchmakerUser.toJSON(e) : undefined ); } else { obj.users = []; } message.self !== undefined && (obj.self = message.self ? MatchmakerMatched_MatchmakerUser.toJSON(message.self) : undefined); return obj; }, fromPartial(object: DeepPartial<MatchmakerMatched>): MatchmakerMatched { const message = { ...baseMatchmakerMatched } as MatchmakerMatched; message.users = []; if (object.ticket !== undefined && object.ticket !== null) { message.ticket = object.ticket; } if ( object.id?.$case === "match_id" && object.id?.match_id !== undefined && object.id?.match_id !== null ) { message.id = { $case: "match_id", match_id: object.id.match_id }; } if ( object.id?.$case === "token" && object.id?.token !== undefined && object.id?.token !== null ) { message.id = { $case: "token", token: object.id.token }; } if (object.users !== undefined && object.users !== null) { for (const e of object.users) { message.users.push(MatchmakerMatched_MatchmakerUser.fromPartial(e)); } } if (object.self !== undefined && object.self !== null) { message.self = MatchmakerMatched_MatchmakerUser.fromPartial(object.self); } return message; }, }; const baseMatchmakerMatched_MatchmakerUser: object = { party_id: "" }; export const MatchmakerMatched_MatchmakerUser = { encode( message: MatchmakerMatched_MatchmakerUser, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.presence !== undefined) { UserPresence.encode(message.presence, writer.uint32(10).fork()).ldelim(); } if (message.party_id !== "") { writer.uint32(18).string(message.party_id); } Object.entries(message.string_properties).forEach(([key, value]) => { MatchmakerMatched_MatchmakerUser_StringPropertiesEntry.encode( { key: key as any, value }, writer.uint32(42).fork() ).ldelim(); }); Object.entries(message.numeric_properties).forEach(([key, value]) => { MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry.encode( { key: key as any, value }, writer.uint32(50).fork() ).ldelim(); }); return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MatchmakerMatched_MatchmakerUser { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerMatched_MatchmakerUser, } as MatchmakerMatched_MatchmakerUser; message.string_properties = {}; message.numeric_properties = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.presence = UserPresence.decode(reader, reader.uint32()); break; case 2: message.party_id = reader.string(); break; case 5: const entry5 = MatchmakerMatched_MatchmakerUser_StringPropertiesEntry.decode( reader, reader.uint32() ); if (entry5.value !== undefined) { message.string_properties[entry5.key] = entry5.value; } break; case 6: const entry6 = MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry.decode( reader, reader.uint32() ); if (entry6.value !== undefined) { message.numeric_properties[entry6.key] = entry6.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchmakerMatched_MatchmakerUser { const message = { ...baseMatchmakerMatched_MatchmakerUser, } as MatchmakerMatched_MatchmakerUser; message.string_properties = {}; message.numeric_properties = {}; if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromJSON(object.presence); } if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if ( object.string_properties !== undefined && object.string_properties !== null ) { Object.entries(object.string_properties).forEach(([key, value]) => { message.string_properties[key] = String(value); }); } if ( object.numeric_properties !== undefined && object.numeric_properties !== null ) { Object.entries(object.numeric_properties).forEach(([key, value]) => { message.numeric_properties[key] = Number(value); }); } return message; }, toJSON(message: MatchmakerMatched_MatchmakerUser): unknown { const obj: any = {}; message.presence !== undefined && (obj.presence = message.presence ? UserPresence.toJSON(message.presence) : undefined); message.party_id !== undefined && (obj.party_id = message.party_id); obj.string_properties = {}; if (message.string_properties) { Object.entries(message.string_properties).forEach(([k, v]) => { obj.string_properties[k] = v; }); } obj.numeric_properties = {}; if (message.numeric_properties) { Object.entries(message.numeric_properties).forEach(([k, v]) => { obj.numeric_properties[k] = v; }); } return obj; }, fromPartial( object: DeepPartial<MatchmakerMatched_MatchmakerUser> ): MatchmakerMatched_MatchmakerUser { const message = { ...baseMatchmakerMatched_MatchmakerUser, } as MatchmakerMatched_MatchmakerUser; message.string_properties = {}; message.numeric_properties = {}; if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromPartial(object.presence); } if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if ( object.string_properties !== undefined && object.string_properties !== null ) { Object.entries(object.string_properties).forEach(([key, value]) => { if (value !== undefined) { message.string_properties[key] = String(value); } }); } if ( object.numeric_properties !== undefined && object.numeric_properties !== null ) { Object.entries(object.numeric_properties).forEach(([key, value]) => { if (value !== undefined) { message.numeric_properties[key] = Number(value); } }); } return message; }, }; const baseMatchmakerMatched_MatchmakerUser_StringPropertiesEntry: object = { key: "", value: "", }; export const MatchmakerMatched_MatchmakerUser_StringPropertiesEntry = { encode( message: MatchmakerMatched_MatchmakerUser_StringPropertiesEntry, 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 ): MatchmakerMatched_MatchmakerUser_StringPropertiesEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerMatched_MatchmakerUser_StringPropertiesEntry, } as MatchmakerMatched_MatchmakerUser_StringPropertiesEntry; 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 ): MatchmakerMatched_MatchmakerUser_StringPropertiesEntry { const message = { ...baseMatchmakerMatched_MatchmakerUser_StringPropertiesEntry, } as MatchmakerMatched_MatchmakerUser_StringPropertiesEntry; 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: MatchmakerMatched_MatchmakerUser_StringPropertiesEntry ): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<MatchmakerMatched_MatchmakerUser_StringPropertiesEntry> ): MatchmakerMatched_MatchmakerUser_StringPropertiesEntry { const message = { ...baseMatchmakerMatched_MatchmakerUser_StringPropertiesEntry, } as MatchmakerMatched_MatchmakerUser_StringPropertiesEntry; 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 baseMatchmakerMatched_MatchmakerUser_NumericPropertiesEntry: object = { key: "", value: 0, }; export const MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry = { encode( message: MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== 0) { writer.uint32(17).double(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerMatched_MatchmakerUser_NumericPropertiesEntry, } as MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.double(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON( object: any ): MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry { const message = { ...baseMatchmakerMatched_MatchmakerUser_NumericPropertiesEntry, } as MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = Number(object.value); } return message; }, toJSON( message: MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry ): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry> ): MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry { const message = { ...baseMatchmakerMatched_MatchmakerUser_NumericPropertiesEntry, } as MatchmakerMatched_MatchmakerUser_NumericPropertiesEntry; 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 baseMatchmakerRemove: object = { ticket: "" }; export const MatchmakerRemove = { encode( message: MatchmakerRemove, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.ticket !== "") { writer.uint32(10).string(message.ticket); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchmakerRemove { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerRemove } as MatchmakerRemove; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ticket = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchmakerRemove { const message = { ...baseMatchmakerRemove } as MatchmakerRemove; if (object.ticket !== undefined && object.ticket !== null) { message.ticket = String(object.ticket); } return message; }, toJSON(message: MatchmakerRemove): unknown { const obj: any = {}; message.ticket !== undefined && (obj.ticket = message.ticket); return obj; }, fromPartial(object: DeepPartial<MatchmakerRemove>): MatchmakerRemove { const message = { ...baseMatchmakerRemove } as MatchmakerRemove; if (object.ticket !== undefined && object.ticket !== null) { message.ticket = object.ticket; } return message; }, }; const baseMatchmakerTicket: object = { ticket: "" }; export const MatchmakerTicket = { encode( message: MatchmakerTicket, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.ticket !== "") { writer.uint32(10).string(message.ticket); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchmakerTicket { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchmakerTicket } as MatchmakerTicket; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ticket = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchmakerTicket { const message = { ...baseMatchmakerTicket } as MatchmakerTicket; if (object.ticket !== undefined && object.ticket !== null) { message.ticket = String(object.ticket); } return message; }, toJSON(message: MatchmakerTicket): unknown { const obj: any = {}; message.ticket !== undefined && (obj.ticket = message.ticket); return obj; }, fromPartial(object: DeepPartial<MatchmakerTicket>): MatchmakerTicket { const message = { ...baseMatchmakerTicket } as MatchmakerTicket; if (object.ticket !== undefined && object.ticket !== null) { message.ticket = object.ticket; } return message; }, }; const baseNotifications: object = {}; export const Notifications = { encode( message: Notifications, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.notifications) { Notification.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Notifications { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseNotifications } as Notifications; message.notifications = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.notifications.push( Notification.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Notifications { const message = { ...baseNotifications } as Notifications; message.notifications = []; if (object.notifications !== undefined && object.notifications !== null) { for (const e of object.notifications) { message.notifications.push(Notification.fromJSON(e)); } } return message; }, toJSON(message: Notifications): unknown { const obj: any = {}; if (message.notifications) { obj.notifications = message.notifications.map((e) => e ? Notification.toJSON(e) : undefined ); } else { obj.notifications = []; } return obj; }, fromPartial(object: DeepPartial<Notifications>): Notifications { const message = { ...baseNotifications } as Notifications; message.notifications = []; if (object.notifications !== undefined && object.notifications !== null) { for (const e of object.notifications) { message.notifications.push(Notification.fromPartial(e)); } } return message; }, }; const baseParty: object = { party_id: "", open: false, max_size: 0 }; export const Party = { encode(message: Party, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.open === true) { writer.uint32(16).bool(message.open); } if (message.max_size !== 0) { writer.uint32(24).int32(message.max_size); } if (message.self !== undefined) { UserPresence.encode(message.self, writer.uint32(34).fork()).ldelim(); } if (message.leader !== undefined) { UserPresence.encode(message.leader, writer.uint32(42).fork()).ldelim(); } for (const v of message.presences) { UserPresence.encode(v!, writer.uint32(50).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Party { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseParty } as Party; message.presences = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.open = reader.bool(); break; case 3: message.max_size = reader.int32(); break; case 4: message.self = UserPresence.decode(reader, reader.uint32()); break; case 5: message.leader = UserPresence.decode(reader, reader.uint32()); break; case 6: message.presences.push(UserPresence.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Party { const message = { ...baseParty } as Party; message.presences = []; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.open !== undefined && object.open !== null) { message.open = Boolean(object.open); } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = Number(object.max_size); } if (object.self !== undefined && object.self !== null) { message.self = UserPresence.fromJSON(object.self); } if (object.leader !== undefined && object.leader !== null) { message.leader = UserPresence.fromJSON(object.leader); } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromJSON(e)); } } return message; }, toJSON(message: Party): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.open !== undefined && (obj.open = message.open); message.max_size !== undefined && (obj.max_size = message.max_size); message.self !== undefined && (obj.self = message.self ? UserPresence.toJSON(message.self) : undefined); message.leader !== undefined && (obj.leader = message.leader ? UserPresence.toJSON(message.leader) : undefined); if (message.presences) { obj.presences = message.presences.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.presences = []; } return obj; }, fromPartial(object: DeepPartial<Party>): Party { const message = { ...baseParty } as Party; message.presences = []; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.open !== undefined && object.open !== null) { message.open = object.open; } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = object.max_size; } if (object.self !== undefined && object.self !== null) { message.self = UserPresence.fromPartial(object.self); } if (object.leader !== undefined && object.leader !== null) { message.leader = UserPresence.fromPartial(object.leader); } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromPartial(e)); } } return message; }, }; const basePartyCreate: object = { open: false, max_size: 0 }; export const PartyCreate = { encode( message: PartyCreate, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.open === true) { writer.uint32(8).bool(message.open); } if (message.max_size !== 0) { writer.uint32(16).int32(message.max_size); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyCreate { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyCreate } as PartyCreate; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.open = reader.bool(); break; case 2: message.max_size = reader.int32(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyCreate { const message = { ...basePartyCreate } as PartyCreate; if (object.open !== undefined && object.open !== null) { message.open = Boolean(object.open); } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = Number(object.max_size); } return message; }, toJSON(message: PartyCreate): unknown { const obj: any = {}; message.open !== undefined && (obj.open = message.open); message.max_size !== undefined && (obj.max_size = message.max_size); return obj; }, fromPartial(object: DeepPartial<PartyCreate>): PartyCreate { const message = { ...basePartyCreate } as PartyCreate; if (object.open !== undefined && object.open !== null) { message.open = object.open; } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = object.max_size; } return message; }, }; const basePartyJoin: object = { party_id: "" }; export const PartyJoin = { encode( message: PartyJoin, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyJoin { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyJoin } as PartyJoin; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyJoin { const message = { ...basePartyJoin } as PartyJoin; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } return message; }, toJSON(message: PartyJoin): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); return obj; }, fromPartial(object: DeepPartial<PartyJoin>): PartyJoin { const message = { ...basePartyJoin } as PartyJoin; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } return message; }, }; const basePartyLeave: object = { party_id: "" }; export const PartyLeave = { encode( message: PartyLeave, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyLeave { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyLeave } as PartyLeave; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyLeave { const message = { ...basePartyLeave } as PartyLeave; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } return message; }, toJSON(message: PartyLeave): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); return obj; }, fromPartial(object: DeepPartial<PartyLeave>): PartyLeave { const message = { ...basePartyLeave } as PartyLeave; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } return message; }, }; const basePartyPromote: object = { party_id: "" }; export const PartyPromote = { encode( message: PartyPromote, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.presence !== undefined) { UserPresence.encode(message.presence, writer.uint32(18).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyPromote { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyPromote } as PartyPromote; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.presence = UserPresence.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyPromote { const message = { ...basePartyPromote } as PartyPromote; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromJSON(object.presence); } return message; }, toJSON(message: PartyPromote): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.presence !== undefined && (obj.presence = message.presence ? UserPresence.toJSON(message.presence) : undefined); return obj; }, fromPartial(object: DeepPartial<PartyPromote>): PartyPromote { const message = { ...basePartyPromote } as PartyPromote; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromPartial(object.presence); } return message; }, }; const basePartyLeader: object = { party_id: "" }; export const PartyLeader = { encode( message: PartyLeader, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.presence !== undefined) { UserPresence.encode(message.presence, writer.uint32(18).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyLeader { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyLeader } as PartyLeader; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.presence = UserPresence.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyLeader { const message = { ...basePartyLeader } as PartyLeader; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromJSON(object.presence); } return message; }, toJSON(message: PartyLeader): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.presence !== undefined && (obj.presence = message.presence ? UserPresence.toJSON(message.presence) : undefined); return obj; }, fromPartial(object: DeepPartial<PartyLeader>): PartyLeader { const message = { ...basePartyLeader } as PartyLeader; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromPartial(object.presence); } return message; }, }; const basePartyAccept: object = { party_id: "" }; export const PartyAccept = { encode( message: PartyAccept, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.presence !== undefined) { UserPresence.encode(message.presence, writer.uint32(18).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyAccept { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyAccept } as PartyAccept; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.presence = UserPresence.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyAccept { const message = { ...basePartyAccept } as PartyAccept; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromJSON(object.presence); } return message; }, toJSON(message: PartyAccept): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.presence !== undefined && (obj.presence = message.presence ? UserPresence.toJSON(message.presence) : undefined); return obj; }, fromPartial(object: DeepPartial<PartyAccept>): PartyAccept { const message = { ...basePartyAccept } as PartyAccept; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromPartial(object.presence); } return message; }, }; const basePartyRemove: object = { party_id: "" }; export const PartyRemove = { encode( message: PartyRemove, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.presence !== undefined) { UserPresence.encode(message.presence, writer.uint32(18).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyRemove { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyRemove } as PartyRemove; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.presence = UserPresence.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyRemove { const message = { ...basePartyRemove } as PartyRemove; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromJSON(object.presence); } return message; }, toJSON(message: PartyRemove): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.presence !== undefined && (obj.presence = message.presence ? UserPresence.toJSON(message.presence) : undefined); return obj; }, fromPartial(object: DeepPartial<PartyRemove>): PartyRemove { const message = { ...basePartyRemove } as PartyRemove; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromPartial(object.presence); } return message; }, }; const basePartyClose: object = { party_id: "" }; export const PartyClose = { encode( message: PartyClose, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyClose { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyClose } as PartyClose; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyClose { const message = { ...basePartyClose } as PartyClose; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } return message; }, toJSON(message: PartyClose): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); return obj; }, fromPartial(object: DeepPartial<PartyClose>): PartyClose { const message = { ...basePartyClose } as PartyClose; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } return message; }, }; const basePartyJoinRequestList: object = { party_id: "" }; export const PartyJoinRequestList = { encode( message: PartyJoinRequestList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): PartyJoinRequestList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyJoinRequestList } as PartyJoinRequestList; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyJoinRequestList { const message = { ...basePartyJoinRequestList } as PartyJoinRequestList; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } return message; }, toJSON(message: PartyJoinRequestList): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); return obj; }, fromPartial(object: DeepPartial<PartyJoinRequestList>): PartyJoinRequestList { const message = { ...basePartyJoinRequestList } as PartyJoinRequestList; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } return message; }, }; const basePartyJoinRequest: object = { party_id: "" }; export const PartyJoinRequest = { encode( message: PartyJoinRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } for (const v of message.presences) { UserPresence.encode(v!, writer.uint32(18).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyJoinRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyJoinRequest } as PartyJoinRequest; message.presences = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.presences.push(UserPresence.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyJoinRequest { const message = { ...basePartyJoinRequest } as PartyJoinRequest; message.presences = []; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromJSON(e)); } } return message; }, toJSON(message: PartyJoinRequest): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); if (message.presences) { obj.presences = message.presences.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.presences = []; } return obj; }, fromPartial(object: DeepPartial<PartyJoinRequest>): PartyJoinRequest { const message = { ...basePartyJoinRequest } as PartyJoinRequest; message.presences = []; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromPartial(e)); } } return message; }, }; const basePartyMatchmakerAdd: object = { party_id: "", min_count: 0, max_count: 0, query: "", }; export const PartyMatchmakerAdd = { encode( message: PartyMatchmakerAdd, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.min_count !== 0) { writer.uint32(16).int32(message.min_count); } if (message.max_count !== 0) { writer.uint32(24).int32(message.max_count); } if (message.query !== "") { writer.uint32(34).string(message.query); } Object.entries(message.string_properties).forEach(([key, value]) => { PartyMatchmakerAdd_StringPropertiesEntry.encode( { key: key as any, value }, writer.uint32(42).fork() ).ldelim(); }); Object.entries(message.numeric_properties).forEach(([key, value]) => { PartyMatchmakerAdd_NumericPropertiesEntry.encode( { key: key as any, value }, writer.uint32(50).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyMatchmakerAdd { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyMatchmakerAdd } as PartyMatchmakerAdd; message.string_properties = {}; message.numeric_properties = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.min_count = reader.int32(); break; case 3: message.max_count = reader.int32(); break; case 4: message.query = reader.string(); break; case 5: const entry5 = PartyMatchmakerAdd_StringPropertiesEntry.decode( reader, reader.uint32() ); if (entry5.value !== undefined) { message.string_properties[entry5.key] = entry5.value; } break; case 6: const entry6 = PartyMatchmakerAdd_NumericPropertiesEntry.decode( reader, reader.uint32() ); if (entry6.value !== undefined) { message.numeric_properties[entry6.key] = entry6.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyMatchmakerAdd { const message = { ...basePartyMatchmakerAdd } as PartyMatchmakerAdd; message.string_properties = {}; message.numeric_properties = {}; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.min_count !== undefined && object.min_count !== null) { message.min_count = Number(object.min_count); } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = Number(object.max_count); } if (object.query !== undefined && object.query !== null) { message.query = String(object.query); } if ( object.string_properties !== undefined && object.string_properties !== null ) { Object.entries(object.string_properties).forEach(([key, value]) => { message.string_properties[key] = String(value); }); } if ( object.numeric_properties !== undefined && object.numeric_properties !== null ) { Object.entries(object.numeric_properties).forEach(([key, value]) => { message.numeric_properties[key] = Number(value); }); } return message; }, toJSON(message: PartyMatchmakerAdd): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.min_count !== undefined && (obj.min_count = message.min_count); message.max_count !== undefined && (obj.max_count = message.max_count); message.query !== undefined && (obj.query = message.query); obj.string_properties = {}; if (message.string_properties) { Object.entries(message.string_properties).forEach(([k, v]) => { obj.string_properties[k] = v; }); } obj.numeric_properties = {}; if (message.numeric_properties) { Object.entries(message.numeric_properties).forEach(([k, v]) => { obj.numeric_properties[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<PartyMatchmakerAdd>): PartyMatchmakerAdd { const message = { ...basePartyMatchmakerAdd } as PartyMatchmakerAdd; message.string_properties = {}; message.numeric_properties = {}; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.min_count !== undefined && object.min_count !== null) { message.min_count = object.min_count; } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = object.max_count; } if (object.query !== undefined && object.query !== null) { message.query = object.query; } if ( object.string_properties !== undefined && object.string_properties !== null ) { Object.entries(object.string_properties).forEach(([key, value]) => { if (value !== undefined) { message.string_properties[key] = String(value); } }); } if ( object.numeric_properties !== undefined && object.numeric_properties !== null ) { Object.entries(object.numeric_properties).forEach(([key, value]) => { if (value !== undefined) { message.numeric_properties[key] = Number(value); } }); } return message; }, }; const basePartyMatchmakerAdd_StringPropertiesEntry: object = { key: "", value: "", }; export const PartyMatchmakerAdd_StringPropertiesEntry = { encode( message: PartyMatchmakerAdd_StringPropertiesEntry, 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 ): PartyMatchmakerAdd_StringPropertiesEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyMatchmakerAdd_StringPropertiesEntry, } as PartyMatchmakerAdd_StringPropertiesEntry; 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): PartyMatchmakerAdd_StringPropertiesEntry { const message = { ...basePartyMatchmakerAdd_StringPropertiesEntry, } as PartyMatchmakerAdd_StringPropertiesEntry; 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: PartyMatchmakerAdd_StringPropertiesEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<PartyMatchmakerAdd_StringPropertiesEntry> ): PartyMatchmakerAdd_StringPropertiesEntry { const message = { ...basePartyMatchmakerAdd_StringPropertiesEntry, } as PartyMatchmakerAdd_StringPropertiesEntry; 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 basePartyMatchmakerAdd_NumericPropertiesEntry: object = { key: "", value: 0, }; export const PartyMatchmakerAdd_NumericPropertiesEntry = { encode( message: PartyMatchmakerAdd_NumericPropertiesEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== 0) { writer.uint32(17).double(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): PartyMatchmakerAdd_NumericPropertiesEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyMatchmakerAdd_NumericPropertiesEntry, } as PartyMatchmakerAdd_NumericPropertiesEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.double(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyMatchmakerAdd_NumericPropertiesEntry { const message = { ...basePartyMatchmakerAdd_NumericPropertiesEntry, } as PartyMatchmakerAdd_NumericPropertiesEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = Number(object.value); } return message; }, toJSON(message: PartyMatchmakerAdd_NumericPropertiesEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<PartyMatchmakerAdd_NumericPropertiesEntry> ): PartyMatchmakerAdd_NumericPropertiesEntry { const message = { ...basePartyMatchmakerAdd_NumericPropertiesEntry, } as PartyMatchmakerAdd_NumericPropertiesEntry; 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 basePartyMatchmakerRemove: object = { party_id: "", ticket: "" }; export const PartyMatchmakerRemove = { encode( message: PartyMatchmakerRemove, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.ticket !== "") { writer.uint32(18).string(message.ticket); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): PartyMatchmakerRemove { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyMatchmakerRemove } as PartyMatchmakerRemove; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.ticket = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyMatchmakerRemove { const message = { ...basePartyMatchmakerRemove } as PartyMatchmakerRemove; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.ticket !== undefined && object.ticket !== null) { message.ticket = String(object.ticket); } return message; }, toJSON(message: PartyMatchmakerRemove): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.ticket !== undefined && (obj.ticket = message.ticket); return obj; }, fromPartial( object: DeepPartial<PartyMatchmakerRemove> ): PartyMatchmakerRemove { const message = { ...basePartyMatchmakerRemove } as PartyMatchmakerRemove; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.ticket !== undefined && object.ticket !== null) { message.ticket = object.ticket; } return message; }, }; const basePartyMatchmakerTicket: object = { party_id: "", ticket: "" }; export const PartyMatchmakerTicket = { encode( message: PartyMatchmakerTicket, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.ticket !== "") { writer.uint32(18).string(message.ticket); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): PartyMatchmakerTicket { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyMatchmakerTicket } as PartyMatchmakerTicket; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.ticket = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyMatchmakerTicket { const message = { ...basePartyMatchmakerTicket } as PartyMatchmakerTicket; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.ticket !== undefined && object.ticket !== null) { message.ticket = String(object.ticket); } return message; }, toJSON(message: PartyMatchmakerTicket): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.ticket !== undefined && (obj.ticket = message.ticket); return obj; }, fromPartial( object: DeepPartial<PartyMatchmakerTicket> ): PartyMatchmakerTicket { const message = { ...basePartyMatchmakerTicket } as PartyMatchmakerTicket; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.ticket !== undefined && object.ticket !== null) { message.ticket = object.ticket; } return message; }, }; const basePartyData: object = { party_id: "", op_code: 0 }; export const PartyData = { encode( message: PartyData, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.presence !== undefined) { UserPresence.encode(message.presence, writer.uint32(18).fork()).ldelim(); } if (message.op_code !== 0) { writer.uint32(24).int64(message.op_code); } if (message.data.length !== 0) { writer.uint32(34).bytes(message.data); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyData { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyData } as PartyData; message.data = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.presence = UserPresence.decode(reader, reader.uint32()); break; case 3: message.op_code = longToNumber(reader.int64() as Long); break; case 4: message.data = reader.bytes(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyData { const message = { ...basePartyData } as PartyData; message.data = new Uint8Array(); if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromJSON(object.presence); } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = Number(object.op_code); } if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data); } return message; }, toJSON(message: PartyData): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.presence !== undefined && (obj.presence = message.presence ? UserPresence.toJSON(message.presence) : undefined); message.op_code !== undefined && (obj.op_code = message.op_code); message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )); return obj; }, fromPartial(object: DeepPartial<PartyData>): PartyData { const message = { ...basePartyData } as PartyData; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.presence !== undefined && object.presence !== null) { message.presence = UserPresence.fromPartial(object.presence); } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = object.op_code; } if (object.data !== undefined && object.data !== null) { message.data = object.data; } return message; }, }; const basePartyDataSend: object = { party_id: "", op_code: 0 }; export const PartyDataSend = { encode( message: PartyDataSend, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } if (message.op_code !== 0) { writer.uint32(16).int64(message.op_code); } if (message.data.length !== 0) { writer.uint32(26).bytes(message.data); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyDataSend { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyDataSend } as PartyDataSend; message.data = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.op_code = longToNumber(reader.int64() as Long); break; case 3: message.data = reader.bytes(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyDataSend { const message = { ...basePartyDataSend } as PartyDataSend; message.data = new Uint8Array(); if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = Number(object.op_code); } if (object.data !== undefined && object.data !== null) { message.data = bytesFromBase64(object.data); } return message; }, toJSON(message: PartyDataSend): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); message.op_code !== undefined && (obj.op_code = message.op_code); message.data !== undefined && (obj.data = base64FromBytes( message.data !== undefined ? message.data : new Uint8Array() )); return obj; }, fromPartial(object: DeepPartial<PartyDataSend>): PartyDataSend { const message = { ...basePartyDataSend } as PartyDataSend; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.op_code !== undefined && object.op_code !== null) { message.op_code = object.op_code; } if (object.data !== undefined && object.data !== null) { message.data = object.data; } return message; }, }; const basePartyPresenceEvent: object = { party_id: "" }; export const PartyPresenceEvent = { encode( message: PartyPresenceEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.party_id !== "") { writer.uint32(10).string(message.party_id); } for (const v of message.joins) { UserPresence.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.leaves) { UserPresence.encode(v!, writer.uint32(26).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PartyPresenceEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePartyPresenceEvent } as PartyPresenceEvent; message.joins = []; message.leaves = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.party_id = reader.string(); break; case 2: message.joins.push(UserPresence.decode(reader, reader.uint32())); break; case 3: message.leaves.push(UserPresence.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PartyPresenceEvent { const message = { ...basePartyPresenceEvent } as PartyPresenceEvent; message.joins = []; message.leaves = []; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = String(object.party_id); } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromJSON(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromJSON(e)); } } return message; }, toJSON(message: PartyPresenceEvent): unknown { const obj: any = {}; message.party_id !== undefined && (obj.party_id = message.party_id); if (message.joins) { obj.joins = message.joins.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.joins = []; } if (message.leaves) { obj.leaves = message.leaves.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.leaves = []; } return obj; }, fromPartial(object: DeepPartial<PartyPresenceEvent>): PartyPresenceEvent { const message = { ...basePartyPresenceEvent } as PartyPresenceEvent; message.joins = []; message.leaves = []; if (object.party_id !== undefined && object.party_id !== null) { message.party_id = object.party_id; } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromPartial(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromPartial(e)); } } return message; }, }; const basePing: object = {}; export const Ping = { encode(_: Ping, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Ping { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePing } as Ping; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): Ping { const message = { ...basePing } as Ping; return message; }, toJSON(_: Ping): unknown { const obj: any = {}; return obj; }, fromPartial(_: DeepPartial<Ping>): Ping { const message = { ...basePing } as Ping; return message; }, }; const basePong: object = {}; export const Pong = { encode(_: Pong, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Pong { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePong } as Pong; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(_: any): Pong { const message = { ...basePong } as Pong; return message; }, toJSON(_: Pong): unknown { const obj: any = {}; return obj; }, fromPartial(_: DeepPartial<Pong>): Pong { const message = { ...basePong } as Pong; return message; }, }; const baseStatus: object = {}; export const Status = { encode( message: Status, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.presences) { UserPresence.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Status { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStatus } as Status; message.presences = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.presences.push(UserPresence.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Status { const message = { ...baseStatus } as Status; message.presences = []; if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromJSON(e)); } } return message; }, toJSON(message: Status): unknown { const obj: any = {}; if (message.presences) { obj.presences = message.presences.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.presences = []; } return obj; }, fromPartial(object: DeepPartial<Status>): Status { const message = { ...baseStatus } as Status; message.presences = []; if (object.presences !== undefined && object.presences !== null) { for (const e of object.presences) { message.presences.push(UserPresence.fromPartial(e)); } } return message; }, }; const baseStatusFollow: object = { user_ids: "", usernames: "" }; export const StatusFollow = { encode( message: StatusFollow, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.user_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): StatusFollow { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStatusFollow } as StatusFollow; message.user_ids = []; message.usernames = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user_ids.push(reader.string()); break; case 2: message.usernames.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StatusFollow { const message = { ...baseStatusFollow } as StatusFollow; message.user_ids = []; message.usernames = []; if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_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: StatusFollow): unknown { const obj: any = {}; if (message.user_ids) { obj.user_ids = message.user_ids.map((e) => e); } else { obj.user_ids = []; } if (message.usernames) { obj.usernames = message.usernames.map((e) => e); } else { obj.usernames = []; } return obj; }, fromPartial(object: DeepPartial<StatusFollow>): StatusFollow { const message = { ...baseStatusFollow } as StatusFollow; message.user_ids = []; message.usernames = []; if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(e); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(e); } } return message; }, }; const baseStatusPresenceEvent: object = {}; export const StatusPresenceEvent = { encode( message: StatusPresenceEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.joins) { UserPresence.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.leaves) { UserPresence.encode(v!, writer.uint32(26).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StatusPresenceEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStatusPresenceEvent } as StatusPresenceEvent; message.joins = []; message.leaves = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 2: message.joins.push(UserPresence.decode(reader, reader.uint32())); break; case 3: message.leaves.push(UserPresence.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StatusPresenceEvent { const message = { ...baseStatusPresenceEvent } as StatusPresenceEvent; message.joins = []; message.leaves = []; if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromJSON(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromJSON(e)); } } return message; }, toJSON(message: StatusPresenceEvent): unknown { const obj: any = {}; if (message.joins) { obj.joins = message.joins.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.joins = []; } if (message.leaves) { obj.leaves = message.leaves.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.leaves = []; } return obj; }, fromPartial(object: DeepPartial<StatusPresenceEvent>): StatusPresenceEvent { const message = { ...baseStatusPresenceEvent } as StatusPresenceEvent; message.joins = []; message.leaves = []; if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromPartial(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromPartial(e)); } } return message; }, }; const baseStatusUnfollow: object = { user_ids: "" }; export const StatusUnfollow = { encode( message: StatusUnfollow, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.user_ids) { writer.uint32(10).string(v!); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StatusUnfollow { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStatusUnfollow } as StatusUnfollow; message.user_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user_ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StatusUnfollow { const message = { ...baseStatusUnfollow } as StatusUnfollow; message.user_ids = []; 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: StatusUnfollow): unknown { const obj: any = {}; if (message.user_ids) { obj.user_ids = message.user_ids.map((e) => e); } else { obj.user_ids = []; } return obj; }, fromPartial(object: DeepPartial<StatusUnfollow>): StatusUnfollow { const message = { ...baseStatusUnfollow } as StatusUnfollow; message.user_ids = []; if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(e); } } return message; }, }; const baseStatusUpdate: object = {}; export const StatusUpdate = { encode( message: StatusUpdate, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.status !== undefined) { StringValue.encode( { value: message.status! }, writer.uint32(10).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StatusUpdate { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStatusUpdate } as StatusUpdate; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.status = StringValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StatusUpdate { const message = { ...baseStatusUpdate } as StatusUpdate; if (object.status !== undefined && object.status !== null) { message.status = String(object.status); } return message; }, toJSON(message: StatusUpdate): unknown { const obj: any = {}; message.status !== undefined && (obj.status = message.status); return obj; }, fromPartial(object: DeepPartial<StatusUpdate>): StatusUpdate { const message = { ...baseStatusUpdate } as StatusUpdate; if (object.status !== undefined && object.status !== null) { message.status = object.status; } return message; }, }; const baseStream: object = { mode: 0, subject: "", subcontext: "", label: "" }; export const Stream = { encode( message: Stream, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.mode !== 0) { writer.uint32(8).int32(message.mode); } if (message.subject !== "") { writer.uint32(18).string(message.subject); } if (message.subcontext !== "") { writer.uint32(26).string(message.subcontext); } if (message.label !== "") { writer.uint32(34).string(message.label); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Stream { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStream } as Stream; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.mode = reader.int32(); break; case 2: message.subject = reader.string(); break; case 3: message.subcontext = reader.string(); break; case 4: message.label = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Stream { const message = { ...baseStream } as Stream; if (object.mode !== undefined && object.mode !== null) { message.mode = Number(object.mode); } if (object.subject !== undefined && object.subject !== null) { message.subject = String(object.subject); } if (object.subcontext !== undefined && object.subcontext !== null) { message.subcontext = String(object.subcontext); } if (object.label !== undefined && object.label !== null) { message.label = String(object.label); } return message; }, toJSON(message: Stream): unknown { const obj: any = {}; message.mode !== undefined && (obj.mode = message.mode); message.subject !== undefined && (obj.subject = message.subject); message.subcontext !== undefined && (obj.subcontext = message.subcontext); message.label !== undefined && (obj.label = message.label); return obj; }, fromPartial(object: DeepPartial<Stream>): Stream { const message = { ...baseStream } as Stream; if (object.mode !== undefined && object.mode !== null) { message.mode = object.mode; } if (object.subject !== undefined && object.subject !== null) { message.subject = object.subject; } if (object.subcontext !== undefined && object.subcontext !== null) { message.subcontext = object.subcontext; } if (object.label !== undefined && object.label !== null) { message.label = object.label; } return message; }, }; const baseStreamData: object = { data: "", reliable: false }; export const StreamData = { encode( message: StreamData, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.stream !== undefined) { Stream.encode(message.stream, writer.uint32(10).fork()).ldelim(); } if (message.sender !== undefined) { UserPresence.encode(message.sender, writer.uint32(18).fork()).ldelim(); } if (message.data !== "") { writer.uint32(26).string(message.data); } if (message.reliable === true) { writer.uint32(32).bool(message.reliable); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StreamData { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStreamData } as StreamData; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.stream = Stream.decode(reader, reader.uint32()); break; case 2: message.sender = UserPresence.decode(reader, reader.uint32()); break; case 3: message.data = reader.string(); break; case 4: message.reliable = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StreamData { const message = { ...baseStreamData } as StreamData; if (object.stream !== undefined && object.stream !== null) { message.stream = Stream.fromJSON(object.stream); } if (object.sender !== undefined && object.sender !== null) { message.sender = UserPresence.fromJSON(object.sender); } if (object.data !== undefined && object.data !== null) { message.data = String(object.data); } if (object.reliable !== undefined && object.reliable !== null) { message.reliable = Boolean(object.reliable); } return message; }, toJSON(message: StreamData): unknown { const obj: any = {}; message.stream !== undefined && (obj.stream = message.stream ? Stream.toJSON(message.stream) : undefined); message.sender !== undefined && (obj.sender = message.sender ? UserPresence.toJSON(message.sender) : undefined); message.data !== undefined && (obj.data = message.data); message.reliable !== undefined && (obj.reliable = message.reliable); return obj; }, fromPartial(object: DeepPartial<StreamData>): StreamData { const message = { ...baseStreamData } as StreamData; if (object.stream !== undefined && object.stream !== null) { message.stream = Stream.fromPartial(object.stream); } if (object.sender !== undefined && object.sender !== null) { message.sender = UserPresence.fromPartial(object.sender); } if (object.data !== undefined && object.data !== null) { message.data = object.data; } if (object.reliable !== undefined && object.reliable !== null) { message.reliable = object.reliable; } return message; }, }; const baseStreamPresenceEvent: object = {}; export const StreamPresenceEvent = { encode( message: StreamPresenceEvent, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.stream !== undefined) { Stream.encode(message.stream, writer.uint32(10).fork()).ldelim(); } for (const v of message.joins) { UserPresence.encode(v!, writer.uint32(18).fork()).ldelim(); } for (const v of message.leaves) { UserPresence.encode(v!, writer.uint32(26).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StreamPresenceEvent { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStreamPresenceEvent } as StreamPresenceEvent; message.joins = []; message.leaves = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.stream = Stream.decode(reader, reader.uint32()); break; case 2: message.joins.push(UserPresence.decode(reader, reader.uint32())); break; case 3: message.leaves.push(UserPresence.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StreamPresenceEvent { const message = { ...baseStreamPresenceEvent } as StreamPresenceEvent; message.joins = []; message.leaves = []; if (object.stream !== undefined && object.stream !== null) { message.stream = Stream.fromJSON(object.stream); } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromJSON(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromJSON(e)); } } return message; }, toJSON(message: StreamPresenceEvent): unknown { const obj: any = {}; message.stream !== undefined && (obj.stream = message.stream ? Stream.toJSON(message.stream) : undefined); if (message.joins) { obj.joins = message.joins.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.joins = []; } if (message.leaves) { obj.leaves = message.leaves.map((e) => e ? UserPresence.toJSON(e) : undefined ); } else { obj.leaves = []; } return obj; }, fromPartial(object: DeepPartial<StreamPresenceEvent>): StreamPresenceEvent { const message = { ...baseStreamPresenceEvent } as StreamPresenceEvent; message.joins = []; message.leaves = []; if (object.stream !== undefined && object.stream !== null) { message.stream = Stream.fromPartial(object.stream); } if (object.joins !== undefined && object.joins !== null) { for (const e of object.joins) { message.joins.push(UserPresence.fromPartial(e)); } } if (object.leaves !== undefined && object.leaves !== null) { for (const e of object.leaves) { message.leaves.push(UserPresence.fromPartial(e)); } } return message; }, }; const baseUserPresence: object = { user_id: "", session_id: "", username: "", persistence: false, }; export const UserPresence = { encode( message: UserPresence, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.user_id !== "") { writer.uint32(10).string(message.user_id); } if (message.session_id !== "") { writer.uint32(18).string(message.session_id); } if (message.username !== "") { writer.uint32(26).string(message.username); } if (message.persistence === true) { writer.uint32(32).bool(message.persistence); } if (message.status !== undefined) { StringValue.encode( { value: message.status! }, writer.uint32(42).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): UserPresence { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseUserPresence } as UserPresence; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user_id = reader.string(); break; case 2: message.session_id = reader.string(); break; case 3: message.username = reader.string(); break; case 4: message.persistence = reader.bool(); break; case 5: message.status = StringValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): UserPresence { const message = { ...baseUserPresence } as UserPresence; if (object.user_id !== undefined && object.user_id !== null) { message.user_id = String(object.user_id); } if (object.session_id !== undefined && object.session_id !== null) { message.session_id = String(object.session_id); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } if (object.persistence !== undefined && object.persistence !== null) { message.persistence = Boolean(object.persistence); } if (object.status !== undefined && object.status !== null) { message.status = String(object.status); } return message; }, toJSON(message: UserPresence): unknown { const obj: any = {}; message.user_id !== undefined && (obj.user_id = message.user_id); message.session_id !== undefined && (obj.session_id = message.session_id); message.username !== undefined && (obj.username = message.username); message.persistence !== undefined && (obj.persistence = message.persistence); message.status !== undefined && (obj.status = message.status); return obj; }, fromPartial(object: DeepPartial<UserPresence>): UserPresence { const message = { ...baseUserPresence } as UserPresence; if (object.user_id !== undefined && object.user_id !== null) { message.user_id = object.user_id; } if (object.session_id !== undefined && object.session_id !== null) { message.session_id = object.session_id; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } if (object.persistence !== undefined && object.persistence !== null) { message.persistence = object.persistence; } if (object.status !== undefined && object.status !== null) { message.status = object.status; } 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"; })(); const atob: (b64: string) => string = globalThis.atob || ((b64) => globalThis.Buffer.from(b64, "base64").toString("binary")); function bytesFromBase64(b64: string): Uint8Array { const bin = atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } const btoa: (bin: string) => string = globalThis.btoa || ((bin) => globalThis.Buffer.from(bin, "binary").toString("base64")); function base64FromBytes(arr: Uint8Array): string { const bin: string[] = []; for (let i = 0; i < arr.byteLength; ++i) { bin.push(String.fromCharCode(arr[i])); } return btoa(bin.join("")); } 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 css from 'styled-jsx/css'; import KeyboardNumberInput from '../../keyboard-number-input'; import Slider from './slider'; import OptionsContainer from '../options-container'; import {useState, useEffect, useMemo} from 'react'; import * as stringMath from 'string-math'; import VideoMetadataContainer from '../video-metadata-container'; import {shake} from '../../../utils/inputs'; import Select, {Separator} from './select'; const percentValues = [100, 75, 50, 33, 25, 20, 10]; const {className: keyboardInputClass, styles: keyboardInputStyles} = css.resolve` height: 24px; background: rgba(255, 255, 255, 0.1); text-align: center; font-size: 12px; box-sizing: border-box; border: none; padding: 4px; border-bottom-left-radius: 4px; border-top-left-radius: 4px; width: 48px; color: white; box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.04), 0px 1px 2px 0px rgba(0, 0, 0, 0.2); input + input { border-bottom-left-radius: 0; border-top-left-radius: 0; border-bottom-right-radius: 4px; border-top-right-radius: 4px; margin-left: 1px; margin-right: 16px; } :focus, :hover { outline: none; background: hsla(0, 0%, 100%, 0.2); } `; const LeftOptions = () => { const {width, height, setDimensions, fps, updateFps, originalFps} = OptionsContainer.useContainer(); const metadata = VideoMetadataContainer.useContainer(); const [widthValue, setWidthValue] = useState<string>(); const [heightValue, setHeightValue] = useState<string>(); const onChange = (event, {ignoreEmpty = true}: {ignoreEmpty?: boolean} = {}) => { if (!ignoreEmpty) { onBlur(event); return; } const {currentTarget: {name, value}} = event; if (name === 'width') { setWidthValue(value); } else { setHeightValue(value); } }; const onBlur = event => { const {currentTarget} = event; const {name} = currentTarget; let value: number; try { value = stringMath(currentTarget.value); } catch {} // Fallback to last valid const updates = {width, height}; if (value) { value = Math.round(value); const ratio = metadata.width / metadata.height; if (name === 'width') { const min = Math.max(1, Math.ceil(ratio)); if (value < min) { shake(currentTarget, {className: 'shake-left'}); updates.width = min; } else if (value > metadata.width) { shake(currentTarget, {className: 'shake-left'}); updates.width = metadata.width; } else { updates.width = value; } updates.height = Math[ratio > 1 ? 'ceil' : 'floor'](updates.width / ratio); } else { const min = Math.max(1, Math.ceil(1 / ratio)); if (value < min) { shake(currentTarget, {className: 'shake-right'}); updates.height = min; } else if (value > metadata.height) { shake(currentTarget, {className: 'shake-right'}); updates.height = metadata.height; } else { updates.height = value; } updates.width = Math[ratio > 1 ? 'floor' : 'ceil'](updates.height * ratio); } } else if (name === 'width') { shake(currentTarget, {className: 'shake-left'}); } else { shake(currentTarget, {className: 'shake-right'}); } setDimensions(updates); setWidthValue(updates.width.toString()); setHeightValue(updates.height.toString()); }; useEffect(() => { if (width && height) { setWidthValue(width.toString()); setHeightValue(height.toString()); } }, [width, height]); const percentOptions = useMemo(() => { const ratio = metadata.width / metadata.height; const options = percentValues.map(percent => { const adjustedWidth = Math.round(metadata.width * (percent / 100)); const adjustedHeight = Math[ratio > 1 ? 'ceil' : 'floor'](adjustedWidth / ratio); return { label: `${adjustedWidth} x ${adjustedHeight} (${percent === 100 ? 'Original' : `${percent}%`})`, value: {width: adjustedWidth, height: adjustedHeight}, checked: width === adjustedWidth }; }); if (options.every(opt => !opt.checked)) { return [ { label: 'Custom', value: {width, height}, checked: true }, { separator: true }, ...options ]; } return options; }, [metadata, width, height]); const selectPercentage = updates => { setDimensions(updates); setWidthValue(updates.width.toString()); setHeightValue(updates.height.toString()); }; const percentLabel = `${Math.round((width / metadata.width) * 100)}%`; return ( <div className="container"> <div className="label">Size</div> <KeyboardNumberInput className={keyboardInputClass} value={widthValue || ''} size="5" name="width" min={1} max={metadata.width} onChange={onChange} onBlur={onBlur} /> <KeyboardNumberInput className={keyboardInputClass} value={heightValue || ''} size="5" name="height" min={1} max={metadata.height} onChange={onChange} onBlur={onBlur} /> <div className="percent"> <Select options={percentOptions as any} customLabel={percentLabel} onChange={selectPercentage}/> </div> <div className="label">FPS</div> <div className="fps"> <Slider value={fps} min={5} max={originalFps} onChange={updateFps}/> </div> {keyboardInputStyles} <style jsx>{` .container { height: 100%; display: flex; align-items: center; } .label { font-size: 12px; margin-right: 8px; color: white; } .percent { height: 24px; width: 68px; margin-left: -8px; margin-right: 8px; } .fps { height: 24px; width: 32px; } .option { width: 48px; height: 22px; background: transparent; display: flex; align-items: center; justify-content: center; font-size: 12px; color: white; box-sizing: border-box; } .option:hover { background: hsla(0, 0%, 100%, 0.2); } .option:active, .option.selected { background: transparent; } `}</style> </div> ); }; export default LeftOptions; // Import React from 'react'; // import PropTypes from 'prop-types'; // import {connect, EditorContainer} from '../../../containers'; // import css from 'styled-jsx/css'; // import KeyboardNumberInput from '../../keyboard-number-input'; // import Slider from './slider'; // const {className: keyboardInputClass, styles: keyboardInputStyles} = css.resolve` // height: 24px; // background: rgba(255, 255, 255, 0.1); // text-align: center; // font-size: 12px; // box-sizing: border-box; // border: none; // padding: 4px; // border-bottom-left-radius: 4px; // border-top-left-radius: 4px; // width: 48px; // color: white; // box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.04), 0px 1px 2px 0px rgba(0, 0, 0, 0.2); // input + input { // border-bottom-left-radius: 0; // border-top-left-radius: 0; // border-bottom-right-radius: 4px; // border-top-right-radius: 4px; // margin-left: 1px; // margin-right: 16px; // } // :focus, :hover { // outline: none; // background: hsla(0, 0%, 100%, 0.2); // } // `; // class LeftOptions extends React.Component { // handleBlur = event => { // const {changeDimension} = this.props; // changeDimension(event, {ignoreEmpty: false}); // } // render() { // const {width, height, changeDimension, fps, originalFps, setFps, original} = this.props; // return ( // <div className="container"> // <div className="label">Size</div> // <KeyboardNumberInput // className={keyboardInputClass} // value={width || ''} // size="5" // min={1} // max={original && original.width} // name="width" // onChange={changeDimension} // onKeyDown={changeDimension} // onBlur={this.handleBlur} // /> // <KeyboardNumberInput // className={keyboardInputClass} // value={height || ''} // size="5" // min={1} // max={original && original.height} // name="height" // onChange={changeDimension} // onKeyDown={changeDimension} // onBlur={this.handleBlur} // /> // <div className="label">FPS</div> // <div className="fps"> // <Slider value={fps} min={1} max={originalFps} onChange={setFps}/> // </div> // {keyboardInputStyles} // <style jsx>{` // .container { // height: 100%; // display: flex; // align-items: center; // } // .label { // font-size: 12px; // margin-right: 8px; // color: white; // } // .fps { // height: 24px; // width: 32px; // } // .option { // width: 48px; // height: 22px; // background: transparent; // display: flex; // align-items: center; // justify-content: center; // font-size: 12px; // color: white; // box-sizing: border-box; // } // .option:hover { // background: hsla(0, 0%, 100%, 0.2); // } // .option:active, // .option.selected { // background: transparent; // } // `}</style> // </div> // ); // } // } // LeftOptions.propTypes = { // width: PropTypes.number, // height: PropTypes.number, // changeDimension: PropTypes.elementType, // fps: PropTypes.number, // setFps: PropTypes.elementType, // originalFps: PropTypes.number, // original: PropTypes.shape({ // width: PropTypes.number, // height: PropTypes.number // }) // }; // export default connect( // [EditorContainer], // ({width, height, fps, originalFps, original}) => ({width, height, fps, originalFps, original}), // ({changeDimension, setFps}) => ({changeDimension, setFps}) // )(LeftOptions);
the_stack
import should from "should"; import Adapt, { AdaptElement, AnyState, Component, createStateStore, PrimitiveComponent, StateStore, } from "../src"; import * as st from "../src/state"; import { Empty, MakeGroup } from "./testlib"; type Update = AnyState | st.StateUpdater; interface StateUpdaterProps { initialState: any; updates: Update[]; constructorStateObserver?: (state: any) => void; buildStartObserver?: (state: any) => void; buildEndObserver?: (state: any) => void; initialStateObserver?: () => void; } class StateUpdater extends Component<StateUpdaterProps, AnyState> { constructor(props: StateUpdaterProps) { super(props); if (props.constructorStateObserver != null) { props.constructorStateObserver(this.state); } } initialState() { if (this.props.initialStateObserver != null) { this.props.initialStateObserver(); } return this.props.initialState; } build() { if (this.props.buildStartObserver != null) { this.props.buildStartObserver(this.state); } for (const u of this.props.updates) { this.setState(u); } if (this.props.buildEndObserver != null) { this.props.buildEndObserver(this.state); } return <Empty id={1} />; } } interface NoInitialStateProps { readTooEarly?: boolean; readState?: boolean; writeState?: boolean; setState?: boolean; } class NoInitialState extends Component<NoInitialStateProps, AnyState> { constructor(props: NoInitialStateProps) { // @ts-ignore - compiler doesn't allow you to touch this before super if (props.readTooEarly) this.state; super(props); if (props.readState) this.state; if (props.writeState) this.state = {a: 1}; if (props.setState) this.setState({b: 2}); } build() { return <Empty id={2}/>; } } interface PWSState { counter: number; } class PrimitiveWithState extends PrimitiveComponent<{}, PWSState> { constructor(props: {}) { super(props); this.setState((prev) => ({ counter: prev.counter + 1 })); } initialState() { return { counter: 0 }; } } describe("DOM setState Tests", () => { let state: StateStore; let buildStartState: any[]; let buildEndState: any[]; let previousState: any[]; let ctorState: any[]; let calledInitial: number; let defaultProps: StateUpdaterProps; beforeEach(() => { state = createStateStore(); buildStartState = []; buildEndState = []; previousState = []; ctorState = []; calledInitial = 0; defaultProps = { initialState: {}, buildStartObserver: (s) => { buildStartState.push(s); }, buildEndObserver: (s) => { buildEndState.push(s); }, constructorStateObserver: (s) => { ctorState.push(s); }, initialStateObserver: () => { calledInitial++; }, updates: [], }; }); function updater(nextState: AnyState): st.StateUpdater { return (prev) => { previousState.push(prev); return nextState; }; } async function checkBuild(dom: AdaptElement) { const out = await Adapt.buildOnce(dom, null, { stateStore: state }); should(out.messages).have.length(0, `Error messages during build`); } it("Should record state for single components", async () => { const initialState = { elem1: "data1", elem2: "data2" }; const dom = <StateUpdater key="root" initialState={initialState} updates={[]} />; await checkBuild(dom); const actual = state.elementState(["root"]); should(actual).eql(initialState); }); it("Should correctly send previous state", async () => { const prevState = { elem: "data" }; const nextState = { elem: "newData" }; const props = { ...defaultProps, initialState: prevState, updates: [ updater(nextState) ], }; const dom = <StateUpdater key="root" {...props} />; state.setElementState(["root"], prevState); await checkBuild(dom); const actual = state.elementState(["root"]); should(ctorState).eql([prevState]); should(calledInitial).eql(0); should(actual).eql(nextState); should(previousState).eql([prevState]); should(buildStartState).eql([prevState]); }); it("Should update state within DOM", async () => { const newState = { elem1: "data1", elem2: "data2" }; const props = { ...defaultProps, updates: [ newState ], }; const dom = <MakeGroup key="root"> <StateUpdater key="updater" {...props} /> </MakeGroup>; await checkBuild(dom); const actual = state.elementState(["root", "root-Group", "updater"]); should(actual).eql(newState); }); it("Should honor initial state", async () => { const initialState = { elem: "data" }; const nextState = { elem: "newData" }; const props = { ...defaultProps, initialState, updates: [ updater(nextState) ], }; const dom = <StateUpdater key="root" {...props} />; await checkBuild(dom); const actual = state.elementState(["root"]); should(actual).eql(nextState); should(previousState).eql([initialState]); should(ctorState).eql([initialState]); should(calledInitial).eql(1); should(buildStartState).eql([initialState]); should(buildEndState).eql(buildStartState); }); it("Should remember state across builds", async () => { const initialState = { elem: "data" }; const nextState = { elem: "newData" }; const props = { ...defaultProps, initialState, updates: [ updater(nextState) ], }; const dom = <StateUpdater key="root" {...props} />; await checkBuild(dom); let actual = state.elementState(["root"]); should(actual).eql(nextState); should(previousState).eql([initialState]); should(ctorState).eql([initialState]); should(calledInitial).eql(1); /* Second build */ await checkBuild(dom); actual = state.elementState(["root"]); should(actual).eql(nextState); should(previousState).eql([initialState, nextState]); should(ctorState).eql([initialState, nextState]); should(calledInitial).eql(1); }); it("Should perform updates in order", async () => { function cat(toAppend: string) { return (prev: {data: string}) => { prev.data = prev.data + toAppend; return prev; }; } const initialState = { init: "yes" }; const props = { ...defaultProps, initialState, updates: [ { data: "1" }, cat("2"), cat("3"), cat("4"), ] }; const finalExpected = { init: "yes", data: "1234", }; const dom = <StateUpdater key="root" {...props} />; await checkBuild(dom); const actual = state.elementState(["root"]); should(actual).eql(finalExpected); should(buildStartState).eql([initialState]); should(buildEndState).eql(buildStartState); }); it("Should error if state read before super", async () => { const dom = <NoInitialState key="root" readTooEarly={true} />; const out = await Adapt.buildOnce(dom, null, { stateStore: state }); should(out.messages).have.length(1); should(out.messages[0].content).match( RegExp("Component construction failed: Must call super constructor " + "in derived class before accessing 'this'")); }); it("Should error if state read without initialState", async () => { const dom = <NoInitialState key="root" readState={true} />; const out = await Adapt.buildOnce(dom, null, { stateStore: state }); should(out.messages).have.length(1); should(out.messages[0].content).match( RegExp("Component construction failed: cannot access this.state in " + "a Component that lacks an initialState method")); }); it("Should error if this.state is written", async () => { const dom = <NoInitialState key="root" writeState={true} />; const out = await Adapt.buildOnce(dom, null, { stateStore: state }); should(out.messages).have.length(1); should(out.messages[0].content).match( RegExp("Component construction failed: State for a component can " + "only be changed by calling this.setState")); }); it("Should error if setState called without initialState", async () => { const dom = <NoInitialState key="root" setState={true} />; const out = await Adapt.buildOnce(dom, null, { stateStore: state }); should(out.messages).have.length(1); should(out.messages[0].content).match( RegExp("Component NoInitialState: cannot access this.setState in " + "a Component that lacks an initialState method")); }); it("Should allow PrimitiveComponent with state", async () => { const dom = <PrimitiveWithState key="root" />; await checkBuild(dom); let actual = state.elementState(["root"]); should(actual).eql({ counter: 1 }); await checkBuild(dom); actual = state.elementState(["root"]); should(actual).eql({ counter: 2 }); }); });
the_stack
import { AbiItem, BurnDetails, ContractCall, EventEmitterTyped, LockAndMintTransaction, Logger, NullLogger, } from "@renproject/interfaces"; import { assert, assertType, fromHex, isDefined, isHex, Ox, payloadToABI, payloadToMintABI, SECONDS, sleep, keccak256, } from "@renproject/utils"; import BigNumber from "bignumber.js"; import BN from "bn.js"; import { EthAddress, EthTransaction } from "./types"; import { Provider, TransactionReceipt } from "@ethersproject/providers"; import { Overrides } from "ethers"; import * as ethers from "ethers"; import { EthereumConfig } from "./networks"; const EMPTY_ADDRESS = "0x" + "00".repeat(20); export interface EthereumTransactionConfig extends Overrides { value?: ethers.BigNumberish | Promise<ethers.BigNumberish>; } /** * eventTopics contains the Ethereum event identifiers (the first log topic) for * Gateway contract events. */ export const eventTopics = { /** * ```js * event LogBurn( * bytes _to, * uint256 _amount, * uint256 indexed _n, * bytes indexed _indexedTo * ); * ``` */ LogBurn: Ox(keccak256(Buffer.from("LogBurn(bytes,uint256,uint256,bytes)"))), /** * ```js * event LogMint( * address indexed _to, * uint256 _amount, * uint256 indexed _n, * bytes32 indexed _signedMessageHash * ); * ``` */ LogMint: Ox( keccak256(Buffer.from("LogMint(address,uint256,uint256,bytes32)")), ), }; /** * Waits for the receipt of a transaction to be available, retrying every 3 * seconds until it is. * * @param web3 A web3 instance. * @param txHash The hash of the transaction being read. */ export const waitForReceipt = async ( provider: Provider, txHash: string, logger?: Logger, timeout?: number, ): Promise<TransactionReceipt> => // eslint-disable-next-line @typescript-eslint/no-misused-promises new Promise<TransactionReceipt>(async (resolve, reject) => { assertType<string>("string", { txHash }); // Wait for confirmation let receipt: TransactionReceipt | undefined; while (!receipt || !receipt.blockHash) { if (logger) { logger.debug(`Fetching transaction receipt: ${txHash}`); } receipt = await provider.getTransactionReceipt(txHash); if (receipt && receipt.blockHash) { break; } await sleep(isDefined(timeout) ? timeout : 15 * SECONDS); } // Status might be undefined - so check against `false` explicitly. if (receipt.status === 0) { reject( new Error( `Transaction was reverted. { "transactionHash": "${txHash}" }`, ), ); return; } resolve(receipt); return; }); export const parseBurnEvent = (event: { transactionHash: string; topics: string[]; data: string; }): BurnDetails<EthTransaction> => { assert(event.topics[0] === eventTopics.LogBurn); const burnLogABI = { anonymous: false, inputs: [ { indexed: false, internalType: "bytes", name: "_to", type: "bytes", }, { indexed: false, internalType: "uint256", name: "_amount", type: "uint256", }, { indexed: true, internalType: "uint256", name: "_n", type: "uint256", }, { indexed: true, internalType: "bytes", name: "_indexedTo", type: "bytes", }, ], name: "LogBurn", type: "event", }; const burnLogDecoder = new ethers.utils.Interface([burnLogABI]); const decodedLog = burnLogDecoder.parseLog(event); const [_to, _amount, _n] = decodedLog.args; return { transaction: event.transactionHash, amount: new BigNumber(_amount.toString()), to: fromHex(_to).toString(), nonce: new BigNumber(_n.toString()), }; }; export const extractBurnDetails = async ( provider: Provider, txHash: string, logger?: Logger, timeout?: number, ): Promise<BurnDetails<EthTransaction>> => { assertType<string>("string", { txHash }); const receipt = await waitForReceipt(provider, txHash, logger, timeout); if (!receipt.logs) { throw Error("No events found in transaction"); } const burnDetails = receipt.logs .filter((event) => event.topics[0] === eventTopics.LogBurn) .map((event) => parseBurnEvent(event)); if (burnDetails.length > 1) { // WARNING: More than one burn found. } if (burnDetails.length) { return burnDetails[0]; } throw Error("No reference ID found in logs"); }; export const getGatewayAddress = async ( network: EthereumConfig, provider: Provider, asset: string, ): Promise<string> => { try { const getGatewayBySymbol: AbiItem = { constant: true, inputs: [ { internalType: "string", name: "_tokenSymbol", type: "string", }, ], name: "getGatewayBySymbol", outputs: [ { internalType: "contract IGateway", name: "", type: "address", }, ], payable: false, stateMutability: "view", type: "function", }; const registry = new ethers.Contract( network.addresses.GatewayRegistry, [getGatewayBySymbol], provider, ); // const registry = new web3.eth.Contract( // [getGatewayBySymbol], // network.addresses.GatewayRegistry, // ); const registryAddress: string = Ox( await registry.getGatewayBySymbol(asset), ); if (!registryAddress || registryAddress === EMPTY_ADDRESS) { throw new Error(`Empty address returned.`); } return registryAddress; } catch (error) { (error || {}).message = `Error looking up ${asset} gateway address${ error.message ? `: ${String(error.message)}` : "." }`; throw error; } }; export const findBurnByNonce = async ( network: EthereumConfig, provider: Provider, asset: string, nonce: Buffer | string | number, ): Promise<BurnDetails<EthTransaction>> => { const gatewayAddress = await getGatewayAddress(network, provider, asset); const nonceBuffer = Buffer.isBuffer(nonce) ? Buffer.from(nonce) : new BN(nonce).toArrayLike(Buffer, "be", 32); const burnEvents = await provider.getLogs({ address: gatewayAddress, fromBlock: "1", toBlock: "latest", topics: [eventTopics.LogBurn, Ox(nonceBuffer)] as string[], }); if (!burnEvents.length) { throw Error(`Burn not found for nonce ${Ox(nonceBuffer)}`); } if (burnEvents.length > 1) { // WARNING: More than one burn with the same nonce. } return parseBurnEvent(burnEvents[0]); }; export const getTokenAddress = async ( network: EthereumConfig, provider: Provider, asset: string, ): Promise<string> => { try { const getTokenBySymbolABI: AbiItem = { constant: true, inputs: [ { internalType: "string", name: "_tokenSymbol", type: "string", }, ], name: "getTokenBySymbol", outputs: [ { internalType: "contract IERC20", name: "", type: "address", }, ], payable: false, stateMutability: "view", type: "function", }; const registry = new ethers.Contract( network.addresses.GatewayRegistry, [getTokenBySymbolABI], provider, ); const tokenAddress: string = Ox(await registry.getTokenBySymbol(asset)); if (!tokenAddress || tokenAddress === EMPTY_ADDRESS) { throw new Error(`Empty address returned.`); } return tokenAddress; } catch (error) { (error || {}).message = `Error looking up ${asset} token address on ${ network.chainLabel }${error.message ? `: ${String(error.message)}` : "."}`; throw error; } }; export const findMintBySigHash = async ( network: EthereumConfig, provider: Provider, asset: string, nHash: Buffer, sigHash?: Buffer, blockLimit?: number, ): Promise<string | undefined> => { let status; try { const gatewayAddress = await getGatewayAddress( network, provider, asset, ); const statusABI: AbiItem = { constant: true, inputs: [ { internalType: "bytes32", name: "", type: "bytes32", }, ], name: "status", outputs: [ { internalType: "bool", name: "", type: "bool", }, ], payable: false, stateMutability: "view", type: "function", }; const gatewayContract = new ethers.Contract( gatewayAddress, [statusABI], provider, ); let fromBlock = 1; let toBlock: string | number = "latest"; if (blockLimit) { toBlock = new BigNumber( (await provider.getBlockNumber()).toString(), ).toNumber(); fromBlock = toBlock - blockLimit + 1; } const newMintEvents = await provider.getLogs({ address: gatewayAddress, fromBlock, toBlock, topics: [eventTopics.LogMint, null, null, Ox(nHash)] as string[], }); if (newMintEvents.length) { return newMintEvents[0].transactionHash; } if (sigHash) { // We can skip the `status` check and call `getPastLogs` directly - for now both are called in case // the contract status = await gatewayContract.status(Ox(sigHash)); if (!status) { return undefined; } const oldMintEvents = await provider.getLogs({ address: gatewayAddress, fromBlock, toBlock, topics: [ eventTopics.LogMint, null, null, Ox(sigHash), ] as string[], }); if (oldMintEvents.length) { return oldMintEvents[0].transactionHash; } } } catch (error) { console.warn(error); // Continue with transaction } if (status) { // The sigHash has already been used, but no transaction was found. // Possible due to a restriction on the number logs that can be fetched, // which is the case on BSC. return ""; } return; }; export const submitToEthereum = async ( signer: ethers.Signer, contractCalls: ContractCall[], mintTx: LockAndMintTransaction, eventEmitter: EventEmitterTyped<{ transactionHash: [string]; confirmation: [number, { status: number }]; }>, // config?: { [key: string]: unknown }, logger: Logger = NullLogger, ): Promise<EthTransaction> => { if (!mintTx.out) { throw new Error(`No result available from RenVM transaction.`); } if (mintTx.out.revert !== undefined) { throw new Error(`Unable to submit reverted RenVM transaction.`); } if (!mintTx.out.signature) { throw new Error(`No signature available from RenVM transaction.`); } let transaction: string | undefined; for (let i = 0; i < contractCalls.length; i++) { const contractCall = contractCalls[i]; const last = i === contractCalls.length - 1; const { contractParams, contractFn, sendTo } = contractCall; const callParams = last ? [ ...(contractParams || []).map((value) => value.value), Ox(new BigNumber(mintTx.out.amount).toString(16)), // _amount: BigNumber Ox(mintTx.out.nhash), Ox(mintTx.out.signature), // _sig: string ] : (contractParams || []).map((value) => value.value); const ABI = last ? payloadToMintABI(contractFn, contractParams || []) : payloadToABI(contractFn, contractParams || []); const contract = new ethers.Contract(sendTo, ABI, signer); const txConfig = typeof contractCall === "object" ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion (contractCall.txConfig as EthereumTransactionConfig) : {}; const config = { ...txConfig, ...{ value: txConfig && txConfig.value ? txConfig.value.toString() : undefined, gasPrice: txConfig && txConfig.gasPrice ? txConfig.gasPrice.toString() : undefined, }, // ...config, }; logger.debug( "Calling Ethereum contract", contractFn, sendTo, ...callParams, config, ); const tx = await contract[contractFn](...callParams, config); if (last) { eventEmitter.emit("transactionHash", tx.hash); } const receipt = await tx.wait(); if (last) { eventEmitter.emit("confirmation", 1, { status: 1 }); } transaction = receipt.transactionHash; if (logger) { logger.debug("Transaction hash", transaction); } } if (transaction === undefined) { throw new Error(`Must provide contract call.`); } return transaction; }; export const addressIsValid = (address: EthAddress): boolean => { if (/^.+\.eth$/.exec(address)) { return true; } try { ethers.utils.getAddress(address); return true; } catch (_error) { return false; } }; export const transactionIsValid = (transaction: EthTransaction): boolean => transaction !== null && isHex(transaction, { length: 32, prefix: true });
the_stack
import {BiMap} from 'bim' import {minBy} from 'lodash' import sleep from 'sleep-promise' import {FocalLength} from '..' import { Aperture, BatteryLevel, computeShutterSpeedSeconds, ConfigName, ExposureMode, ISO, WhiteBalance, } from '../configs' import {decodeIFD, IFDType} from '../IFD' import {ResCode} from '../PTPDatacode' import {PTPDataView} from '../PTPDataView' import { ConfigDesc, createReadonlyConfigDesc, OperationResult, OperationResultStatus, TakePhotoOption, } from '../Tethr' import {TethrObject} from '../TethrObject' import {isntNil} from '../util' import {TethrPTPUSB} from '.' enum OpCodeSigma { GetCamConfig = 0x9010, GetCamStatus = 0x9011, GetCamDataGroup1 = 0x9012, GetCamDataGroup2 = 0x9013, GetCamDataGroup3 = 0x9014, GetCamCaptStatus = 0x9015, SetCamDataGroup1 = 0x9016, SetCamDataGroup2 = 0x9017, SetCamDataGroup3 = 0x9018, SetCamClockAdj = 0x9019, GetCamCanSetInfo = 0x901a, SnapCommand = 0x901b, ClearImageDBSingle = 0x901c, ClearImageDBAll = 0x901d, GetPictFileInfo = 0x9020, GetPartialPictFile = 0x9021, GetBigPartialPictFile = 0x9022, GetCamDataGroup4 = 0x9023, // ver1.1 SetCamDataGroup4 = 0x9024, // ver1.1 GetCamCanSetInfo2 = 0x9025, // ver1.1 GetCamCanSetInfo3 = 0x9026, // ver1.2 GetCamDataGroup5 = 0x9027, // ver1.2 SetCamDataGroup5 = 0x9028, // ver1.2 GetCamDataGroup6 = 0x9029, // ver1.2 SetCamDataGroup6 = 0x902a, // ver1.2 GetViewFrame = 0x902b, // V21 GetCamCanSetInfo4 = 0x902e, // V21 GetCamStatus2 = 0x902c, GetPictFileInfo2 = 0x902d, CloseApplication = 0x902f, // V21 GetCamCanSetInfo5 = 0x9030, // V5 GetCamDataGroupFocus = 0x9031, // V5 SetCamDataGroupFocus = 0x9032, // V5 GetCamDataGroupMovie = 0x9033, // V5 SetCamDataGroupMovie = 0x9034, // V5 ConfigApi = 0x9035, // V5 GetMovieFileInfo = 0x9036, // V5 GetPartialMovieFile = 0x9037, // V5 } enum CaptStatus { runSnap = 0x0001, compSnap = 0x0002, runImageCreate = 0x0004, compImageCreate = 0x0005, compMovieStopStandby = 0x0006, compMovieCreate = 0x0007, okAf = 0x8001, okCwb = 0x8002, okImageSave = 0x8003, okNoerrorEtc = 0x8004, ngAf = 0x6001, ngBaffaFull = 0x6002, ngCwb = 0x6003, ngImageCreate = 0x6004, ngGeneral = 0x6005, } enum SnapCaptureMode { GeneralCapture = 0x01, NonAFCapture = 0x02, AFDriveOnly = 0x03, StartAF = 0x04, StopAF = 0x05, StartCapture = 0x06, StopCapture = 0x07, StartRecordingMovieWithAF = 0x10, StartRecordingMovieWithoutAF = 0x20, StopRecordingMovie = 0x30, } const ConfigListSigma: ConfigName[] = [ 'aperture', 'iso', 'colorTemperature', 'colorMode', 'exposureComp', 'exposureMode', 'imageAspect', 'imageQuality', 'imageSize', 'liveviewEnabled', 'liveviewMagnifyRatio', 'shutterSpeed', 'whiteBalance', ] export class TethrSigma extends TethrPTPUSB { private liveviewEnabled = false public async open() { await super.open() await this.device.receiveData({ label: 'SigmaFP ConfigApi', opcode: OpCodeSigma.ConfigApi, parameters: [0x0], }) } public async getAperture(): Promise<Aperture | null> { const {aperture} = await this.getCamDataGroup1() if (aperture === 0x0) return 'auto' return ( this.apertureOneThirdTable.get(aperture) ?? this.apertureHalfTable.get(aperture) ?? null ) } public async setAperture(aperture: Aperture): Promise<OperationResult<void>> { if (aperture === 'auto') return {status: 'invalid parameter'} const byte = this.apertureOneThirdTable.getKey(aperture) if (!byte) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup1, 1, byte) } public async getApertureDesc() { const fValue = (await this.getCamCanSetInfo5()).fValue const value = await this.getAperture() if (fValue.length === 0) { // Should be auto aperture return { writable: false, value, } } const [svMin, svMax, step] = fValue const isStepOneThird = Math.abs(step - 1 / 3) < Math.abs(step - 1 / 2) const table = isStepOneThird ? this.apertureOneThirdTable : this.apertureHalfTable const apertures = Array.from(table.values()) const fMinRaw = Math.sqrt(2 ** svMin) const fMaxRaw = Math.sqrt(2 ** svMax) const fMin = minBy(apertures, a => Math.abs(a - fMinRaw)) const fMax = minBy(apertures, a => Math.abs(a - fMaxRaw)) if (!fMin || !fMax) throw new Error() const values = apertures.filter(a => fMin <= a && a <= fMax) return { writable: true, value, option: { type: 'enum', values, }, } as ConfigDesc<Aperture> } public async getBatteryLevelDesc(): Promise<ConfigDesc<BatteryLevel>> { const {batteryLevel} = await this.getCamDataGroup1() const value = this.batteryLevelTable.get(batteryLevel) ?? null return { writable: false, value, } } public async getCanTakePhotoDesc() { return createReadonlyConfigDesc(true) } public async getCanRunAutoFocusDesc() { return createReadonlyConfigDesc(true) } public async getCanStartLiveviewDesc() { return createReadonlyConfigDesc(true) } public async setColorMode(colorMode: string): Promise<OperationResult<void>> { const id = this.colorModeTable.getKey(colorMode) if (id === undefined) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup3, 4, id) } public async getColorModeDesc(): Promise<ConfigDesc<string>> { const decodeColorMode = (id: number) => { return this.colorModeTable.get(id) ?? 'Unknown' } const {colorMode} = await this.getCamDataGroup3() const {colorMode: colorModeOptions} = await this.getCamCanSetInfo5() return { writable: colorModeOptions.length > 0, value: decodeColorMode(colorMode), option: { type: 'enum', values: colorModeOptions.map(decodeColorMode), }, } } public async getColorTemperature() { const wb = await this.getWhiteBalance() if (wb !== 'manual') return null const {colorTemperature} = await this.getCamDataGroup5() return colorTemperature } public async setColorTemperature(value: number) { const r0 = await this.setCamData(OpCodeSigma.SetCamDataGroup2, 13, 0x0e) const r1 = await this.setCamData(OpCodeSigma.SetCamDataGroup5, 1, value) const status: OperationResultStatus = r0.status === 'ok' && r1.status === 'ok' ? 'ok' : 'general error' return {status} } public async getColorTemperatureDesc() { const {colorTemerature} = await this.getCamCanSetInfo5() const value = await this.getColorTemperature() if (colorTemerature.length !== 3) { // When WB is not set to 'manual' return { writable: false, value, } } const [min, max, step] = colorTemerature return { writable: true, value, option: { type: 'range', min, max, step, }, } as ConfigDesc<number> } public async getExposureMode() { const {exposureMode} = await this.getCamDataGroup2() return this.exposureModeTable.get(exposureMode) ?? null } public async setExposureMode( exposureMode: ExposureMode ): Promise<OperationResult<void>> { const id = this.exposureModeTable.getKey(exposureMode) if (!id) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup2, 2, id) } public async getExposureModeDesc(): Promise<ConfigDesc<ExposureMode>> { const {exposureMode} = await this.getCamCanSetInfo5() const value = await this.getExposureMode() const values = exposureMode .map(n => this.exposureModeTable.get(n)) .filter(isntNil) return { writable: values.length > 0, value, option: { type: 'enum', values, }, } } public async getExposureComp() { const {exposureComp} = await this.getCamDataGroup1() return this.compensationOneThirdTable.get(exposureComp) ?? null } public async setExposureComp(value: string): Promise<OperationResult<void>> { const id = this.compensationOneThirdTable.getKey(value) if (id === undefined) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup1, 5, id) } public async getExposureCompDesc(): Promise<ConfigDesc<string>> { const {exposureComp} = await this.getCamCanSetInfo5() const value = await this.getExposureComp() if (exposureComp.length < 3) { return { writable: false, value, } } const [min, max] = exposureComp const allValues = [...this.compensationOneThirdTable.values()] const values = allValues .map(v => [v, decodeExposureComp(v)] as [string, number]) .sort((a, b) => a[1] - b[1]) .filter(([, n]) => min - 1e-4 <= n && n <= max + 1e-4) .map(([v]) => v) return { writable: exposureComp.length > 0, value, option: { type: 'enum', values, }, } function decodeExposureComp(v: string) { if (v === '0') return 0x0 let negative = false, digits = 0, thirds = 0 const match1 = v.match(/^([+-]?)([0-9]+)( 1\/3| 2\/3)?$/) if (match1) { negative = match1[1] === '-' digits = parseInt(match1[2]) thirds = !match1[3] ? 0 : match1[3] === ' 1/3' ? 1 : 2 } const match2 = !match1 && v.match(/^([+-]?)(1\/3|2\/3)$/) if (match2) { negative = match2[1] === '-' thirds = match2[2] === '1/3' ? 1 : 2 } if (!match1 && !match2) return null return (negative ? -1 : 1) * (digits + thirds / 3) } } public async getFocalLengthDesc() { const {currentLensFocalLength} = await this.getCamDataGroup1() const value = decodeFocalLength(currentLensFocalLength) const {lensWideFocalLength, lensTeleFocalLength} = await this.getCamDataGroup3() const min = decodeFocalLength(lensWideFocalLength) const max = decodeFocalLength(lensTeleFocalLength) return { writable: false, value, option: { type: 'range', min, max, step: 0, }, } as ConfigDesc<FocalLength> function decodeFocalLength(byte: number) { const integer = byte >> 4, fractional = byte & 0b1111 return integer + fractional / 10 } } public async getImageAspect() { const {imageAspect} = await this.getCamDataGroup5() const id = imageAspect - 245 // Magic number return this.imageAspectTable.get(id) ?? null } public async setImageAspect( imageAspect: string ): Promise<OperationResult<void>> { const id = this.imageAspectTable.getKey(imageAspect) if (id === undefined) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup5, 3, id) } public async getImageAspectDesc(): Promise<ConfigDesc<string>> { const decodeImageAspectIFD = (id: number) => { return this.imageAspectTableIFD.get(id) ?? 'Unknown' } const {imageAspect: values} = await this.getCamCanSetInfo5() const value = await this.getImageAspect() return { writable: values.length > 0, value, option: { type: 'enum', values: values.map(decodeImageAspectIFD), }, } } public async setImageQuality( imageQuality: string ): Promise<OperationResult<void>> { let jpegQuality: string | null = null let dngBitDepth: number | null = null const hasDngMatch = imageQuality.match(/^raw (12|14)bit(?:,([a-z]+))?/i) if (hasDngMatch) { const [, dngBitDepthStr, jpegQualityStr] = hasDngMatch jpegQuality = jpegQualityStr ?? null dngBitDepth = parseInt(dngBitDepthStr) } else { jpegQuality = imageQuality } // Generate imageQuality value for setCamData let imageQualityID switch (jpegQuality) { case null: imageQualityID = 0x00 break case 'fine': imageQualityID = 0x02 break case 'standard': imageQualityID = 0x04 break case 'low': imageQualityID = 0x08 break default: return {status: 'invalid parameter'} } imageQualityID |= dngBitDepth === null ? 0x00 : 0x10 const setImageQualityResult = ( await this.setCamData(OpCodeSigma.SetCamDataGroup2, 15, imageQualityID) ).status let setDngBitDepthResult: OperationResultStatus = 'ok' if (dngBitDepth !== null) { setDngBitDepthResult = ( await this.setCamData(OpCodeSigma.SetCamDataGroup4, 9, dngBitDepth) ).status } if (setImageQualityResult === 'ok' && setDngBitDepthResult === 'ok') { return {status: 'ok'} } else { return {status: 'invalid parameter'} } } public async getImageQualityDesc() { type ImageQualityConfig = { jpegQuality: string | null hasDNG: boolean } const imageQuality: ImageQualityConfig = await (async () => { const {imageQuality} = await this.getCamDataGroup2() let jpegQuality: string | null = null switch (imageQuality & 0x0f) { case 0x02: jpegQuality = 'fine' break case 0x04: jpegQuality = 'standard' break case 0x08: jpegQuality = 'low' break } const hasDNG = !!(imageQuality & 0x10) return { jpegQuality, hasDNG, } })() const dngBitDepth = await (async () => { const {dngImageQuality} = await this.getCamDataGroup4() return dngImageQuality })() return { writable: true, value: stringifyImageQuality(imageQuality, dngBitDepth), option: { type: 'enum', values: [ // NOTE: Hard-coded so this might not work for some cases 'low', 'standard', 'fine', 'raw 12bit,fine', 'raw 14bit,fine', 'raw 12bit', 'raw 14bit', ], }, } as ConfigDesc<string> function stringifyImageQuality( quality: ImageQualityConfig, dngBitDepth: number ) { if (quality.hasDNG) { if (quality.jpegQuality) { return `raw ${dngBitDepth}bit,${quality.jpegQuality}` } else { return `raw ${dngBitDepth}bit` } } else { if (quality.jpegQuality) { return quality.jpegQuality } else { throw new Error('Invalid ImageQualityConfig') } } } } public async setImageSize(imageSize: string): Promise<OperationResult<void>> { const id = this.imageSizeTable.getKey(imageSize) if (id === undefined) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup2, 14, id) } public async getImageSizeDesc(): Promise<ConfigDesc<string>> { const {resolution} = await this.getCamDataGroup2() const value = this.imageSizeTable.get(resolution) if (!value) { return { writable: false, value: null, } } return { writable: true, value, option: { type: 'enum', values: ['low', 'medium', 'high'], }, } } public async getIso() { const {isoAuto, isoSpeed} = await this.getCamDataGroup1() if (isoAuto === 0x01) { return 'auto' } else { return this.isoTable.get(isoSpeed) ?? null } } public async setIso(iso: ISO): Promise<OperationResult<void>> { if (iso === 'auto') { return this.setCamData(OpCodeSigma.SetCamDataGroup1, 3, 0x1) } const id = this.isoTable.getKey(iso) if (!id) return {status: 'invalid parameter'} const setISOAutoResult = await this.setCamData( OpCodeSigma.SetCamDataGroup1, 3, 0x0 ) const setISOValueResult = await this.setCamData( OpCodeSigma.SetCamDataGroup1, 4, id ) if (setISOAutoResult.status === 'ok' && setISOValueResult.status === 'ok') { return {status: 'ok'} } else { return {status: 'invalid parameter'} } } public async getIsoDesc(): Promise<ConfigDesc<ISO>> { const {isoManual} = await this.getCamCanSetInfo5() const value = await this.getIso() const [svMin, svMax] = isoManual const isoMin = Math.round(3.125 * 2 ** svMin) const isoMax = Math.round(3.125 * 2 ** svMax) const isos = [...this.isoTable.values()] const values = isos.filter(a => isoMin <= a && a <= isoMax) values.unshift('auto') return { writable: true, value, option: { type: 'enum', values, }, } } public async getLiveviewEnabledDesc(): Promise<ConfigDesc<boolean>> { return { writable: false, value: this.liveviewEnabled, } } public async setLiveviewMagnifyLevelRatio( value: number ): Promise<OperationResult<void>> { const id = this.liveviewMagnifyRatioTable.getKey(value) if (!id) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup4, 5, id) } public async getLiveviewMagnifyLevelRatioDesc() { const {lvMagnifyRatio} = await this.getCamDataGroup4() const value = this.liveviewMagnifyRatioTable.get(lvMagnifyRatio) ?? null const {lvMagnifyRatio: values} = await this.getCamCanSetInfo5() return { writable: values.length > 0, value, option: { type: 'enum', values, }, } } public async getShutterSpeed() { const {shutterSpeed} = await this.getCamDataGroup1() if (shutterSpeed === 0x0) return 'auto' return ( this.shutterSpeedOneThirdTable.get(shutterSpeed) ?? this.shutterSpeedHalfTable.get(shutterSpeed) ?? null ) } public async setShutterSpeed(ss: string): Promise<OperationResult<void>> { const byte = this.shutterSpeedOneThirdTable.getKey(ss) if (!byte) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup1, 0, byte) } public async getShutterSpeedDesc() { const range = (await this.getCamCanSetInfo5()).shutterSpeed const value = await this.getShutterSpeed() if (range.length < 3) { return { writable: false, value, } } const [tvMin, tvMax, step] = range const isStepOneThird = Math.abs(step - 1 / 3) < Math.abs(step - 1 / 2) const table = isStepOneThird ? this.shutterSpeedOneThirdTable : this.shutterSpeedHalfTable const shutterSpeeds = Array.from(table.entries()).filter( e => e[1] !== 'sync' && e[1] !== 'bulb' ) const ssMinRaw = 1 / 2 ** tvMin const ssMaxRaw = 1 / 2 ** tvMax const ssMinEntry = minBy(shutterSpeeds, e => Math.abs(computeShutterSpeedSeconds(e[1]) - ssMinRaw) ) const ssMaxEntry = minBy(shutterSpeeds, e => Math.abs(computeShutterSpeedSeconds(e[1]) - ssMaxRaw) ) if (!ssMinEntry || !ssMaxEntry) throw new Error() const ssMinIndex = ssMinEntry[0] const ssMaxIndex = ssMaxEntry[0] const values = shutterSpeeds .filter(e => ssMinIndex <= e[0] && e[0] <= ssMaxIndex) .map(e => e[1]) return { writable: values.length > 0, value, option: { type: 'enum', values, }, } as ConfigDesc<string> } public async getWhiteBalance() { const {whiteBalance} = await this.getCamDataGroup2() return this.whiteBalanceTable.get(whiteBalance) ?? null } public async setWhiteBalance( wb: WhiteBalance ): Promise<OperationResult<void>> { const id = this.whiteBalanceTable.getKey(wb) if (!id) return {status: 'invalid parameter'} return this.setCamData(OpCodeSigma.SetCamDataGroup2, 13, id) } public async getWhiteBalanceDesc(): Promise<ConfigDesc<WhiteBalance>> { const {whiteBalance} = await this.getCamCanSetInfo5() const value = await this.getWhiteBalance() const values = whiteBalance .map(v => this.whiteBalanceTableIFD.get(v)) .filter(isntNil) return { writable: values.length > 0, value, option: { type: 'enum', values, }, } } // Actions public async takePhoto({download = true}: TakePhotoOption = {}): Promise< OperationResult<TethrObject[]> > { const captId = await this.executeSnapCommand( SnapCaptureMode.NonAFCapture, 2 ) if (captId === null) return {status: 'general error'} if (!download) { await this.clearImageDBSingle(captId) return {status: 'ok', value: []} } const pictInfos = await this.getPictFileInfo2() const getAllPictPromises = pictInfos.map(async info => { // Get file buffer const {data} = await this.device.receiveData({ label: 'SigmaFP GetBigPartialPictFile', opcode: OpCodeSigma.GetBigPartialPictFile, parameters: [info.fileAddress, 0x0, info.fileSize], maxByteLength: info.fileSize + 1000, }) // First 4 bytes seems to be buffer length so splice it const jpegData = data.slice(4) const isRaw = /dng/i.test(info.fileExt) const format = isRaw ? 'raw' : 'jpeg' const type = isRaw ? 'image/x-adobe-dng' : 'image/jpeg' const blob = new Blob([jpegData], {type}) return { format, blob, } as TethrObject }) await this.clearImageDBSingle(captId) const picts = await Promise.all(getAllPictPromises) return {status: 'ok', value: picts} } public async runAutoFocus(): Promise<OperationResult<void>> { const captId = await this.executeSnapCommand(SnapCaptureMode.StartAF) if (captId !== null) { await this.clearImageDBSingle(captId) return {status: 'ok'} } else { return {status: 'general error'} } } public async startLiveview(): Promise<OperationResult<MediaStream>> { const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') if (!ctx) return {status: 'general error'} this.liveviewEnabled = true this.emit('liveviewEnabledChanged', await this.getDesc('liveviewEnabled')) const updateFrame = async () => { if (!this.liveviewEnabled) return try { const {resCode, data} = await this.device.receiveData({ label: 'SigmaFP GetViewFrame', opcode: OpCodeSigma.GetViewFrame, expectedResCodes: [ResCode.OK, ResCode.DeviceBusy], maxByteLength: 1_000_000, // = 1MB }) if (resCode !== ResCode.OK) return null // Might be quirky but somehow works const jpegData = data.slice(10) const image = new Blob([jpegData], {type: 'image/jpg'}) const imageBitmap = await createImageBitmap(image) const sizeChanged = canvas.width !== imageBitmap.width || canvas.height !== imageBitmap.height if (sizeChanged) { canvas.width = imageBitmap.width canvas.height = imageBitmap.height } ctx.drawImage(imageBitmap, 0, 0) } finally { requestAnimationFrame(updateFrame) } } updateFrame() const stream = canvas.captureStream(60) return {status: 'ok', value: stream} } public async stopLiveview(): Promise<OperationResult<void>> { this.liveviewEnabled = false this.emit('liveviewEnabledChanged', await this.getDesc('liveviewEnabled')) return {status: 'ok'} } private async getCamDataGroup1() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamDataGroup1', opcode: OpCodeSigma.GetCamDataGroup1, parameters: [0x0], }) const dataView = new PTPDataView(data) dataView.skip(3) // OC + FieldPreset return { shutterSpeed: dataView.readUint8(), aperture: dataView.readUint8(), programShift: dataView.readInt8(), isoAuto: dataView.readUint8(), isoSpeed: dataView.readUint8(), exposureComp: dataView.readUint8(), abValue: dataView.readUint8(), abSettings: dataView.readUint8(), frameBufferState: dataView.readUint8(), mediaFreeSpace: dataView.readUint16(), mediaStatus: dataView.readUint8(), currentLensFocalLength: dataView.readUint16(), batteryLevel: dataView.readUint8(), abShotRemainNumber: dataView.readUint8(), expCompExcludeAB: dataView.readUint8(), } } private async getCamDataGroup2() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamDataGroup2', opcode: OpCodeSigma.GetCamDataGroup2, parameters: [0x0], }) const dataView = new PTPDataView(data) dataView.skip(3) // OC + FieldPreset return { driveMode: dataView.readUint8(), specialMode: dataView.readUint8(), exposureMode: dataView.readUint8(), aeMeteringMode: dataView.readUint8(), whiteBalance: dataView.goto(3 + 10).readUint8(), resolution: dataView.readUint8(), imageQuality: dataView.readUint8(), } } private async getCamDataGroup3() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamDataGroup3', opcode: OpCodeSigma.GetCamDataGroup3, parameters: [0x0], }) const dataView = new PTPDataView(data) dataView.skip(3) // OC + FieldPreset return { colorSpace: dataView.skip(3).readUint8(), colorMode: dataView.readUint8(), batteryKind: dataView.readUint8(), lensWideFocalLength: dataView.readUint16(), lensTeleFocalLength: dataView.readUint16(), afAuxiliaryLight: dataView.readUint8(), afBeep: dataView.readUint8(), timerSound: dataView.readUint8(), destinationToSave: dataView.skip(1).readUint8(), } } private async getCamDataGroup4() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamDataGroup4', opcode: OpCodeSigma.GetCamDataGroup4, parameters: [0x0], }) const dataView = new PTPDataView(data) dataView.skip(3) // OC + FieldPreset return { dcCropMode: dataView.readUint8(), lvMagnifyRatio: dataView.readUint8(), isoExtension: dataView.readUint8(), continuousShootingSpeed: dataView.readUint8(), hdr: dataView.readUint8(), dngImageQuality: dataView.readUint8(), fillLight: dataView.readUint8(), } } private async getCamDataGroup5() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamDataGroup5', opcode: OpCodeSigma.GetCamDataGroup5, parameters: [0x0], }) const dataView = new PTPDataView(data) dataView.skip(3) // OC + FieldPreset return { intervalTimerSecond: dataView.readUint16(), intervalTimerFame: dataView.readUint8(), intervalTimerSecond_Remain: dataView.readUint16(), intervalTimerFrame_Remain: dataView.readUint8(), colorTemperature: dataView.readUint16(), imageAspect: dataView.skip(2).readUint8(), } } private async getCamCanSetInfo5() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamCanSetInfo5', opcode: OpCodeSigma.GetCamCanSetInfo5, parameters: [0x0], }) return decodeIFD(data, { imageQuality: {tag: 11, type: IFDType.Byte}, dngImageQuality: {tag: 12, type: IFDType.Byte}, imageAspect: {tag: 21, type: IFDType.Byte}, exposureMode: {tag: 200, type: IFDType.Byte}, fValue: {tag: 210, type: IFDType.SignedShort}, shutterSpeed: {tag: 212, type: IFDType.SignedShort}, isoManual: {tag: 215, type: IFDType.SignedShort}, exposureComp: {tag: 217, type: IFDType.SignedShort}, whiteBalance: {tag: 301, type: IFDType.Byte}, colorTemerature: {tag: 302, type: IFDType.Short}, colorMode: {tag: 320, type: IFDType.Byte}, lvMagnifyRatio: {tag: 701, type: IFDType.Byte}, }) } private async getCamDataGroupFocus() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamDataGroupFocus', opcode: OpCodeSigma.GetCamDataGroupFocus, parameters: [0x0], }) return decodeIFD(data, { focusMode: {tag: 1, type: IFDType.Byte}, afLock: {tag: 2, type: IFDType.Byte}, afFaceEyePriorMode: {tag: 3, type: IFDType.Byte}, afFaceEyePriorDetectionStatus: {tag: 4, type: IFDType.Byte}, afAreaSelect: {tag: 10, type: IFDType.Byte}, afAreaMode: {tag: 11, type: IFDType.Byte}, afFrameSize: {tag: 12, type: IFDType.Byte}, // afFramePosition: {tag: 13, type: IFDType.Byte}, // afFrameFaceFocusDetection: {tag: 14, type: IFDType.Byte}, preAlwaysAf: {tag: 51, type: IFDType.Byte}, afLimit: {tag: 52, type: IFDType.Byte}, }) } private async setCamData( opcode: number, devicePropIndex: number, value: number ): Promise<OperationResult<void>> { const dataView = new PTPDataView() dataView.writeUint16(1 << devicePropIndex) dataView.writeUint16(value) const data = this.encodeParameter(dataView.toBuffer()) try { await this.device.sendData({ label: 'SigmaFP SetCamDataGroup#', opcode, data, }) } catch (err) { return {status: 'invalid parameter'} } await this.emitAllConfigChangedEvents() return {status: 'ok'} } private async getCamCaptStatus(imageId = 0) { const {data} = await this.device.receiveData({ label: 'SigmaFP GetCamCaptStatus', opcode: OpCodeSigma.GetCamCaptStatus, parameters: [imageId], }) const dataView = new PTPDataView(data.slice(1)) const status = { imageId: dataView.readUint8(), imageDBHead: dataView.readUint8(), imageDBTail: dataView.readUint8(), status: dataView.readUint16(), destination: dataView.readUint8(), } return status } /** * * @returns Capture ID if the command execution has succeed, otherwise null */ private async executeSnapCommand( captureMode: number, captureAmount = 1 ): Promise<number | null> { const {imageDBTail: captId} = await this.getCamCaptStatus() const snapState = new Uint8Array([captureMode, captureAmount]).buffer await this.device.sendData({ label: 'Sigma SnapCommand', opcode: OpCodeSigma.SnapCommand, data: this.encodeParameter(snapState), }) for (let restTries = 50; restTries > 0; restTries--) { const {status} = await this.getCamCaptStatus(captId) const isFailure = (status & 0xf000) === 0x6000 if (isFailure) return null const isSucceed = (status & 0xf000) === 0x8000 if (isSucceed) return captId if (status === CaptStatus.compImageCreate) return captId await sleep(500) } return null } private async clearImageDBSingle(captId: number) { await this.device.sendData({ label: 'SigmaFP ClearImageDBSingle', opcode: OpCodeSigma.ClearImageDBSingle, parameters: [captId], data: new ArrayBuffer(8), }) } private async clearImageDBAll() { await this.device.sendData({ label: 'SigmaFP ClearImageDBAll', opcode: OpCodeSigma.ClearImageDBAll, data: new ArrayBuffer(8), }) } private async getPictFileInfo2() { const {data} = await this.device.receiveData({ label: 'SigmaFP GetPictFileInfo2', opcode: 0x902d, }) const dataView = new PTPDataView(data) dataView.skip(4) // Packet Size const byteOffsets = dataView.readUint32Array() const pictInfos = byteOffsets.map(offset => { dataView.goto(offset) return { fileAddress: dataView.readUint32(), fileSize: dataView.readUint32(), fileExt: dataView.skip(8).readAsciiString(), folderName: dataView.skip(4).readAsciiString(), fileName: dataView.readAsciiString(), } }) return pictInfos } private async emitAllConfigChangedEvents() { for await (const config of ConfigListSigma) { const desc = await this.getDesc(config) this.emit(`${config}Changed`, desc) } } private encodeParameter(buffer: ArrayBuffer) { const bytes = new Uint8Array(buffer) const size = buffer.byteLength const encodedBuffer = new ArrayBuffer(size + 2) const encodedBytes = new Uint8Array(encodedBuffer) // Set size at the first byte encodedBytes[0] = size // Insert the content for (let i = 0; i < size; i++) { encodedBytes[1 + i] = bytes[i] } // Add checksum on the last let checksum = 0 for (let i = 0; i <= size; i++) { checksum += encodedBytes[i] } encodedBytes[size + 1] = checksum return encodedBuffer } private colorModeTable = new BiMap<number, string>([ [0x00, 'normal'], [0x01, 'sepia'], [0x02, 'bw'], [0x03, 'standard'], [0x04, 'vivid'], [0x05, 'neutral'], [0x06, 'portrait'], [0x07, 'landscape'], [0x08, 'fov classic blue'], [0x09, 'sunset red'], [0x0a, 'forest'], [0x0b, 'cinema'], [0x0c, 'fov classic yellow'], [0x0d, 'teal and orange'], [0x0e, 'off'], [0x0f, 'powder blue'], ]) private imageAspectTable = new BiMap<number, string>([ [1, '21:9'], [2, '16:9'], [3, '3:2'], [4, '4:3'], [5, '7:6'], [6, '1:1'], [7, 'a size'], ]) private imageAspectTableIFD = new BiMap<number, string>([ [1, '21:9'], [2, '16:9'], [3, '3:2'], [4, 'a size'], [5, '4:3'], [6, '7:6'], [7, '1:1'], ]) private isoTable = new BiMap<number, ISO>([ [0b00000000, 6], [0b00000011, 8], [0b00000101, 10], [0b00001000, 12], [0b00001011, 16], [0b00001101, 20], [0b00010000, 25], [0b00010011, 32], [0b00010101, 40], [0b00011000, 50], [0b00011011, 64], [0b00011101, 80], [0b00100000, 100], [0b00100011, 125], [0b00100101, 160], [0b00101000, 200], [0b00101011, 250], [0b00101101, 320], [0b00110000, 400], [0b00110011, 500], [0b00110101, 640], [0b00111000, 800], [0b00111011, 1000], [0b00111101, 1250], [0b01000000, 1600], [0b01000011, 2000], [0b01000101, 2500], [0b01001000, 3200], [0b01001011, 4000], [0b01001101, 5000], [0b01010000, 6400], [0b01010011, 8000], [0b01010101, 10000], [0b01011000, 12800], [0b01011011, 16000], [0b01011101, 20000], [0b01100000, 25600], [0b01100011, 32000], [0b01100101, 40000], [0b01101000, 51200], [0b01101011, 64000], [0b01101101, 80000], [0b01110000, 102400], ]) private compensationOneThirdTable = new BiMap<number, string>([ [0b00000000, '0'], [0b00000011, '+1/3'], [0b00000101, '+2/3'], [0b00001000, '+1'], [0b00001011, '+1 1/3'], [0b00001110, '+1 2/3'], [0b00010000, '+2'], [0b00010011, '+2 1/3'], [0b00010101, '+2 2/3'], [0b00011000, '+3'], [0b00011011, '+3 1/3'], [0b00011101, '+3 2/3'], [0b00100000, '+4'], [0b00100011, '+4 1/3'], [0b00100101, '+4 2/3'], [0b00101000, '+5'], [0b00101011, '+5 1/3'], [0b00101101, '+5 2/3'], [0b00110000, '+6'], [0b00110011, '+6 1/3'], [0b11001101, '-6 1/3'], [0b11010000, '-6'], [0b11010011, '-5 2/3'], [0b11010101, '-5 1/3'], [0b11011000, '-5'], [0b11011011, '-4 2/3'], [0b11011101, '-4 1/3'], [0b11100000, '-4'], [0b11100011, '-3 2/3'], [0b11100101, '-3 1/3'], [0b11101000, '-3'], [0b11101011, '-2 2/3'], [0b11101101, '-2 1/3'], [0b11110000, '-2'], [0b11110011, '-1 2/3'], [0b11110101, '-1 1/3'], [0b11111000, '-1'], [0b11111011, '-2/3'], [0b11111101, '-1/3'], ]) private shutterSpeedOneThirdTable = new BiMap<number, string>([ [0b00001000, 'bulb'], [0b00010000, '30'], [0b00010011, '25'], [0b00010101, '20'], [0b00011000, '15'], [0b00011011, '13'], [0b00011101, '10'], [0b00100000, '8'], [0b00100011, '6'], [0b00100101, '5'], [0b00101000, '4'], [0b00101011, '3.2'], [0b00101101, '2.5'], [0b00110000, '2'], [0b00110011, '1.6'], [0b00110101, '1.3'], [0b00111000, '1'], [0b00111011, '0.8'], [0b00111101, '0.6'], [0b01000000, '0.5'], [0b01000011, '0.4'], [0b01000101, '0.3'], [0b01001000, '1/4'], [0b01001011, '1/5'], [0b01001101, '1/6'], [0b01010000, '1/8'], [0b01010011, '1/10'], [0b01010101, '1/13'], [0b01011000, '1/15'], [0b01011011, '1/20'], [0b01011101, '1/25'], [0b01100000, '1/30'], [0b01100011, '1/40'], [0b01100101, '1/50'], [0b01101000, '1/60'], [0b01101011, '1/80'], [0b01101101, '1/100'], [0b01110000, '1/125'], [0b01110011, '1/160'], [0b01110100, '1/180'], [0b01110101, '1/200'], [0b01111000, '1/250'], [0b01111011, '1/320'], [0b01111100, '1/350'], [0b01111101, '1/400'], [0b10000000, '1/500'], [0b10000011, '1/640'], [0b10000100, '1/750'], [0b10000101, '1/800'], [0b10001000, '1/1000'], [0b10001011, '1/1250'], [0b10001100, '1/1500'], [0b10001101, '1/1600'], [0b10010000, '1/2000'], [0b10010011, '1/2500'], [0b10010100, '1/3000'], [0b10010101, '1/3200'], [0b10011000, '1/4000'], [0b10011011, '1/5000'], [0b10011100, '1/6000'], [0b10011101, '1/6000'], [0b10100000, '1/8000'], [0b10100010, 'sync'], [0b10100011, '1/10000'], [0b10100101, '1/12800'], [0b10101000, '1/16000'], [0b10101011, '1/20000'], [0b10101101, '1/25600'], [0b10110000, '1/32000'], ]) private shutterSpeedHalfTable = new BiMap<number, string>([ [0b00001000, 'bulb'], [0b00010001, '30'], [0b00010100, '20'], [0b00011000, '15'], [0b00011100, '10'], [0b00100000, '8'], [0b00100100, '6'], [0b00101000, '4'], [0b00101100, '3'], [0b00110000, '2'], [0b00110100, '1.5'], [0b00111000, '1'], [0b00111100, '0.7'], [0b01000000, '1/2'], [0b01000100, '1/3'], [0b01001000, '1/4'], [0b01001100, '1/6'], [0b01010000, '1/8'], [0b01010100, '1/10'], [0b01011000, '1/15'], [0b01011100, '1/20'], [0b01100000, '1/30'], [0b01100100, '1/45'], [0b01101000, '1/60'], [0b01101100, '1/90'], [0b01110000, '1/125'], [0b01111000, '1/250'], [0b10000000, '1/500'], [0b10001000, '1/1000'], [0b10010000, '1/2000'], [0b10011000, '1/4000'], [0b10100000, '1/8000'], [0b10100010, 'sync'], [0b10101000, '1/16000'], [0b10110000, '1/32000'], ]) private apertureOneThirdTable = new BiMap<number, number>([ [0b00001000, 1.0], [0b00001011, 1.1], [0b00001101, 1.2], [0b00010000, 1.4], [0b00010011, 1.6], [0b00010101, 1.8], [0b00011000, 2.0], [0b00011011, 2.2], [0b00011101, 2.5], [0b00100000, 2.8], [0b00100011, 3.2], [0b00100101, 3.5], [0b00101000, 4.0], [0b00101011, 4.5], [0b00101101, 5.0], [0b00110000, 5.6], [0b00110011, 6.3], [0b00110101, 7.1], [0b00111000, 8.0], [0b00111011, 9.0], [0b00111101, 10], [0b01000000, 11], [0b01000011, 13], [0b01000101, 14], [0b01001000, 16], [0b01001011, 18], [0b01001101, 20], [0b01010000, 22], [0b01010011, 25], [0b01010101, 29], [0b01011000, 32], [0b01011011, 36], [0b01011101, 40], [0b01100000, 45], [0b01100011, 51], [0b01100101, 57], [0b01101000, 64], [0b01101011, 72], [0b01101101, 81], [0b01110000, 91], ]) private apertureHalfTable = new BiMap<number, number>([ [0b00001000, 1.0], [0b00001100, 1.2], [0b00010000, 1.4], [0b00010100, 1.8], [0b00011000, 2.0], [0b00011100, 2.5], [0b00100000, 2.8], [0b00100100, 3.5], [0b00101000, 4.0], [0b00101100, 4.5], [0b00110000, 5.6], [0b00110100, 6.7], [0b00111000, 8.0], [0b00111100, 9.5], [0b01000000, 11], [0b01000100, 13], [0b01001000, 16], [0b01001100, 19], [0b01010000, 22], [0b01010100, 27], [0b01011000, 32], [0b01011100, 38], [0b01100000, 45], [0b01100100, 54], [0b01101000, 64], [0b01101100, 76], [0b01110000, 91], ]) protected exposureModeTable = new BiMap<number, ExposureMode>([ [0x1, 'P'], [0x2, 'A'], [0x3, 'S'], [0x4, 'M'], ]) protected liveviewMagnifyRatioTable = new BiMap<number, number>([ [0x1, 1], [0x2, 4], [0x3, 8], ]) private batteryLevelTable = new Map<number, null | BatteryLevel>([ [0x00, null], [0x01, 100], [0x02, 66], [0x03, 33], [0x04, 'low'], [0x05, 0], [0x06, null], [0x07, 0], [0x08, 'ac'], [0x09, null], [0x0a, 80], [0x0b, 60], [0x0c, null], ]) private whiteBalanceTable = new BiMap<number, WhiteBalance>([ [0x01, 'auto'], [0x02, 'daylight'], // Sunlight [0x03, 'shade'], [0x04, 'cloud'], // Overcast [0x05, 'incandescent'], [0x06, 'fluorescent'], [0x07, 'flash'], [0x08, 'custom'], // Custom 1 // [0x09, null], // CustomCapture 1 [0x0a, 'custom2'], // Custom 2 // [0x0b, null], // CustomCapture 2 [0x0c, 'custom3'], // Custom 3 // // [0x0d, null], // CustomCapture 3 [0x0e, 'manual'], // Custom Temperature [0x0f, 'auto ambience'], // Auto (Light Source Priority) ]) private whiteBalanceTableIFD = new Map<number, WhiteBalance>([ [0x1, 'auto'], [0x2, 'auto ambience'], [0x3, 'daylight'], [0x4, 'shade'], [0x5, 'tungsten'], [0x6, 'fluorescent'], [0x7, 'flash'], [0x8, 'manual'], ]) private imageSizeTable = new BiMap<number, string>([ [0x1, 'high'], [0x3, 'medium'], [0x4, 'low'], ]) }
the_stack
import Dom from '../dom'; import Listeners from './listeners'; import Flipper from '../flipper'; import SearchInput from './search-input'; import EventsDispatcher from './events'; import { isMobileScreen, keyCodes, cacheable } from '../utils'; import ScrollLocker from './scroll-locker'; /** * Describe parameters for rendering the single item of Popover */ export interface PopoverItem { /** * Item icon to be appeared near a title */ icon: string; /** * Displayed text */ label: string; /** * Item name * Used in data attributes needed for cypress tests */ name?: string; /** * Additional displayed text */ secondaryLabel?: string; /** * Itm click handler * * @param item - clicked item */ onClick: (item: PopoverItem) => void; } /** * Event that can be triggered by the Popover */ export enum PopoverEvent { /** * When popover overlay is clicked */ OverlayClicked = 'overlay-clicked', } /** * Popover is the UI element for displaying vertical lists */ export default class Popover extends EventsDispatcher<PopoverEvent> { /** * Items list to be displayed */ private readonly items: PopoverItem[]; /** * Stores the visibility state. */ private isShown = false; /** * Created nodes */ private nodes: { wrapper: HTMLElement; popover: HTMLElement; items: HTMLElement; nothingFound: HTMLElement; overlay: HTMLElement; } = { wrapper: null, popover: null, items: null, nothingFound: null, overlay: null, } /** * Additional wrapper's class name */ private readonly className: string; /** * Listeners util instance */ private listeners: Listeners; /** * Flipper - module for keyboard iteration between elements */ private flipper: Flipper; /** * Pass true to enable local search field */ private readonly searchable: boolean; /** * Instance of the Search Input */ private search: SearchInput; /** * Label for the 'Filter' placeholder */ private readonly filterLabel: string; /** * Label for the 'Nothing found' message */ private readonly nothingFoundLabel: string; /** * Style classes */ private static get CSS(): { popover: string; popoverOpened: string; itemsWrapper: string; item: string; itemHidden: string; itemFocused: string; itemLabel: string; itemIcon: string; itemSecondaryLabel: string; noFoundMessage: string; noFoundMessageShown: string; popoverOverlay: string; popoverOverlayHidden: string; } { return { popover: 'ce-popover', popoverOpened: 'ce-popover--opened', itemsWrapper: 'ce-popover__items', item: 'ce-popover__item', itemHidden: 'ce-popover__item--hidden', itemFocused: 'ce-popover__item--focused', itemLabel: 'ce-popover__item-label', itemIcon: 'ce-popover__item-icon', itemSecondaryLabel: 'ce-popover__item-secondary-label', noFoundMessage: 'ce-popover__no-found', noFoundMessageShown: 'ce-popover__no-found--shown', popoverOverlay: 'ce-popover__overlay', popoverOverlayHidden: 'ce-popover__overlay--hidden', }; } /** * ScrollLocker instance */ private scrollLocker = new ScrollLocker() /** * Creates the Popover * * @param options - config * @param options.items - config for items to be displayed * @param options.className - additional class name to be added to the popover wrapper * @param options.filterLabel - label for the search Field * @param options.nothingFoundLabel - label of the 'nothing found' message */ constructor({ items, className, searchable, filterLabel, nothingFoundLabel }: { items: PopoverItem[]; className?: string; searchable?: boolean; filterLabel: string; nothingFoundLabel: string; }) { super(); this.items = items; this.className = className || ''; this.searchable = searchable; this.listeners = new Listeners(); this.filterLabel = filterLabel; this.nothingFoundLabel = nothingFoundLabel; this.render(); this.enableFlipper(); } /** * Returns rendered wrapper */ public getElement(): HTMLElement { return this.nodes.wrapper; } /** * Shows the Popover */ public show(): void { /** * Clear search and items scrolling */ this.search.clear(); this.nodes.items.scrollTop = 0; this.nodes.popover.classList.add(Popover.CSS.popoverOpened); this.nodes.overlay.classList.remove(Popover.CSS.popoverOverlayHidden); this.flipper.activate(); if (this.searchable) { window.requestAnimationFrame(() => { this.search.focus(); }); } if (isMobileScreen()) { this.scrollLocker.lock(); } this.isShown = true; } /** * Hides the Popover */ public hide(): void { /** * If it's already hidden, do nothing * to prevent extra DOM operations */ if (!this.isShown) { return; } this.nodes.popover.classList.remove(Popover.CSS.popoverOpened); this.nodes.overlay.classList.add(Popover.CSS.popoverOverlayHidden); this.flipper.deactivate(); if (isMobileScreen()) { this.scrollLocker.unlock(); } this.isShown = false; } /** * Clears memory */ public destroy(): void { this.listeners.removeAll(); } /** * Returns true if some item is focused */ public hasFocus(): boolean { return this.flipper.hasFocus(); } /** * Helps to calculate height of popover while it is not displayed on screen. * Renders invisible clone of popover to get actual height. */ @cacheable public calculateHeight(): number { let height = 0; const popoverClone = this.nodes.popover.cloneNode(true) as HTMLElement; popoverClone.style.visibility = 'hidden'; popoverClone.style.position = 'absolute'; popoverClone.style.top = '-1000px'; popoverClone.classList.add(Popover.CSS.popoverOpened); document.body.appendChild(popoverClone); height = popoverClone.offsetHeight; popoverClone.remove(); return height; } /** * Makes the UI */ private render(): void { this.nodes.wrapper = Dom.make('div', this.className); this.nodes.popover = Dom.make('div', Popover.CSS.popover); this.nodes.wrapper.appendChild(this.nodes.popover); this.nodes.overlay = Dom.make('div', [Popover.CSS.popoverOverlay, Popover.CSS.popoverOverlayHidden]); this.nodes.wrapper.appendChild(this.nodes.overlay); if (this.searchable) { this.addSearch(this.nodes.popover); } this.nodes.items = Dom.make('div', Popover.CSS.itemsWrapper); this.items.forEach(item => { this.nodes.items.appendChild(this.createItem(item)); }); this.nodes.popover.appendChild(this.nodes.items); this.nodes.nothingFound = Dom.make('div', [ Popover.CSS.noFoundMessage ], { textContent: this.nothingFoundLabel, }); this.nodes.popover.appendChild(this.nodes.nothingFound); this.listeners.on(this.nodes.popover, 'click', (event: KeyboardEvent|MouseEvent) => { const clickedItem = (event.target as HTMLElement).closest(`.${Popover.CSS.item}`) as HTMLElement; if (clickedItem) { this.itemClicked(clickedItem); } }); this.listeners.on(this.nodes.overlay, 'click', () => { this.emit(PopoverEvent.OverlayClicked); }); } /** * Adds the s4arch field to passed element * * @param holder - where to append search input */ private addSearch(holder: HTMLElement): void { this.search = new SearchInput({ items: this.items, placeholder: this.filterLabel, onSearch: (filteredItems): void => { const itemsVisible = []; this.items.forEach((item, index) => { const itemElement = this.nodes.items.children[index]; if (filteredItems.includes(item)) { itemsVisible.push(itemElement); itemElement.classList.remove(Popover.CSS.itemHidden); } else { itemElement.classList.add(Popover.CSS.itemHidden); } }); this.nodes.nothingFound.classList.toggle(Popover.CSS.noFoundMessageShown, itemsVisible.length === 0); /** * Update flipper items with only visible */ this.flipper.deactivate(); this.flipper.activate(itemsVisible); this.flipper.focusFirst(); }, }); const searchField = this.search.getElement(); holder.appendChild(searchField); } /** * Renders the single item * * @param item - item data to be rendered */ private createItem(item: PopoverItem): HTMLElement { const el = Dom.make('div', Popover.CSS.item); el.dataset.itemName = item.name; const label = Dom.make('div', Popover.CSS.itemLabel, { innerHTML: item.label, }); if (item.icon) { el.appendChild(Dom.make('div', Popover.CSS.itemIcon, { innerHTML: item.icon, })); } el.appendChild(label); if (item.secondaryLabel) { el.appendChild(Dom.make('div', Popover.CSS.itemSecondaryLabel, { textContent: item.secondaryLabel, })); } return el; } /** * Item click handler * * @param itemEl - clicked item */ private itemClicked(itemEl: HTMLElement): void { const allItems = this.nodes.wrapper.querySelectorAll(`.${Popover.CSS.item}`); const itemIndex = Array.from(allItems).indexOf(itemEl); const clickedItem = this.items[itemIndex]; clickedItem.onClick(clickedItem); } /** * Creates Flipper instance to be able to leaf tools */ private enableFlipper(): void { const tools = Array.from(this.nodes.wrapper.querySelectorAll(`.${Popover.CSS.item}`)) as HTMLElement[]; this.flipper = new Flipper({ items: tools, focusedItemClass: Popover.CSS.itemFocused, allowedKeys: [ keyCodes.TAB, keyCodes.UP, keyCodes.DOWN, keyCodes.ENTER, ], }); } }
the_stack
import { reduceField, ReducerID } from '..'; import { getFieldDisplayName } from '../field'; import { DataFrame, FieldType } from '../types/dataFrame'; import { DataFrameJSON } from './DataFrameJSON'; import { StreamingDataFrame } from './StreamingDataFrame'; describe('Streaming JSON', () => { describe('when called with a DataFrame', () => { const json: DataFrameJSON = { schema: { fields: [ { name: 'time', type: FieldType.time }, { name: 'name', type: FieldType.string }, { name: 'value', type: FieldType.number }, ], }, data: { values: [ [100, 200, 300], ['a', 'b', 'c'], [1, 2, 3], ], }, }; const stream = new StreamingDataFrame(json, { maxLength: 5, maxDelta: 300, }); it('should create frame with schema & data', () => { expect(stream.fields.map((f) => ({ name: f.name, value: f.values.buffer }))).toMatchInlineSnapshot(` Array [ Object { "name": "time", "value": Array [ 100, 200, 300, ], }, Object { "name": "name", "value": Array [ "a", "b", "c", ], }, Object { "name": "value", "value": Array [ 1, 2, 3, ], }, ] `); }); it('should append new data to frame', () => { stream.push({ data: { values: [[400], ['d'], [4]], }, }); expect(stream.fields.map((f) => ({ name: f.name, value: f.values.buffer }))).toMatchInlineSnapshot(` Array [ Object { "name": "time", "value": Array [ 100, 200, 300, 400, ], }, Object { "name": "name", "value": Array [ "a", "b", "c", "d", ], }, Object { "name": "value", "value": Array [ 1, 2, 3, 4, ], }, ] `); }); it('should append new data and slice based on maxDelta', () => { stream.push({ data: { values: [[500], ['e'], [5]], }, }); expect(stream.fields.map((f) => ({ name: f.name, value: f.values.buffer }))).toMatchInlineSnapshot(` Array [ Object { "name": "time", "value": Array [ 200, 300, 400, 500, ], }, Object { "name": "name", "value": Array [ "b", "c", "d", "e", ], }, Object { "name": "value", "value": Array [ 2, 3, 4, 5, ], }, ] `); }); it('should append new data and slice based on maxLength', () => { stream.push({ data: { values: [ [501, 502, 503], ['f', 'g', 'h'], [6, 7, 8, 9], ], }, }); expect(stream.fields.map((f) => ({ name: f.name, value: f.values.buffer }))).toMatchInlineSnapshot(` Array [ Object { "name": "time", "value": Array [ 400, 500, 501, 502, 503, ], }, Object { "name": "name", "value": Array [ "d", "e", "f", "g", "h", ], }, Object { "name": "value", "value": Array [ 4, 5, 6, 7, 8, 9, ], }, ] `); }); }); describe('lengths property is accurate', () => { const stream = new StreamingDataFrame( { schema: { fields: [{ name: 'simple', type: FieldType.number }], }, data: { values: [[100]], }, }, { maxLength: 5, } ); let val = reduceField({ field: stream.fields[0], reducers: [ReducerID.lastNotNull] })[ReducerID.lastNotNull]; expect(val).toEqual(100); expect(stream.length).toEqual(1); stream.push({ data: { values: [[200]] }, }); val = reduceField({ field: stream.fields[0], reducers: [ReducerID.lastNotNull] })[ReducerID.lastNotNull]; expect(val).toEqual(200); expect(stream.length).toEqual(2); const copy = ({ ...stream } as any) as DataFrame; expect(copy.length).toEqual(2); }); describe('streaming labels column', () => { const stream = new StreamingDataFrame( { schema: { fields: [ { name: 'labels', type: FieldType.string }, { name: 'time', type: FieldType.time }, { name: 'speed', type: FieldType.number }, { name: 'light', type: FieldType.number }, ], }, }, { maxLength: 4, } ); stream.push({ data: { values: [ ['sensor=A', 'sensor=B'], [100, 100], [10, 15], [1, 2], ], }, }); stream.push({ data: { values: [ ['sensor=B', 'sensor=C'], [200, 200], [20, 25], [3, 4], ], }, }); stream.push({ data: { values: [ ['sensor=A', 'sensor=C'], [300, 400], [30, 40], [5, 6], ], }, }); expect(stream.fields.map((f) => ({ name: f.name, labels: f.labels, values: f.values.buffer }))) .toMatchInlineSnapshot(` Array [ Object { "labels": undefined, "name": "time", "values": Array [ 100, 200, 300, 400, ], }, Object { "labels": Object { "sensor": "A", }, "name": "speed", "values": Array [ 10, undefined, 30, undefined, ], }, Object { "labels": Object { "sensor": "A", }, "name": "light", "values": Array [ 1, undefined, 5, undefined, ], }, Object { "labels": Object { "sensor": "B", }, "name": "speed", "values": Array [ 15, 20, undefined, undefined, ], }, Object { "labels": Object { "sensor": "B", }, "name": "light", "values": Array [ 2, 3, undefined, undefined, ], }, Object { "labels": Object { "sensor": "C", }, "name": "speed", "values": Array [ undefined, 25, undefined, 40, ], }, Object { "labels": Object { "sensor": "C", }, "name": "light", "values": Array [ undefined, 4, undefined, 6, ], }, ] `); // Push value with empty labels stream.push({ data: { values: [[''], [500], [50], [7]], }, }); expect(stream.fields.map((f) => getFieldDisplayName(f, stream, [stream]))).toMatchInlineSnapshot(` Array [ "time", "speed A", "light A", "speed B", "light B", "speed C", "light C", "speed 4", "light 4", ] `); // speed+light 4 ¯\_(ツ)_/¯ better than undefined labels }); describe('keep track of packets', () => { const json: DataFrameJSON = { schema: { fields: [ { name: 'time', type: FieldType.time }, { name: 'value', type: FieldType.number }, ], }, data: { values: [ [100, 200, 300], [1, 2, 3], ], }, }; const stream = new StreamingDataFrame(json, { maxLength: 4, maxDelta: 300, }); const getSnapshot = (f: StreamingDataFrame) => { return { values: f.fields[1].values.toArray(), info: f.packetInfo, }; }; expect(getSnapshot(stream)).toMatchInlineSnapshot(` Object { "info": Object { "action": "replace", "length": 3, "number": 1, }, "values": Array [ 1, 2, 3, ], } `); stream.push({ data: { values: [ [400, 500], [4, 5], ], }, }); expect(getSnapshot(stream)).toMatchInlineSnapshot(` Object { "info": Object { "action": "append", "length": 2, "number": 2, }, "values": Array [ 2, 3, 4, 5, ], } `); stream.push({ data: { values: [[600], [6]], }, }); expect(getSnapshot(stream)).toMatchInlineSnapshot(` Object { "info": Object { "action": "append", "length": 1, "number": 3, }, "values": Array [ 3, 4, 5, 6, ], } `); }); /* describe('transpose vertical records', () => { let vrecsA = [ ['sensor=A', 'sensor=B'], [100, 100], [10, 15], ]; let vrecsB = [ ['sensor=B', 'sensor=C'], [200, 200], [20, 25], ]; let vrecsC = [ ['sensor=A', 'sensor=C'], [300, 400], [30, 40], ]; let cTables = transpose(vrecsC); expect(cTables).toMatchInlineSnapshot(` Array [ Array [ "sensor=A", "sensor=C", ], Array [ Array [ Array [ 300, ], Array [ 30, ], ], Array [ Array [ 400, ], Array [ 40, ], ], ], ] `); let cJoined = join(cTables[1]); expect(cJoined).toMatchInlineSnapshot(` Array [ Array [ 300, 400, ], Array [ 30, undefined, ], Array [ undefined, 40, ], ] `); }); */ });
the_stack
import { Vector2, Vector3, Matrix4, Texture } from "three"; export const rayMarchingVertexShaderSrc = [ // switch on high precision floats "#ifdef GL_ES", "precision highp float;", "#endif", "varying vec3 pObj;", "void main()", "{", " pObj = position;", " gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);", "}", ].join("\n"); export const rayMarchingFragmentShaderSrc = [ "#ifdef GL_ES", "precision highp float;", "#endif", "#define M_PI 3.14159265358979323846", "uniform vec2 iResolution;", "uniform vec2 textureRes;", "uniform float GAMMA_MIN;", "uniform float GAMMA_MAX;", "uniform float GAMMA_SCALE;", "uniform float BRIGHTNESS;", "uniform float DENSITY;", "uniform float maskAlpha;", "uniform float ATLAS_X;", "uniform float ATLAS_Y;", "uniform vec3 AABB_CLIP_MIN;", "uniform float CLIP_NEAR;", "uniform vec3 AABB_CLIP_MAX;", "uniform float CLIP_FAR;", "uniform sampler2D textureAtlas;", "uniform sampler2D textureAtlasMask;", "uniform int BREAK_STEPS;", "uniform float SLICES;", "uniform float isOrtho;", "uniform float orthoThickness;", "uniform float orthoScale;", "uniform int maxProject;", "uniform vec3 flipVolume;", "uniform vec3 volumeScale;", // view space to axis-aligned volume box "uniform mat4 inverseModelViewMatrix;", " varying vec3 pObj;", "float powf(float a, float b){", " return pow(a,b);", "}", "float rand(vec2 co){", " float threadId = gl_FragCoord.x/(gl_FragCoord.y + 1.0);", " float bigVal = threadId*1299721.0/911.0;", " vec2 smallVal = vec2(threadId*7927.0/577.0, threadId*104743.0/1039.0);", " return fract(sin(dot(co, smallVal)) * bigVal);", "}", "vec4 luma2Alpha(vec4 color, float vmin, float vmax, float C){", " float x = dot(color.rgb, vec3(0.2125, 0.7154, 0.0721));", //' float x = max(color[2], max(color[0],color[1]));', " float xi = (x-vmin)/(vmax-vmin);", " xi = clamp(xi,0.0,1.0);", " float y = pow(xi,C);", " y = clamp(y,0.0,1.0);", " color[3] = y;", " return(color);", "}", "vec2 offsetFrontBack(float t, float nx, float ny){", " int a = int(t);", " int ax = int(ATLAS_X);", " vec2 os = vec2(float(a-(a/ax)*ax) / ATLAS_X, float(a/ax) / ATLAS_Y);", " return os;", "}", "vec4 sampleAs3DTexture(sampler2D tex, vec4 pos) {", " float bounds = float(pos[0] >= 0.0 && pos[0] <= 1.0 &&", " pos[1] >= 0.0 && pos[1] <= 1.0 &&", " pos[2] >= 0.0 && pos[2] <= 1.0 );", " float nSlices = float(SLICES);", // get location within atlas tile // TODO: get loc1 which follows ray to next slice along ray direction // when flipvolume = 1: pos // when flipvolume = -1: 1-pos " vec2 loc0 = vec2(", " (flipVolume.x*(pos.x - 0.5) + 0.5)/ATLAS_X,", " (flipVolume.y*(pos.y - 0.5) + 0.5)/ATLAS_Y);", // loc ranges from 0 to 1/ATLAS_X, 1/ATLAS_Y // shrink loc0 to within one half edge texel - so as not to sample across edges of tiles. "loc0 = vec2(0.5/textureRes.x, 0.5/textureRes.y) + loc0*vec2(1.0-(ATLAS_X)/textureRes.x, 1.0-(ATLAS_Y)/textureRes.y);", // interpolate between two slices " float z = (pos.z)*(nSlices-1.0);", " float zfloor = floor(z);", " float z0 = zfloor;", " float z1 = (zfloor+1.0);", " z1 = clamp(z1, 0.0, nSlices-1.0);", " float t = z-zfloor;", //mod(z, 1.0);', // flipped: "if (flipVolume.z == -1.0) {", " z0 = nSlices - z0 - 1.0;", " z1 = nSlices - z1 - 1.0;", " t = 1.0 - t;", "}", // get slice offsets in texture atlas " vec2 o0 = offsetFrontBack(z0,ATLAS_X,ATLAS_Y);//*pix;", " vec2 o1 = offsetFrontBack(z1,ATLAS_X,ATLAS_Y);//*pix;", " o0 = clamp(o0, vec2(0.0,0.0), vec2(1.0-1.0/ATLAS_X, 1.0-1.0/ATLAS_Y)) + loc0;", " o1 = clamp(o1, vec2(0.0,0.0), vec2(1.0-1.0/ATLAS_X, 1.0-1.0/ATLAS_Y)) + loc0;", " vec4 slice0Color = texture2D(tex, o0);", " vec4 slice1Color = texture2D(tex, o1);", // NOTE we could premultiply the mask in the fuse function, // but that is slower to update the maskAlpha value than here in the shader. // it is a memory vs perf tradeoff. Do users really need to update the maskAlpha at realtime speed? " float slice0Mask = texture2D(textureAtlasMask, o0).x;", " float slice1Mask = texture2D(textureAtlasMask, o1).x;", // or use max for conservative 0 or 1 masking? " float maskVal = mix(slice0Mask, slice1Mask, t);", // take mask from 0..1 to alpha..1 " maskVal = mix(maskVal, 1.0, maskAlpha);", " vec4 retval = mix(slice0Color, slice1Color, t);", // only mask the rgb, not the alpha(?) " retval.rgb *= maskVal;", " return bounds*retval;", "}", "vec4 sampleStack(sampler2D tex, vec4 pos) {", " vec4 col = sampleAs3DTexture(tex, pos);", " col = luma2Alpha(col, GAMMA_MIN, GAMMA_MAX, GAMMA_SCALE);", "return col;", "}", "bool intersectBox(in vec3 r_o, in vec3 r_d, in vec3 boxMin, in vec3 boxMax,", " out float tnear, out float tfar){", // compute intersection of ray with all six bbox planes " vec3 invR = vec3(1.0,1.0,1.0) / r_d;", " vec3 tbot = invR * (boxMin - r_o);", " vec3 ttop = invR * (boxMax - r_o);", // re-order intersections to find smallest and largest on each axis " vec3 tmin = min(ttop, tbot);", " vec3 tmax = max(ttop, tbot);", // find the largest tmin and the smallest tmax " float largest_tmin = max(max(tmin.x, tmin.y), max(tmin.x, tmin.z));", " float smallest_tmax = min(min(tmax.x, tmax.y), min(tmax.x, tmax.z));", " tnear = largest_tmin;", " tfar = smallest_tmax;", // use >= here? " return(smallest_tmax > largest_tmin);", "}", "vec4 accumulate(vec4 col, float s, vec4 C) {", " float stepScale = (1.0 - powf((1.0-col.w),s));", " col.w = stepScale;", " col.xyz *= col.w;", " col = clamp(col,0.0,1.0);", " C = (1.0-C.w)*col + C;", " return C;", "}", "vec4 accumulateMax(vec4 col, float s, vec4 C) {", " if (col.x*col.w > C.x) { C.x = col.x*col.w; }", " if (col.y*col.w > C.y) { C.y = col.y*col.w; }", " if (col.z*col.w > C.z) { C.z = col.z*col.w; }", " if (col.w > C.w) { C.w = col.w; }", " return C;", "}", "vec4 integrateVolume(vec4 eye_o,vec4 eye_d,", " float tnear, float tfar,", " float clipNear, float clipFar,", " sampler2D textureAtlas", " ){", " vec4 C = vec4(0.0);", " float tend = tfar;", " float tbegin = tnear;", //' // march along ray from front to back, accumulating color', //' //estimate step length', " const int maxSteps = 512;", // modify the 3 components of eye_d by volume scale " float scaledSteps = float(BREAK_STEPS) * length((eye_d.xyz/volumeScale));", " float csteps = clamp(float(scaledSteps), 1.0, float(maxSteps));", " float invstep = (tfar-tnear)/csteps;", // special-casing the single slice to remove the random ray dither. // this removes a Moire pattern visible in single slice images, which we want to view as 2D images as best we can. " float r = (SLICES==1.0) ? 0.0 : 0.5 - 1.0*rand(eye_d.xy);", // if ortho and clipped, make step size smaller so we still get same number of steps " float tstep = invstep*orthoThickness;", " float tfarsurf = r*tstep;", " float overflow = mod((tfarsurf - tend),tstep);", // random dithering offset " float t = tbegin + overflow;", " t += r*tstep;", // random dithering offset " float tdist = 0.0;", " int numSteps = 0;", "vec4 pos, col;", // We need to be able to scale the alpha contrib with number of ray steps, // in order to make the final color invariant to the step size(?) // use maxSteps (a constant) as the numerator... Not sure if this is sound. " float s = 0.5 * float(maxSteps) / csteps;", "for(int i=0; i<maxSteps; i++){", " pos = eye_o + eye_d*t;", // !!! assume box bounds are -0.5 .. 0.5. pos = (pos-min)/(max-min) // scaling is handled by model transform and already accounted for before we get here. // AABB clip is independent of this and is only used to determine tnear and tfar. " pos.xyz = (pos.xyz-(-0.5))/((0.5)-(-0.5)); //0.5 * (pos + 1.0); // map position from [boxMin, boxMax] to [0, 1] coordinates", " col = sampleStack(textureAtlas,pos);", " col.xyz *= BRIGHTNESS;", " if (maxProject != 0) {", " C = accumulateMax(col, s, C);", " } else {", // for practical use the density only matters for regular volume integration " col.w *= DENSITY;", " C = accumulate(col, s, C);", " }", " t += tstep;", " numSteps = i;", " if (t > tend || t > tbegin+clipFar ) break;", " if (C.w > 1.0 ) break;", "}", " return C;", "}", "void main()", "{", " gl_FragColor = vec4(0.0);", " vec2 vUv = gl_FragCoord.xy/iResolution.xy;", " vec3 eyeRay_o, eyeRay_d;", " if (isOrtho == 0.0) {", // for perspective rays: // world space camera coordinates // transform to object space " eyeRay_o = (inverseModelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;", " eyeRay_d = normalize(pObj - eyeRay_o);", " }", " else {", // for ortho rays: " float zDist = 2.0;", " eyeRay_d = (inverseModelViewMatrix*vec4(0.0, 0.0, -zDist, 0.0)).xyz;", " vec4 ray_o = vec4(2.0*vUv - 1.0, 1.0, 1.0);", " ray_o.xy *= orthoScale;", " ray_o.x *= iResolution.x/iResolution.y;", " eyeRay_o = (inverseModelViewMatrix*ray_o).xyz;", " }", // -0.5..0.5 is full box. AABB_CLIP lets us clip to a box shaped ROI to look at // I am applying it here at the earliest point so that the ray march does // not waste steps. For general shaped ROI, this has to be handled more // generally (obviously) " vec3 boxMin = AABB_CLIP_MIN;", " vec3 boxMax = AABB_CLIP_MAX;", " float tnear, tfar;", " bool hit = intersectBox(eyeRay_o, eyeRay_d, boxMin, boxMax, tnear, tfar);", " if (!hit) {", // return background color if ray misses the cube // is this safe to do when there is other geometry / gObjects drawn? " gl_FragColor = vec4(0.0);", //C1;//vec4(0.0);', " return;", " }", " float clipNear = 0.0;//-(dot(eyeRay_o.xyz, eyeNorm) + dNear) / dot(eyeRay_d.xyz, eyeNorm);", " float clipFar = 10000.0;//-(dot(eyeRay_o.xyz,-eyeNorm) + dFar ) / dot(eyeRay_d.xyz,-eyeNorm);", " vec4 C = integrateVolume(vec4(eyeRay_o,1.0), vec4(eyeRay_d,0.0),", " tnear, tfar,", //intersections of box " clipNear, clipFar,", " textureAtlas);//,nBlocks);", " C = clamp(C, 0.0, 1.0);", " gl_FragColor = C;", " return;", "}", ].join("\n"); export const rayMarchingShaderUniforms = { iResolution: { type: "v2", value: new Vector2(100, 100), }, CLIP_NEAR: { type: "f", value: 0.0, }, CLIP_FAR: { type: "f", value: 10000.0, }, maskAlpha: { type: "f", value: 1.0, }, BRIGHTNESS: { type: "f", value: 0.0, }, DENSITY: { type: "f", value: 1.0, }, GAMMA_MIN: { type: "f", value: 0.0, }, GAMMA_MAX: { type: "f", value: 1.0, }, GAMMA_SCALE: { type: "f", value: 1.0, }, BREAK_STEPS: { type: "i", value: 128, }, ATLAS_X: { type: "f", value: 6, }, ATLAS_Y: { type: "f", value: 6, }, SLICES: { type: "f", value: 50, }, isOrtho: { type: "f", value: 0.0, }, orthoThickness: { type: "f", value: 1.0, }, orthoScale: { type: "f", value: 0.5, // needs to come from ThreeJsPanel's setting }, AABB_CLIP_MIN: { type: "v3", value: new Vector3(-0.5, -0.5, -0.5), }, AABB_CLIP_MAX: { type: "v3", value: new Vector3(0.5, 0.5, 0.5), }, inverseModelViewMatrix: { type: "m4", value: new Matrix4(), }, textureAtlas: { type: "t", value: new Texture(), }, textureAtlasMask: { type: "t", value: new Texture(), }, maxProject: { type: "i", value: 0, }, flipVolume: { type: "v3", value: new Vector3(1.0, 1.0, 1.0), }, volumeScale: { type: "v3", value: new Vector3(1.0, 1.0, 1.0), }, textureRes: { type: "v2", value: new Vector2(1.0, 1.0), }, };
the_stack
import React, {useState} from "react"; import styles from "./custom-card.module.scss"; import {Card, Row, Col, Modal, Select} from "antd"; import {convertDateFromISO, getInitialChars, extractCollectionFromSrcQuery} from "../../../util/conversionFunctions"; import {CustomStepTooltips} from "../../../config/tooltips.config"; import {MLTooltip} from "@marklogic/design-system"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import Steps from "../../steps/steps"; import {faCog} from "@fortawesome/free-solid-svg-icons"; import {Link, useHistory} from "react-router-dom"; import {SecurityTooltips} from "../../../config/tooltips.config"; const {Option} = Select; interface Props { data: any; flows: any; entityTypeTitle: any; getArtifactProps: any; updateCustomArtifact: any; canReadOnly: any; canReadWrite: any; canWriteFlow: any; entityModel: any; addStepToFlow: any; addStepToNew: any; } const CustomCard: React.FC<Props> = (props) => { const activityType = "custom"; const [stepData, setStepData] = useState({}); const [openStepSettings, setOpenStepSettings] = useState(false); // show add-to-flow options when hovering const [showLinks, setShowLinks] = useState(""); const [selectVisible, setSelectVisible] = useState(false); const [tooltipVisible, setTooltipVisible] = useState(false); // show confirmation dialog to add step to flow const [addDialogVisible, setAddDialogVisible] = useState(false); // selected step name and flow name when adding step const [stepName, setStepName] = useState(""); const [flowName, setFlowName] = useState(""); const [selected, setSelected] = useState({}); let history = useHistory(); // helper functions const isStepInFlow = (stepName, flowName) => { let result = false, flow; if (props.flows) flow = props.flows.find(f => f.name === flowName); if (flow) result = flow["steps"].findIndex(s => s.stepName === stepName) > -1; return result; }; // updates step settings const updateCustomArtifact = async (payload) => { // Update local form state setStepData(prevState => ({...prevState, ...payload})); await props.updateCustomArtifact(payload); }; // mouse over/mouse leave events with card body (shows/hides add-to-flow options) function handleMouseOver(e, name) { setStepName(name); setSelectVisible(true); setTooltipVisible(true); if (typeof e.target.className === "string" && (e.target.className === "ant-card-body" || e.target.className.startsWith("custom-card_cardContainer") || e.target.className.startsWith("custom-card_formatFileContainer") || e.target.className.startsWith("custom-card_sourceQuery") || e.target.className.startsWith("custom-card_lastUpdatedStyle")) ) { setShowLinks(name); } } function handleMouseLeave() { setShowLinks(""); setSelectVisible(false); setTooltipVisible(false); } const OpenStepSettings = async (name : String) => { setStepData(await props.getArtifactProps(name)); setOpenStepSettings(true); }; // confirmation dialog to add flow to step const onAddOk = async (lName, fName) => { await props.addStepToFlow(lName, fName, "custom"); setAddDialogVisible(false); history.push({ pathname: "/tiles/run/add", state: { flowName: fName, addFlowDirty: true, flowsDefaultKey: [props.flows.findIndex(el => el.name === fName)], existingFlow: true } }); }; const onCancel = () => { setAddDialogVisible(false); setSelected({}); // reset menus on cancel }; const addConfirmation = ( <Modal visible={addDialogVisible} okText={<div data-testid={`${stepName}-to-${flowName}-Confirm`}>Yes</div>} cancelText="No" onOk={() => onAddOk(stepName, flowName)} onCancel={() => onCancel()} width={400} maskClosable={false} > <div aria-label="add-step-confirmation" style={{fontSize: "16px", padding: "10px"}}> { isStepInFlow(stepName, flowName) ? <p aria-label="step-in-flow">The step <strong>{stepName}</strong> is already in the flow <strong>{flowName}</strong>. Would you like to add another instance?</p> : <p aria-label="step-not-in-flow">Are you sure you want to add the step <strong>{stepName}</strong> to the flow <strong>{flowName}</strong>?</p> } </div> </Modal> ); // select dropdown when adding step function handleSelect(obj) { let selectedNew = {...selected}; selectedNew[obj.loadName] = obj.flowName; setSelected(selectedNew); handleStepAdd(obj.stepName, obj.flowName); } const handleStepAdd = (stepName, flowName) => { setStepName(stepName); setFlowName(flowName); setAddDialogVisible(true); }; return ( <div className={styles.customContainer}> <Row gutter={16} type="flex" > { props && props.data.length > 0 ? props.data.map((elem, index) => ( <Col key={index}> <div data-testid={`${props.entityTypeTitle}-${elem.name}-step`} onMouseOver={(e) => handleMouseOver(e, elem.name)} onMouseLeave={handleMouseLeave} > <Card actions={[ <MLTooltip title={CustomStepTooltips.viewCustom} placement="bottom"> <span className={styles.viewStepSettingsIcon} onClick={() => OpenStepSettings(elem.name)} role="edit-custom button" data-testid={elem.name+"-edit"}><FontAwesomeIcon icon={faCog}/> Edit Step Settings</span> </MLTooltip>, ]} className={styles.cardStyle} size="small" > <div className={styles.formatFileContainer}> <span aria-label={`${elem.name}-step-label`} className={styles.customNameStyle}>{getInitialChars(elem.name, 27, "...")}</span> </div> <br /> {elem.selectedSource === "collection" ? <div className={styles.sourceQuery}>Collection: {extractCollectionFromSrcQuery(elem.sourceQuery)}</div> : <div className={styles.sourceQuery}>Source Query: {getInitialChars(elem.sourceQuery, 32, "...")}</div>} <br /><br /> <p className={styles.lastUpdatedStyle}>Last Updated: {convertDateFromISO(elem.lastUpdated)}</p> <div className={styles.cardLinks} style={{display: showLinks === elem.name ? "block" : "none"}}> { props.canWriteFlow ? <Link id="tiles-run-add" to={ { pathname: "/tiles/run/add", state: { stepToAdd: elem.name, targetEntityType: props.entityModel.entityTypeId, stepDefinitionType: "custom" } } }> <div className={styles.cardLink} data-testid={`${elem.name}-toNewFlow`}> Add step to a new flow </div> </Link> : <div className={styles.cardDisabledLink} data-testid={`${elem.name}-disabledToNewFlow`}> Add step to a new flow </div> } <div className={styles.cardNonLink} data-testid={`${elem.name}-toExistingFlow`}> Add step to an existing flow { /** dropdown of flow names to add this custom step to */ selectVisible ? <MLTooltip title={"Curate: "+SecurityTooltips.missingPermission} placement={"bottom"} visible={tooltipVisible && !props.canWriteFlow}> <div className={styles.cardLinkSelect} data-testid={`add-${elem.name}-select`}> <Select style={{width: "100%"}} value={selected[elem.name] ? selected[elem.name] : undefined} onChange={(flowName) => handleSelect({flowName: flowName, stepName: elem.name})} placeholder="Select Flow" defaultActiveFirstOption={false} disabled={!props.canWriteFlow} data-testid={`${elem.name}-flowsList`} getPopupContainer={() => document.getElementById("entityTilesContainer") || document.body} > { props.flows && props.flows.length > 0 ? props.flows.map((f, i) => ( <Option aria-label={`${f.name}-option`} value={f.name} key={i}>{f.name}</Option> )) : null } </Select> </div> </MLTooltip> : null } </div> </div> </Card> </div> </Col> )) : <span></span> } </Row> {addConfirmation} <Steps // Basic Settings isEditing={true} stepData={stepData} canReadWrite={props.canReadWrite} canReadOnly={props.canReadOnly} // Advanced Settings canWrite={props.canReadWrite} tooltipsData={CustomStepTooltips} updateStep={updateCustomArtifact} openStepSettings={openStepSettings} setOpenStepSettings={setOpenStepSettings} targetEntityType={props.entityModel.entityTypeId} targetEntityName={props.entityModel.entityName} activityType={activityType} /> </div> ); }; export default CustomCard;
the_stack
import { LoanToken } from '@defichain/whale-api-client/dist/api/loan' import { EnvironmentNetwork } from '../../../../../../shared/environment' import { checkCollateralDetailValues, checkVaultDetailValues } from '../../../../support/loanCommands' import { VaultStatus } from '../../../../../app/screens/AppNavigator/screens/Loans/VaultStatusTypes' import BigNumber from 'bignumber.js' function addCollateral (): void { cy.go('back') cy.wait(2000) cy.getByTestID('vault_card_0_status').contains('READY') cy.getByTestID('vault_card_0_collateral_token_group_DFI').should('exist') cy.getByTestID('vault_card_0_collateral_token_group_dBTC').should('exist') cy.getByTestID('vault_card_0_total_collateral').contains('$1,500.00') } context('Wallet - Loans', () => { before(function () { cy.createEmptyWallet(true) cy.sendDFItoWallet().wait(6000) }) it('should display correct loans from API', function () { cy.getByTestID('bottom_tab_loans').click() cy.getByTestID('button_create_vault').click() cy.getByTestID('loan_scheme_option_0').click() cy.getByTestID('create_vault_submit_button').click() cy.getByTestID('button_confirm_create_vault').click().wait(4000) cy.closeOceanInterface() cy.intercept('**/loans/tokens?size=200').as('loans') cy.wait(['@loans']).then((intercept: any) => { const data: any[] = intercept.response.body.data cy.getByTestID('loans_tabs_BROWSE_LOANS').click() data.forEach((loan: LoanToken, i) => { // const price = loan.activePrice?.active?.amount ?? 0 cy.getByTestID(`loan_card_${i}_display_symbol`).contains(loan.token.displaySymbol) cy.getByTestID(`loan_card_${i}_interest_rate`).contains(`${loan.interest}%`) // TODO update to fix volatility /* cy.getByTestID(`loan_card_${i}_loan_amount`) .contains(price > 0 ? `$${Number(new BigNumber(price).toFixed(2)).toLocaleString()}` : '-') */ }) }) }) }) context('Wallet - Loans Feature Gated', () => { it('should not have loans tab if loan feature is blocked', function () { cy.intercept('**/settings/flags', { body: [] }) cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_loans').should('not.exist') }) it('should not have loans tab if feature flag api does not contains loan', function () { cy.intercept('**/settings/flags', { body: [ { id: 'foo', name: 'bar', stage: 'alpha', version: '>=0.0.0', description: 'foo', networks: [EnvironmentNetwork.RemotePlayground, EnvironmentNetwork.LocalPlayground], platforms: ['ios', 'android', 'web'] } ] }) cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_loans').should('not.exist') }) it('should not have loans tab if feature flag api failed', function () { cy.intercept('**/settings/flags', { statusCode: 404, body: '404 Not Found!', headers: { 'x-not-found': 'true' } }) cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_loans').should('not.exist') }) it('should not have loans tab if loan feature is beta and not activated by user', function () { cy.intercept('**/settings/flags', { body: [ { id: 'loan', name: 'Loan', stage: 'beta', version: '>=0.0.0', description: 'Loan', networks: [EnvironmentNetwork.RemotePlayground, EnvironmentNetwork.LocalPlayground], platforms: ['ios', 'android', 'web'] } ] }) cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_loans').should('not.exist') }) it('should have loans tab if loan feature is beta is activated by user', function () { cy.intercept('**/settings/flags', { body: [ { id: 'loan', name: 'Loan', stage: 'beta', version: '>=0.0.0', description: 'Loan', networks: [EnvironmentNetwork.RemotePlayground, EnvironmentNetwork.LocalPlayground], platforms: ['ios', 'android', 'web'] } ] }) cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_balances').click() cy.getByTestID('header_settings').click() cy.getByTestID('setting_navigate_About').click() cy.getByTestID('try_beta_features').click() cy.getByTestID('feature_loan_row').should('exist') cy.getByTestID('feature_loan_switch').click().should(() => { expect(localStorage.getItem('WALLET.ENABLED_FEATURES')).to.eq('["loan"]') }) cy.getByTestID('bottom_tab_loans').should('exist') cy.getByTestID('feature_loan_switch').click().should(() => { expect(localStorage.getItem('WALLET.ENABLED_FEATURES')).to.eq('[]') }) }) it('should have loans tab if loan feature is public', function () { cy.intercept('**/settings/flags', { body: [ { id: 'loan', name: 'Loan', stage: 'public', version: '>=0.0.0', description: 'Loan', networks: [EnvironmentNetwork.RemotePlayground, EnvironmentNetwork.LocalPlayground], platforms: ['ios', 'android', 'web'] } ] }) cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_loans').should('exist') }) }) context('Wallet - Loans - Take Loans', () => { let vaultId = '' const walletTheme = { isDark: false } before(function () { cy.createEmptyWallet(true) cy.sendDFItoWallet().sendDFITokentoWallet().sendTokenToWallet(['BTC']).wait(6000) cy.setWalletTheme(walletTheme) cy.getByTestID('bottom_tab_loans').click() cy.getByTestID('empty_vault').should('exist') cy.createVault(0) cy.getByTestID('vault_card_0_manage_loans_button').should('not.exist') cy.getByTestID('vault_card_0_vault_id').then(($txt: any) => { vaultId = $txt[0].textContent }) cy.getByTestID('vault_card_0_edit_collaterals_button').click() cy.addCollateral('10', 'DFI') cy.addCollateral('10', 'dBTC') }) it('should add collateral', function () { addCollateral() }) it('should add loan', function () { let annualInterest: string cy.getByTestID('vault_card_0_manage_loans_button').click() checkVaultDetailValues('READY', vaultId, '$1,500.00', '$0.00', '5') cy.getByTestID('button_browse_loans').click() cy.getByTestID('loan_card_DUSD').click() cy.getByTestID('form_input_borrow').type('1000').blur() cy.wait(3000) cy.getByTestID('text_input_usd_value').should('have.value', '1000.00') cy.getByTestID('form_input_borrow_error').contains('This amount may place the vault in liquidation') cy.getByTestID('text_resulting_col_ratio').contains('150.00%') cy.getByTestID('borrow_loan_submit_button').should('have.attr', 'aria-disabled') cy.getByTestID('form_input_borrow').clear().type('100').blur() cy.wait(3000) cy.getByTestID('text_input_usd_value').should('have.value', '100.00') cy.getByTestID('text_resulting_col_ratio').contains('1,500.00%') cy.getByTestID('text_estimated_annual_interest').then(($txt: any) => { annualInterest = $txt[0].textContent.replace(' DUSD', '').replace(',', '') }) cy.getByTestID('text_total_loan_with_annual_interest').then(($txt: any) => { const totalLoanWithAnnualInterest = $txt[0].textContent.replace(' DUSD', '').replace(',', '') expect(new BigNumber(totalLoanWithAnnualInterest).toFixed(8)).to.be.equal(new BigNumber('100').plus(annualInterest).toFixed(8)) }) cy.getByTestID('borrow_loan_submit_button').click() cy.getByTestID('text_borrow_amount').contains('100.00000000') cy.getByTestID('text_borrow_amount_suffix').contains('DUSD') cy.getByTestID('text_transaction_type').contains('Borrow loan token') cy.getByTestID('tokens_to_borrow').contains('100.00000000') cy.getByTestID('tokens_to_borrow_suffix').contains('DUSD') cy.getByTestID('text_vault_id').contains(vaultId) cy.getByTestID('text_collateral_amount').contains('$1,500.00') cy.getByTestID('text_current_collateral_ratio').contains('N/A') cy.getByTestID('text_resulting_col_ratio').contains('1,500.00') cy.getByTestID('button_confirm_borrow_loan').click().wait(3000) cy.getByTestID('txn_authorization_description') .contains('Borrowing 100.00000000 DUSD') cy.closeOceanInterface() }) it('should verify vault card', function () { cy.checkVaultTag('ACTIVE', VaultStatus.Healthy, 'vault_card_0_status', walletTheme.isDark) cy.getByTestID('vault_card_0_col_ratio').contains('1,500%') cy.getByTestID('vault_card_0_min_ratio').contains('150%') cy.getByTestID('vault_card_0_total_loan').contains('$100') cy.getByTestID('vault_card_0_loan_symbol_DUSD').should('exist') cy.getByTestID('vault_card_0_total_collateral').contains('$1,500.00') }) it('should borrow more loan', function () { let annualInterest: string cy.getByTestID('vault_card_0').click() cy.getByTestID('collateral_tab_LOANS').click() cy.getByTestID('loan_card_DUSD_borrow_more').click() cy.getByTestID('loan_symbol').contains('DUSD') cy.getByTestID('loan_outstanding_balance').contains('100') cy.getByTestID('vault_id').contains(vaultId) cy.checkVaultTag('ACTIVE', VaultStatus.Healthy, 'vault_status_tag', walletTheme.isDark) cy.getByTestID('loan_col_ratio').contains('1,500.00%') cy.getByTestID('loan_min_col').contains('150.00%') cy.getByTestID('loan_add_input').type('1000').blur() cy.getByTestID('loan_add_input_error').contains('This amount may place the vault in liquidation') cy.getByTestID('text_input_usd_value').should('have.value', '1000.00') cy.getByTestID('text_resulting_col_ratio').contains('136') cy.getByTestID('borrow_more_button').should('have.attr', 'aria-disabled') cy.getByTestID('text_estimated_annual_interest').then(($txt: any) => { annualInterest = $txt[0].textContent.replace(' DUSD', '').replace(',', '') }) cy.getByTestID('text_total_loan_with_annual_interest').then(($txt: any) => { const totalLoanWithAnnualInterest = $txt[0].textContent.replace(' DUSD', '').replace(',', '') expect(new BigNumber(totalLoanWithAnnualInterest).toFixed(8)).to.be.equal(new BigNumber('1000').plus(annualInterest).toFixed(8)) }) cy.getByTestID('text_total_loan_with_annual_interest_suffix').contains('DUSD') cy.getByTestID('loan_add_input').clear().type('648').blur() cy.getByTestID('text_resulting_col_ratio').contains('200') cy.getByTestID('borrow_more_button').click() // check confirm page cy.getByTestID('text_borrow_amount').contains('648.00000000') cy.getByTestID('text_borrow_amount_suffix').contains('DUSD') cy.getByTestID('text_transaction_type').contains('Borrow loan token') cy.getByTestID('tokens_to_borrow').contains('648.00000000') cy.getByTestID('tokens_to_borrow_suffix').contains('DUSD') cy.getByTestID('text_vault_id').contains(vaultId) cy.getByTestID('text_collateral_amount').contains('$1,500.00') cy.getByTestID('text_resulting_col_ratio').contains('200') cy.getByTestID('button_confirm_borrow_loan').click().wait(3000) cy.getByTestID('txn_authorization_description').contains('Borrowing 648.00000000 DUSD') cy.closeOceanInterface() }) it('should verify vault card after adding loans', function () { cy.checkVaultTag('ACTIVE', VaultStatus.AtRisk, 'vault_card_0_status', walletTheme.isDark) cy.getByTestID('vault_card_0_col_ratio').contains('201%') cy.getByTestID('vault_card_0_min_ratio').contains('150%') cy.getByTestID('vault_card_0_total_loan').contains('$748') cy.getByTestID('vault_card_0_loan_symbol_DUSD').should('exist') cy.getByTestID('vault_card_0_total_collateral').contains('$1,500.00') }) it('should verify collaterals page', function () { cy.getByTestID('vault_card_0_edit_collaterals_button').click() checkCollateralDetailValues('ACTIVE', '$1,500.00', '$748.00', 201.00, '%', '150.00', '5.00') }) it('should verify resulting collateralization after taking loan', function () { cy.removeCollateral('1', 'DFI', 187.17) checkCollateralDetailValues('ACTIVE', '$1,400.00', '$748', 187.16, '%', '150.00', '5.00') cy.removeCollateral('1', 'DFI', 173.80) checkCollateralDetailValues('ACTIVE', '$1,300.00', '$748', 173.79, '%', '150.00', '5.00') }) it('should borrow another loan token', function () { cy.go('back') cy.wait(2000) cy.getByTestID('loans_tabs_BROWSE_LOANS').click() cy.getByTestID('header_loans_search').click() cy.getByTestID('loans_search_input').type('dTS25').blur() cy.getByTestID('loan_card_dTS25').click() cy.getByTestID('borrow_loan_vault').click() cy.getByTestID('select_vault_0').click() cy.getByTestID('form_input_borrow').clear().type('3').blur() cy.wait(3000) cy.getByTestID('text_input_usd_value').should('have.value', '75.00') cy.getByTestID('text_resulting_col_ratio').contains('157.96') cy.getByTestID('borrow_loan_submit_button').click() cy.getByTestID('button_confirm_borrow_loan').click().wait(3000) cy.getByTestID('txn_authorization_description').contains('Borrowing 3.00000000 dTS25') cy.closeOceanInterface() cy.getByTestID('loans_tabs_YOUR_VAULTS').click() cy.checkVaultTag('ACTIVE', VaultStatus.NearLiquidation, 'vault_card_0_status', walletTheme.isDark) cy.getByTestID('vault_card_0_col_ratio').contains('158%') cy.getByTestID('vault_card_0_min_ratio').contains('150%') cy.getByTestID('vault_card_0_total_loan').contains('$823') cy.getByTestID('vault_card_0_loan_symbol_DUSD').should('exist') cy.getByTestID('vault_card_0_loan_symbol_dTS25').should('exist') cy.getByTestID('vault_card_0_total_collateral').contains('$1,300.00') }) }) context('Wallet - Loans - Payback Loans', () => { let vaultId = '' const walletTheme = { isDark: false } before(function () { cy.createEmptyWallet(true) cy.sendDFItoWallet().sendDFITokentoWallet().sendDFITokentoWallet().sendTokenToWallet(['BTC']).wait(6000) cy.setWalletTheme(walletTheme) cy.getByTestID('bottom_tab_loans').click() cy.getByTestID('empty_vault').should('exist') cy.createVault(0) cy.getByTestID('vault_card_0_manage_loans_button').should('not.exist') cy.getByTestID('vault_card_0_vault_id').then(($txt: any) => { vaultId = $txt[0].textContent }) cy.getByTestID('vault_card_0_edit_collaterals_button').click() cy.addCollateral('10', 'DFI') cy.addCollateral('10', 'dBTC') }) it('should add collateral', function () { addCollateral() }) it('should add loan', function () { cy.getByTestID('vault_card_0_manage_loans_button').click() cy.getByTestID('button_browse_loans').click() cy.getByTestID('loan_card_DUSD').click() cy.getByTestID('form_input_borrow').clear().type('100').blur() cy.wait(3000) cy.getByTestID('borrow_loan_submit_button').click() cy.getByTestID('text_borrow_amount').contains('100.00000000') cy.getByTestID('text_borrow_amount_suffix').contains('DUSD') cy.getByTestID('button_confirm_borrow_loan').click().wait(3000) cy.getByTestID('txn_authorization_description') .contains('Borrowing 100.00000000 DUSD') cy.closeOceanInterface() }) it('should be swap DUSD', function () { cy.getByTestID('bottom_tab_dex').click() cy.getByTestID('close_dex_guidelines').click() cy.getByTestID('pool_pair_swap-horiz_DUSD-DFI').click() cy.getByTestID('switch_button').click() cy.wait(4000) cy.getByTestID('text_input_tokenA').type('1').blur() cy.wait(3000) cy.getByTestID('button_submit').click() cy.getByTestID('button_confirm_swap').click().wait(4000) cy.closeOceanInterface() cy.getByTestID('bottom_tab_loans').click() }) it('should be able to payback loan', function () { cy.getByTestID('vault_card_0').click() cy.getByTestID('collateral_tab_LOANS').click() cy.getByTestID('loan_card_DUSD_payback_loan').click() cy.getByTestID('payback_input_text').clear().type('100000').blur() cy.getByTestID('payback_loan_button').should('have.attr', 'aria-disabled') cy.getByTestID('payback_input_text').clear().type('102').blur() cy.getByTestID('text_resulting_loan_amount').contains('0.00000000') cy.getByTestID('text_resulting_col_ratio').contains('N/A') cy.getByTestID('payback_loan_button').click() cy.getByTestID('confirm_title').contains('You are paying') cy.getByTestID('text_payment_amount').contains('102.00000000') cy.getByTestID('text_payment_amount_suffix').contains('DUSD') cy.getByTestID('text_transaction_type').contains('Loan payment') cy.getByTestID('tokens_to_pay').contains('102.00000000') cy.getByTestID('tokens_to_pay_suffix').contains('DUSD') cy.getByTestID('text_resulting_loan_amount').contains('0.00000000') cy.getByTestID('text_resulting_loan_amount_suffix').contains('DUSD') cy.getByTestID('text_vault_id').contains(vaultId) cy.getByTestID('text_current_collateral_ratio').contains('N/A') cy.getByTestID('button_confirm_payback_loan').click().wait(4000) cy.getByTestID('txn_authorization_description') .contains('Paying 102.00000000 DUSD') cy.closeOceanInterface() cy.checkVaultTag('READY', VaultStatus.Ready, 'vault_card_0_status', walletTheme.isDark) }) })
the_stack
import * as vscode from 'vscode'; import TelemetryReporter from '@vscode/extension-telemetry'; import { DocumentSelector, ExecuteCommandParams, ExecuteCommandRequest, LanguageClient, LanguageClientOptions, RevealOutputChannelOn, State, StaticFeature, ServerOptions, } from 'vscode-languageclient/node'; import { Utils } from 'vscode-uri'; import { clientSupportsCommand, getInitializationOptions, getServerExecutable } from './utils/clientHelpers'; import { GenerateBugReportCommand } from './commands/generateBugReport'; import { ModuleCallsDataProvider } from './providers/moduleCalls'; import { ModuleProvidersDataProvider } from './providers/moduleProviders'; import { ServerPath } from './utils/serverPath'; import { config, getActiveTextEditor, isTerraformFile } from './utils/vscode'; import { TelemetryFeature } from './features/telemetry'; import { ShowReferencesFeature } from './features/showReferences'; import { CustomSemanticTokens } from './features/semanticTokens'; import { ModuleProvidersFeature } from './features/moduleProviders'; import { ModuleCallsFeature } from './features/moduleCalls'; const id = 'terraform'; const brand = `HashiCorp Terraform`; const documentSelector: DocumentSelector = [ { scheme: 'file', language: 'terraform' }, { scheme: 'file', language: 'terraform-vars' }, ]; const outputChannel = vscode.window.createOutputChannel(brand); export let terraformStatus: vscode.StatusBarItem; let reporter: TelemetryReporter; let client: LanguageClient; export async function activate(context: vscode.ExtensionContext): Promise<void> { const manifest = context.extension.packageJSON; terraformStatus = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 0); reporter = new TelemetryReporter(context.extension.id, manifest.version, manifest.appInsightsKey); context.subscriptions.push(reporter); if (previewExtensionPresent(context.extension.id)) { reporter.sendTelemetryEvent('previewExtensionPresentWithStable'); return undefined; } // get rid of pre-2.0.0 settings await migrateLegacySettings(); // Subscriptions context.subscriptions.push( new GenerateBugReportCommand(context), vscode.commands.registerCommand('terraform.enableLanguageServer', async () => { if (!enabled()) { const current = config('terraform').get('languageServer'); await config('terraform').update( 'languageServer', Object.assign(current, { external: true }), vscode.ConfigurationTarget.Global, ); } return startLanguageServer(context); }), vscode.commands.registerCommand('terraform.disableLanguageServer', async () => { if (enabled()) { const current = config('terraform').get('languageServer'); await config('terraform').update( 'languageServer', Object.assign(current, { external: false }), vscode.ConfigurationTarget.Global, ); } return stopLanguageServer(); }), vscode.workspace.onDidChangeConfiguration(async (event: vscode.ConfigurationChangeEvent) => { if (event.affectsConfiguration('terraform') || event.affectsConfiguration('terraform-ls')) { const reloadMsg = 'Reload VSCode window to apply language server changes'; const selected = await vscode.window.showInformationMessage(reloadMsg, 'Reload'); if (selected === 'Reload') { vscode.commands.executeCommand('workbench.action.reloadWindow'); } } }), vscode.commands.registerCommand('terraform.apply', async () => { await terraformCommand('apply', false); }), vscode.commands.registerCommand('terraform.initCurrent', async () => { await terraformCommand('init', true); }), vscode.commands.registerCommand('terraform.plan', async () => { await terraformCommand('plan', false); }), vscode.commands.registerCommand('terraform.validate', async () => { await terraformCommand('validate', true); }), ); if (!enabled()) { reporter.sendTelemetryEvent('disabledTerraformLS'); return; } const lsPath = new ServerPath(context); if (lsPath.hasCustomBinPath()) { reporter.sendTelemetryEvent('usePathToBinary'); } const executable = await getServerExecutable(lsPath); const serverOptions: ServerOptions = { run: executable, debug: executable, }; outputChannel.appendLine(`Launching language server: ${executable.command} ${executable.args?.join(' ')}`); const initializationOptions = getInitializationOptions(); const clientOptions: LanguageClientOptions = { documentSelector: documentSelector, initializationOptions: initializationOptions, initializationFailedHandler: (error) => { reporter.sendTelemetryException(error); return false; }, outputChannel: outputChannel, revealOutputChannelOn: RevealOutputChannelOn.Never, }; client = new LanguageClient(id, serverOptions, clientOptions); client.onDidChangeState((event) => { console.log(`Client: ${State[event.oldState]} --> ${State[event.newState]}`); if (event.newState === State.Stopped) { reporter.sendTelemetryEvent('stopClient'); } }); const moduleProvidersDataProvider = new ModuleProvidersDataProvider(context, client); const moduleCallsDataProvider = new ModuleCallsDataProvider(context, client); const features: StaticFeature[] = [ new CustomSemanticTokens(client, manifest), new ModuleProvidersFeature(client, moduleProvidersDataProvider), new ModuleCallsFeature(client, moduleCallsDataProvider), ]; if (vscode.env.isTelemetryEnabled) { features.push(new TelemetryFeature(client, reporter)); } const codeLensReferenceCount = config('terraform').get<boolean>('codelens.referenceCount'); if (codeLensReferenceCount) { features.push(new ShowReferencesFeature(client)); } client.registerFeatures(features); await startLanguageServer(context); // these need the LS to function, so are only registered if enabled context.subscriptions.push( vscode.commands.registerCommand('terraform.init', async () => { const workspaceFolders = vscode.workspace.workspaceFolders; const selected = await vscode.window.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, defaultUri: workspaceFolders ? workspaceFolders[0]?.uri : undefined, openLabel: 'Initialize', }); if (selected && client) { const moduleUri = selected[0]; const requestParams: ExecuteCommandParams = { command: `terraform-ls.terraform.init`, arguments: [`uri=${moduleUri}`], }; await execWorkspaceCommand(client, requestParams); } }), vscode.window.registerTreeDataProvider('terraform.modules', moduleCallsDataProvider), vscode.window.registerTreeDataProvider('terraform.providers', moduleProvidersDataProvider), vscode.window.onDidChangeVisibleTextEditors(async (editors: readonly vscode.TextEditor[]) => { const textEditor = editors.find((ed) => !!ed.viewColumn); if (textEditor?.document === undefined) { return; } if (!isTerraformFile(textEditor.document)) { return; } await updateTerraformStatusBar(textEditor.document.uri); }), ); } export async function deactivate(): Promise<void> { if (client === undefined) { return; } return client.stop(); } export async function updateTerraformStatusBar(documentUri: vscode.Uri): Promise<void> { if (client === undefined) { return; } const initSupported = clientSupportsCommand(client.initializeResult, `terraform-ls.terraform.init`); if (!initSupported) { return; } try { const moduleUri = Utils.dirname(documentUri); const response = await moduleCallers(moduleUri.toString()); if (response.moduleCallers.length === 0) { const dirName = Utils.basename(moduleUri); terraformStatus.text = `$(refresh) ${dirName}`; terraformStatus.color = new vscode.ThemeColor('statusBar.foreground'); terraformStatus.tooltip = `Click to run terraform init`; terraformStatus.command = 'terraform.initCurrent'; terraformStatus.show(); } else { terraformStatus.hide(); terraformStatus.text = ''; } } catch (err) { if (err instanceof Error) { vscode.window.showErrorMessage(err.message); reporter.sendTelemetryException(err); } terraformStatus.hide(); } } async function startLanguageServer(ctx: vscode.ExtensionContext) { try { console.log('Starting client'); ctx.subscriptions.push(client.start()); await client.onReady(); reporter.sendTelemetryEvent('startClient'); const initializeResult = client.initializeResult; if (initializeResult !== undefined) { const multiFoldersSupported = initializeResult.capabilities.workspace?.workspaceFolders?.supported; console.log(`Multi-folder support: ${multiFoldersSupported}`); } vscode.commands.executeCommand('setContext', 'terraform.showTreeViews', true); } catch (error) { console.log(error); // for test failure reporting if (error instanceof Error) { vscode.window.showErrorMessage(error instanceof Error ? error.message : error); } else if (typeof error === 'string') { vscode.window.showErrorMessage(error); } } } async function stopLanguageServer() { try { await client?.stop(); vscode.commands.executeCommand('setContext', 'terraform.showTreeViews', false); } catch (error) { console.log(error); // for test failure reporting if (error instanceof Error) { vscode.window.showErrorMessage(error instanceof Error ? error.message : error); } else if (typeof error === 'string') { vscode.window.showErrorMessage(error); } } } // eslint-disable-next-line @typescript-eslint/no-explicit-any function execWorkspaceCommand(client: LanguageClient, params: ExecuteCommandParams): Promise<any> { reporter.sendTelemetryEvent('execWorkspaceCommand', { command: params.command }); return client.sendRequest(ExecuteCommandRequest.type, params); } interface ModuleCaller { uri: string; } interface ModuleCallersResponse { version: number; moduleCallers: ModuleCaller[]; } // eslint-disable-next-line @typescript-eslint/no-explicit-any async function modulesCallersCommand(languageClient: LanguageClient, moduleUri: string): Promise<any> { const requestParams: ExecuteCommandParams = { command: `terraform-ls.module.callers`, arguments: [`uri=${moduleUri}`], }; return execWorkspaceCommand(languageClient, requestParams); } export async function moduleCallers(moduleUri: string): Promise<ModuleCallersResponse> { if (client === undefined) { return { version: 0, moduleCallers: [], }; } const response = await modulesCallersCommand(client, moduleUri); const moduleCallers: ModuleCaller[] = response.callers; return { version: response.v, moduleCallers }; } async function terraformCommand(command: string, languageServerExec = true): Promise<void> { const textEditor = getActiveTextEditor(); if (textEditor) { const moduleUri = Utils.dirname(textEditor.document.uri); const response = await moduleCallers(moduleUri.toString()); let selectedModule: string; if (response.moduleCallers.length > 1) { const selected = await vscode.window.showQuickPick( response.moduleCallers.map((m) => m.uri), { canPickMany: false }, ); if (!selected) { return; } selectedModule = selected; } else if (response.moduleCallers.length === 1) { selectedModule = response.moduleCallers[0].uri; } else { selectedModule = moduleUri.toString(); } if (languageServerExec && client) { const requestParams: ExecuteCommandParams = { command: `terraform-ls.terraform.${command}`, arguments: [`uri=${selectedModule}`], }; return execWorkspaceCommand(client, requestParams); } else { const terminalName = `Terraform ${selectedModule}`; const moduleURI = vscode.Uri.parse(selectedModule); const terraformCommand = await vscode.window.showInputBox({ value: `terraform ${command}`, prompt: `Run in ${selectedModule}`, }); if (terraformCommand) { const terminal = vscode.window.terminals.find((t) => t.name === terminalName) || vscode.window.createTerminal({ name: `Terraform ${selectedModule}`, cwd: moduleURI }); terminal.sendText(terraformCommand); terminal.show(); } return; } } else { vscode.window.showWarningMessage(`Open a module then run terraform ${command} again`); return; } } function enabled(): boolean { return config('terraform').get('languageServer.external', false); } async function migrateLegacySettings() { if (config('terraform').has('languageServer.enabled')) { try { await config('terraform').update( 'languageServer', { enabled: undefined, external: true }, vscode.ConfigurationTarget.Global, ); } catch (err) { const error = err instanceof Error ? err.message : err; console.error(`Error trying to erase pre-2.0.0 settings: ${error}`); } } } function previewExtensionPresent(currentExtensionID: string) { const stable = vscode.extensions.getExtension('hashicorp.terraform'); const preview = vscode.extensions.getExtension('hashicorp.terraform-preview'); const msg = 'Please ensure only one is enabled or installed and reload this window'; if (currentExtensionID === 'hashicorp.terraform-preview') { if (stable !== undefined) { vscode.window.showErrorMessage('Terraform Preview cannot be used while Terraform Stable is also enabled.' + msg); return true; } } else if (currentExtensionID === 'hashicorp.terraform') { if (preview !== undefined) { vscode.window.showErrorMessage('Terraform Stable cannot be used while Terraform Preview is also enabled.' + msg); return true; } } return false; }
the_stack
import * as React from 'react'; import { IconButton } from 'office-ui-fabric-react/lib/Button'; import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel'; import { Link } from 'office-ui-fabric-react/lib/Link'; import { Shimmer, ShimmerElementsGroup, ShimmerElementType } from 'office-ui-fabric-react/lib/Shimmer'; import { IFollowedSitesProps } from './IFollowedSitesProps'; import { ISiteItem } from '../../../Common/Modules/ISiteItem'; import styles from '../../MyFollowedSitesApplicationCustomizer.module.scss'; import { formProperties } from '@uifabric/utilities'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { sortBy } from '@microsoft/sp-lodash-subset'; import Utilities from '../../../Common/Services/Utilities'; export default class FollowedSites extends React.Component<IFollowedSitesProps, any>{ //Stores user followed sites locally private _myFollowedSites: ISiteItem[] | undefined; //Browser session storage key to store user followed sites for re-use. private _UserSessionStorageKey: string | undefined; public constructor(props: IFollowedSitesProps) { super(props); this.state = { openPanel: false, isDataLoaded: false, myFollowedSites: [] }; } /** * @description - React component lifecycle method */ public componentDidMount(): void { try { //Generate dynamic session storage key to store information about user followed sites. this._UserSessionStorageKey = this.props.currentContext.pageContext.user.loginName.substring(0, this.props.currentContext.pageContext.user.loginName.indexOf('@')) + '_FollowedSites'; } catch (error) { } } /** * @description - React lifecycle event */ private handleLogoClick(): void { try { //Open panel and show data loading progress. this.setState({ openPanel: true, isDataLoaded: false }); //Getting user followed site information session storage if available. //let myFollowedSitesString: string = this.getFromSessionStorage(this._UserSessionStorageKey); let myFollowedSitesString: string = Utilities.getFromSessionStorage(this._UserSessionStorageKey); if (myFollowedSitesString && myFollowedSitesString !== undefined && myFollowedSitesString.length > 0) { console.log('Loading from Session storage'); this._myFollowedSites = JSON.parse(myFollowedSitesString); //Optional:Setting timeout to have effect of loading data setTimeout(() => { this.setState({ myFollowedSites: this._myFollowedSites, isDataLoaded: true }); }, 500); } else { //Getting followed sites information from server console.log('Loading from server'); this.setState({ openPanel: true, isDataLoaded: false }); this.getUserFollowedSitesFromServer().then(ufsites => { if (ufsites) { //Setting data to react component state this.setState({ myFollowedSites: ufsites, isDataLoaded: true }); //Convert user followed sites object array as JSON string myFollowedSitesString = JSON.stringify(ufsites); //store value in session so it can be retrieved when required. //this.updateSessionStorage(this._UserSessionStorageKey, myFollowedSitesString); Utilities.updateSessionStorage(this._UserSessionStorageKey, myFollowedSitesString); } }); } } catch (error) { console.log(JSON.stringify(error)); } } /** * @description - Loads user followed sites from server */ private handleRefreshClick(): void { try { event.preventDefault(); console.log('Loading from server'); let myFollowedSitesString: string | undefined; this.setState({ openPanel: true, isDataLoaded: false }); this.getUserFollowedSitesFromServer().then(ufsites => { if (ufsites) { this.setState({ myFollowedSites: ufsites, isDataLoaded: true }); //store value in session so it can be retrieved when required. myFollowedSitesString = JSON.stringify(ufsites); if (undefined !== myFollowedSitesString) { this.updateSessionStorage(this._UserSessionStorageKey, myFollowedSitesString); } } }).catch(err => { console.log(JSON.stringify(err)); }); } catch (error) { console.log(error); } } /*** * @description - Generate UI for Followed sites */ private generateFollowedSitesUI(): React.ReactElement[] { let sitesUI: React.ReactElement[] = []; try { if (this.state.myFollowedSites && this.state.myFollowedSites.length > 0) { this.state.myFollowedSites.map((mysite: ISiteItem) => { sitesUI.push( <div className={styles.sitelink}> <Link href={mysite.Uri} target="_blank"> {(mysite.SiteLogo === null || mysite.SiteLogo === undefined) && <Icon iconName="FavoriteStarFill" className={styles.sitelogdefault} /> } {mysite.SiteLogo && mysite.SiteLogo !== undefined && <img src={mysite.SiteLogo} className={styles.sitelogo} /> } {mysite.Name} </Link> </div> ); }); } return sitesUI; } catch (error) { console.log(JSON.stringify(error)); } } /** * @description - Method to close panel. * @param event - Close panel */ private dismissPanel(event: any): void { try { event.preventDefault(); this.setState({ openPanel: false }); } catch (error) { } } /** * @description -Retrieve information from session storage based on key. * @param key - Session storage key */ private getFromSessionStorage(key: string): string { let sessionValue: string = null; try { if (key !== undefined && key) { sessionValue = window.sessionStorage.getItem(key); } } catch (error) { } return sessionValue; } /** * @description - Storage new key value pair in user session. * @param key - Session storage key * @param value - Session storage value */ private updateSessionStorage(key: string, value: string): void { try { if (key && key !== undefined && value && value !== undefined) { window.sessionStorage.setItem(key, value); } } catch (error) { } } /** * @description - Return user followed sites retrieved from server */ private async getUserFollowedSitesFromServer(): Promise<ISiteItem[]> { try { return this.props.spService.getMyFollowedSites().then(fSites => { if (fSites && fSites !== undefined && fSites.length > 0) { let uniqueSites: ISiteItem[] = []; //Remove duplicates if any fSites.forEach(fsite => { if (undefined !== fsite) { if (uniqueSites.indexOf(uniqueSites.filter(u => u.Uri === fsite.Uri)[0]) === -1) { uniqueSites.push(fsite); } } }); //Sort based on site Name let sortedFSites: ISiteItem[] = sortBy(uniqueSites, ['Name']); //let sortedFSites: ISiteItem[] = this.props.spService.SortMyFollowedSites(uniqueSites, "Name"); this._myFollowedSites = sortedFSites; return sortedFSites; } }); } catch (error) { } } /** * @description - React lifecycle event -Render component UI */ public render(): React.ReactElement<IFollowedSitesProps> { const mySitesUI = this.generateFollowedSitesUI(); return ( <div className={styles.app} > <div className={styles.iconcontainer}> <IconButton iconProps={{ iconName: 'AdminSLogoInverse32', className: styles.iconstyle }} ariaLabel='My Followed Sites' title='My Followed Sites' onClick={this.handleLogoClick.bind(this)} /> </div> {this.state.openPanel && <Panel isOpen={this.state.openPanel} type={PanelType.medium} closeButtonAriaLabel="Close" headerText="My Followed Sites" onDismiss={this.dismissPanel.bind(this)} > <Shimmer ariaLabel="Loading data" isDataLoaded={this.state.isDataLoaded}> <div className={styles.refreshcontainer}> <div className={styles.refreshbutton}> <IconButton iconProps={{ iconName: 'Refresh', className: styles.refreshbuttonstyle }} ariaLabel='Refresh' title='Refresh' onClick={this.handleRefreshClick.bind(this)} /> </div> </div> <p className={styles.sitespanel}> {mySitesUI} </p> </Shimmer> </Panel> } </div > ); } }
the_stack
import { MathUtil, Matrix, Quaternion, Vector3 } from "oasis-engine"; import { LiteUpdateFlagManager } from "./LiteUpdateFlagManager"; import { LiteUpdateFlag } from "./LiteUpdateFlag"; import { LiteColliderShape } from "./shape/LiteColliderShape"; import { LiteCollider } from "./LiteCollider"; /** * Used to implement transformation related functions. */ export class LiteTransform { private static _tempQuat0: Quaternion = new Quaternion(); private static _tempMat42: Matrix = new Matrix(); private _position: Vector3 = new Vector3(); private _rotation: Vector3 = new Vector3(); private _rotationQuaternion: Quaternion = new Quaternion(); private _scale: Vector3 = new Vector3(1, 1, 1); private _worldRotationQuaternion: Quaternion = new Quaternion(); private _localMatrix: Matrix = new Matrix(); private _worldMatrix: Matrix = new Matrix(); private _updateFlagManager: LiteUpdateFlagManager = new LiteUpdateFlagManager(); private _isParentDirty: boolean = true; private _parentTransformCache: LiteTransform = null; private _dirtyFlag: number = TransformFlag.WmWpWeWqWs; private _owner: LiteColliderShape | LiteCollider; set owner(value: LiteColliderShape | LiteCollider) { this._owner = value; } /** * Local position. * @remarks Need to re-assign after modification to ensure that the modification takes effect. */ get position(): Vector3 { return this._position; } set position(value: Vector3) { if (this._position !== value) { value.cloneTo(this._position); } this._setDirtyFlagTrue(TransformFlag.LocalMatrix); this._updateWorldPositionFlag(); } /** * Local rotation, defining the rotation by using a unit quaternion. * @remarks Need to re-assign after modification to ensure that the modification takes effect. */ get rotationQuaternion(): Quaternion { if (this._isContainDirtyFlag(TransformFlag.LocalQuat)) { Quaternion.rotationEuler( MathUtil.degreeToRadian(this._rotation.x), MathUtil.degreeToRadian(this._rotation.y), MathUtil.degreeToRadian(this._rotation.z), this._rotationQuaternion ); this._setDirtyFlagFalse(TransformFlag.LocalQuat); } return this._rotationQuaternion; } set rotationQuaternion(value: Quaternion) { if (this._rotationQuaternion !== value) { value.cloneTo(this._rotationQuaternion); } this._setDirtyFlagTrue(TransformFlag.LocalMatrix | TransformFlag.LocalEuler); this._setDirtyFlagFalse(TransformFlag.LocalQuat); this._updateWorldRotationFlag(); } /** * World rotation, defining the rotation by using a unit quaternion. * @remarks Need to re-assign after modification to ensure that the modification takes effect. */ get worldRotationQuaternion(): Quaternion { if (this._isContainDirtyFlag(TransformFlag.WorldQuat)) { const parent = this._getParentTransform(); if (parent != null) { Quaternion.multiply(parent.worldRotationQuaternion, this.rotationQuaternion, this._worldRotationQuaternion); } else { this.rotationQuaternion.cloneTo(this._worldRotationQuaternion); } this._setDirtyFlagFalse(TransformFlag.WorldQuat); } return this._worldRotationQuaternion; } set worldRotationQuaternion(value: Quaternion) { if (this._worldRotationQuaternion !== value) { value.cloneTo(this._worldRotationQuaternion); } const parent = this._getParentTransform(); if (parent) { Quaternion.invert(parent.worldRotationQuaternion, LiteTransform._tempQuat0); Quaternion.multiply(value, LiteTransform._tempQuat0, this._rotationQuaternion); } else { value.cloneTo(this._rotationQuaternion); } this.rotationQuaternion = this._rotationQuaternion; this._setDirtyFlagFalse(TransformFlag.WorldQuat); } /** * Local scaling. * @remarks Need to re-assign after modification to ensure that the modification takes effect. */ get scale(): Vector3 { return this._scale; } set scale(value: Vector3) { if (this._scale !== value) { value.cloneTo(this._scale); } this._setDirtyFlagTrue(TransformFlag.LocalMatrix); this._updateWorldScaleFlag(); } /** * Local matrix. * @remarks Need to re-assign after modification to ensure that the modification takes effect. */ get localMatrix(): Matrix { if (this._isContainDirtyFlag(TransformFlag.LocalMatrix)) { Matrix.affineTransformation(this._scale, this.rotationQuaternion, this._position, this._localMatrix); this._setDirtyFlagFalse(TransformFlag.LocalMatrix); } return this._localMatrix; } set localMatrix(value: Matrix) { if (this._localMatrix !== value) { value.cloneTo(this._localMatrix); } this._localMatrix.decompose(this._position, this._rotationQuaternion, this._scale); this._setDirtyFlagTrue(TransformFlag.LocalEuler); this._setDirtyFlagFalse(TransformFlag.LocalMatrix); this._updateAllWorldFlag(); } /** * World matrix. * @remarks Need to re-assign after modification to ensure that the modification takes effect. */ get worldMatrix(): Matrix { if (this._isContainDirtyFlag(TransformFlag.WorldMatrix)) { const parent = this._getParentTransform(); if (parent) { Matrix.multiply(parent.worldMatrix, this.localMatrix, this._worldMatrix); } else { this.localMatrix.cloneTo(this._worldMatrix); } this._setDirtyFlagFalse(TransformFlag.WorldMatrix); } return this._worldMatrix; } set worldMatrix(value: Matrix) { if (this._worldMatrix !== value) { value.cloneTo(this._worldMatrix); } const parent = this._getParentTransform(); if (parent) { Matrix.invert(parent.worldMatrix, LiteTransform._tempMat42); Matrix.multiply(value, LiteTransform._tempMat42, this._localMatrix); } else { value.cloneTo(this._localMatrix); } this.localMatrix = this._localMatrix; this._setDirtyFlagFalse(TransformFlag.WorldMatrix); } /** * Set local position by X, Y, Z value. * @param x - X coordinate * @param y - Y coordinate * @param z - Z coordinate */ setPosition(x: number, y: number, z: number): void { this._position.setValue(x, y, z); this.position = this._position; } /** * Set local rotation by the X, Y, Z, and W components of the quaternion. * @param x - X component of quaternion * @param y - Y component of quaternion * @param z - Z component of quaternion * @param w - W component of quaternion */ setRotationQuaternion(x: number, y: number, z: number, w: number): void { this._rotationQuaternion.setValue(x, y, z, w); this.rotationQuaternion = this._rotationQuaternion; } /** * Set local scaling by scaling values along X, Y, Z axis. * @param x - Scaling along X axis * @param y - Scaling along Y axis * @param z - Scaling along Z axis */ setScale(x: number, y: number, z: number): void { this._scale.setValue(x, y, z); this.scale = this._scale; } /** * Register world transform change flag. * @returns Change flag */ registerWorldChangeFlag(): LiteUpdateFlag { return this._updateFlagManager.register(); } /** * Get worldMatrix: Will trigger the worldMatrix update of itself and all parent entities. * Get worldPosition: Will trigger the worldMatrix, local position update of itself and the worldMatrix update of all parent entities. * In summary, any update of related variables will cause the dirty mark of one of the full process (worldMatrix or worldRotationQuaternion) to be false. */ private _updateWorldPositionFlag(): void { if (!this._isContainDirtyFlags(TransformFlag.WmWp)) { this._worldAssociatedChange(TransformFlag.WmWp); if (this._owner instanceof LiteCollider) { const shapes = this._owner._shapes; for (let i: number = 0, n: number = shapes.length; i < n; i++) { shapes[i]._transform._updateWorldPositionFlag(); } } } } /** * Get worldMatrix: Will trigger the worldMatrix update of itself and all parent entities. * Get worldPosition: Will trigger the worldMatrix, local position update of itself and the worldMatrix update of all parent entities. * Get worldRotationQuaternion: Will trigger the world rotation (in quaternion) update of itself and all parent entities. * Get worldRotation: Will trigger the world rotation(in euler and quaternion) update of itself and world rotation(in quaternion) update of all parent entities. * In summary, any update of related variables will cause the dirty mark of one of the full process (worldMatrix or worldRotationQuaternion) to be false. */ private _updateWorldRotationFlag() { if (!this._isContainDirtyFlags(TransformFlag.WmWeWq)) { this._worldAssociatedChange(TransformFlag.WmWeWq); if (this._owner instanceof LiteCollider) { const shapes = this._owner._shapes; for (let i: number = 0, n: number = shapes.length; i < n; i++) { shapes[i]._transform._updateWorldRotationFlag(); } } } } /** * Get worldMatrix: Will trigger the worldMatrix update of itself and all parent entities. * Get worldPosition: Will trigger the worldMatrix, local position update of itself and the worldMatrix update of all parent entities. * Get worldScale: Will trigger the scaling update of itself and all parent entities. * In summary, any update of related variables will cause the dirty mark of one of the full process (worldMatrix) to be false. */ private _updateWorldScaleFlag() { if (!this._isContainDirtyFlags(TransformFlag.WmWs)) { this._worldAssociatedChange(TransformFlag.WmWs); if (this._owner instanceof LiteCollider) { const shapes = this._owner._shapes; for (let i: number = 0, n: number = shapes.length; i < n; i++) { shapes[i]._transform._updateWorldScaleFlag(); } } } } /** * Update all world transform property dirty flag, the principle is the same as above. */ private _updateAllWorldFlag(): void { if (!this._isContainDirtyFlags(TransformFlag.WmWpWeWqWs)) { this._worldAssociatedChange(TransformFlag.WmWpWeWqWs); if (this._owner instanceof LiteCollider) { const shapes = this._owner._shapes; for (let i: number = 0, n: number = shapes.length; i < n; i++) { shapes[i]._transform._updateAllWorldFlag(); } } } } private _getParentTransform(): LiteTransform | null { if (!this._isParentDirty) { return this._parentTransformCache; } let parentCache: LiteTransform = null; if (this._owner instanceof LiteColliderShape) { let parent = this._owner._collider; parentCache = parent._transform; } this._parentTransformCache = parentCache; this._isParentDirty = false; return parentCache; } private _isContainDirtyFlags(targetDirtyFlags: number): boolean { return (this._dirtyFlag & targetDirtyFlags) === targetDirtyFlags; } private _isContainDirtyFlag(type: number): boolean { return (this._dirtyFlag & type) != 0; } private _setDirtyFlagTrue(type: number) { this._dirtyFlag |= type; } private _setDirtyFlagFalse(type: number) { this._dirtyFlag &= ~type; } private _worldAssociatedChange(type: number): void { this._dirtyFlag |= type; this._updateFlagManager.distribute(); } } /** * Dirty flag of transform. */ enum TransformFlag { LocalEuler = 0x1, LocalQuat = 0x2, WorldPosition = 0x4, WorldEuler = 0x8, WorldQuat = 0x10, WorldScale = 0x20, LocalMatrix = 0x40, WorldMatrix = 0x80, /** WorldMatrix | WorldPosition */ WmWp = 0x84, /** WorldMatrix | WorldEuler | WorldQuat */ WmWeWq = 0x98, /** WorldMatrix | WorldPosition | WorldEuler | WorldQuat */ WmWpWeWq = 0x9c, /** WorldMatrix | WorldScale */ WmWs = 0xa0, /** WorldMatrix | WorldPosition | WorldScale */ WmWpWs = 0xa4, /** WorldMatrix | WorldPosition | WorldEuler | WorldQuat | WorldScale */ WmWpWeWqWs = 0xbc }
the_stack
import * as bodyParser from 'body-parser'; import * as morgan from 'morgan'; import * as bunyan from 'bunyan'; import * as cookieParser from 'cookie-parser'; import * as express from 'express'; import cookieSession = require('cookie-session'); import * as methodOverride from 'method-override'; import * as passport from 'passport'; import * as passportAzureAD from 'passport-azure-ad'; import * as config from './config'; import * as path from 'path'; import * as express_request_id from 'express-request-id'; import * as simple_oath2 from 'simple-oauth2'; import * as graph from './graph'; import * as oauth2 from './oauth2'; export const log = bunyan.createLogger({ name: 'BUNYAN-LOGGER', src: true, }); // ----------------------------------------------------------------------------- // Passport Setup Follows // ----------------------------------------------------------------------------- // Setup schemas for Passport's User object and the the session persistence format. // Augument Passport's request.user with the Azure AD oauthToken declare global { namespace Express { interface User { oid: string; oauthToken: oauth2.Token; } } } type FullUserSchema = Express.User; // This now includes the above declaration for User. interface MinimizedUserSchema { oid: string; refresh_token: string; } passport.serializeUser((user: FullUserSchema, done) => { const stored: MinimizedUserSchema = { oid: user.oid, refresh_token: user.oauthToken.refresh_token }; done(null, stored); }); passport.deserializeUser(async (stored: MinimizedUserSchema, done) => { if (!stored || !stored.refresh_token) { return done(Error('no user profile')); } let oauthClient = await oauth2.client(stored); if (oauthClient.expired()) { oauthClient = await oauthClient.refresh(); // must reassign here. } const profile = await graph.user(oauthClient.token.access_token).catch(reason => { log.error('could not retrieve profile', reason); }); if (!profile) { return done(Error('no user profile')); } const result = { ...profile, oid: stored.oid, oauthToken: oauthClient.token }; return done(null, result); }); // ----------------------------------------------------------------------------- // Define the AzureAD OIDCStrategy Strategy // ----------------------------------------------------------------------------- const OIDCStrategyTemplate = {} as passportAzureAD.IOIDCStrategyOptionWithoutRequest; const azureStrategyOptions: passportAzureAD.IOIDCStrategyOptionWithRequest = { identityMetadata: config.creds.identityMetadata, clientID: config.creds.clientID, responseType: config.creds.responseType as typeof OIDCStrategyTemplate.responseType, responseMode: config.creds.responseMode as typeof OIDCStrategyTemplate.responseMode, redirectUrl: config.creds.redirectUrl, allowHttpForRedirectUrl: config.creds.allowHttpForRedirectUrl, clientSecret: config.creds.clientSecret, validateIssuer: config.creds.validateIssuer, isB2C: config.creds.isB2C, issuer: config.creds.issuer, passReqToCallback: true, scope: config.creds.scope, loggingLevel: config.creds.logLevel as typeof OIDCStrategyTemplate.loggingLevel, nonceLifetime: config.creds.nonceLifetime, nonceMaxAmount: config.creds.nonceMaxAmount, useCookieInsteadOfSession: config.creds.useCookieInsteadOfSession, cookieEncryptionKeys: config.creds.cookieEncryptionKeys, clockSkew: config.creds.clockSkew, }; // ----------------------------------------------------------------------------- // Use the Azure OIDCStrategy within Passport. // // Strategies in passport require a `verify` function, which accepts credentials // (in this case, the `oid` claim in id_token), and invoke a callback to find // the corresponding user object. // // The following are the accepted prototypes for the `verify` function // (1) function(iss, sub, done) // (2) function(iss, sub, profile, done) // (3) function(iss, sub, profile, access_token, refresh_token, done) // (4) function(iss, sub, profile, access_token, refresh_token, params, done) // (5) function(iss, sub, profile, jwtClaims, access_token, refresh_token, params, done) // (6) prototype (1)-(5) with an additional `req` parameter as the first parameter // // To do prototype (6), passReqToCallback must be set to true in the config. // ----------------------------------------------------------------------------- passport.use(new passportAzureAD.OIDCStrategy(azureStrategyOptions, processAzureStrategy)); async function processAzureStrategy(req: express.Request, iss: string, sub: string, profile: passportAzureAD.IProfile, jwtClaims: any, access_token: string, refresh_token: string, oauthToken: any, done: passportAzureAD.VerifyCallback) { if (!profile.oid) { return done(new Error('No oid found'), null); } // asynchronous verification, for effect... process.nextTick(async () => { const fullProfile = await graph.user(access_token); if (!fullProfile) { return done(Error('no profile')); } const oauth = oauth2.client(oauthToken); const result = { ...fullProfile, oid: profile.oid, oauthToken: oauth.token }; return done(null, result); }); } // ----------------------------------------------------------------------------- // Config the express app and all the required middleware // ----------------------------------------------------------------------------- export const app = express(); app.use(morgan(config.httpLogFormat)); app.set('trust proxy', true); app.set('views', path.join(__dirname, '../public/views')); app.set('view engine', 'ejs'); app.use(express_request_id()); app.use(methodOverride()); app.use(cookieParser()); app.use(cookieSession({ keys: config.creds.cookieEncryptionKeys.map(value => value.key), secure: false, maxAge: 1000 * 60 * 60 * 24 * 365 })); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(passport.initialize()); app.use(passport.session()); // ----------------------------------------------------------------------------- // Define a couple of authencation request handlers. // ----------------------------------------------------------------------------- function ensureAuthenticated(req: express.Request, res: express.Response, next: express.NextFunction) { if (req.isAuthenticated()) { return next(); } res.redirect('/login'); } function ensureAuthenticatedApi(req: express.Request, res: express.Response, next: express.NextFunction) { if (req.isAuthenticated()) { return next(); } res.sendStatus(401).end(); return next(); } app.get('/', (req, res) => { const user = { ...req.user, oauthToken: '[removed]'}; res.render('index', { user }); }); app.get('/account', ensureAuthenticated, (req, res, next) => { const user = { ...req.user, oauthToken: '[removed]'}; res.render('account', { user }); }); app.get('/login', (req, res, next) => { passport.authenticate('azuread-openidconnect', { response: res, // required customState: 'my_state', // optional. Provide a value if you want to provide custom state value. failureRedirect: '/', } as passport.AuthenticateOptions, )(req, res, next); }, (req, res) => { log.info('login was called'); res.redirect('/'); }); // 'GET returnURL' // `passport.authenticate` will try to authenticate the content returned in // query (such as authorization code). If authentication fails, user will be // redirected to '/' (home page); otherwise, it passes to the next middleware. app.get('/auth/openid/return', (req, res, next) => { passport.authenticate('azuread-openidconnect', { response: res, // required failureRedirect: '/', } as passport.AuthenticateOptions, )(req, res, next); }, (req, res, next) => { log.info('received a return from AzureAD.'); res.redirect('/'); }); // 'POST returnURL' // `passport.authenticate` will try to authenticate the content returned in // body (such as authorization code). If authentication fails, user will be // redirected to '/' (home page); otherwise, it passes to the next middleware. app.post('/auth/openid/return', (req, res, next) => { passport.authenticate('azuread-openidconnect', { response: res, // required failureRedirect: '/', } as passport.AuthenticateOptions, )(req, res, next); }, (req, res, next) => { log.info('received a return from AzureAD.'); res.redirect('/'); }); // 'endsession' route, logout from passport, and destroy the session with AAD. app.get('/endsession', (req, res) => { req.session = null; req.logOut(); res.redirect('/'); }); // 'logout' route, logout from passport, and destroy the session with AAD. app.get('/logout', (req, res) => { req.session = null; // req.session.destroy((err) => { req.logOut(); res.redirect(config.destroySessionUrl); }); app.get('/api/v1.0/me', ensureAuthenticatedApi, async (req, res, next) => { try { let oauth = oauth2.client(req.user.oauthToken); if (oauth.expired()) { oauth = await oauth.refresh(); } const result = await graph.user(oauth.token.access_token); res.json(result); res.end(); next(); } catch (error) { res.status(error.statusCode).json(error).end(); return next(); } }); app.get('/api/v1.0/profile', ensureAuthenticatedApi, async (req, res, next) => { try { let oauth = oauth2.client(req.user.oauthToken); if (oauth.expired()) { oauth = await oauth.refresh(); } const result = await graph.client(oauth.token.access_token).api('/me/extensions/com.code-with.vott').get(); res.json(result); res.end(); next(); } catch (error) { res.status(error.statusCode).json(error).end(); return next(); } }); app.put('/api/v1.0/profile', ensureAuthenticatedApi, async (req, res, next) => { try { let oauth = oauth2.client(req.user.oauthToken); if (oauth.expired()) { oauth = await oauth.refresh(); } const body = { ...req.body, extensionName: 'com.code-with.vott' }; let result = null; try { // Handle bad graph open extension semantics result = await graph.client(oauth.token.access_token).api('/me/extensions/').post(body); } catch (error) { // if it already exists and we are replacing. Delete and try again. result = await graph.client(oauth.token.access_token).api('/me/extensions/com.code-with.vott').delete(); result = await graph.client(oauth.token.access_token).api('/me/extensions').post(body); } res.json(result); res.end(); next(); } catch (error) { res.status(error.statusCode).json(error).end(); return next(); } }); app.get('/api/v1.0/cloudconnections/:id', ensureAuthenticatedApi, async (req, res, next) => { try { const id = req.params.id; // careful should only be a domain name pattern. let oauth = oauth2.client(req.user.oauthToken); if (oauth.expired()) { oauth = await oauth.refresh(); } const result = await graph.client(oauth.token.access_token).api(`/me/extensions/com.code-with.vott.${id}`).get(); res.json(result); res.end(); next(); } catch (error) { res.status(error.statusCode).json(error).end(); return next(); } }); app.put('/api/v1.0/cloudconnections/:id', ensureAuthenticatedApi, async (req, res, next) => { try { const id = req.params.id; // careful should only be a domain name pattern. let oauth = oauth2.client(req.user.oauthToken); if (oauth.expired()) { oauth = await oauth.refresh(); } const body = { ...req.body, extensionName: `com.code-with.vott.${id}` }; let result = null; try { // Handle bad graph open extension semantics result = await graph.client(oauth.token.access_token).api('/me/extensions/').post(body); } catch (error) { // if it already exists and we are replacing. Delete and try again. result = await graph.client(oauth.token.access_token).api(`/me/extensions/com.code-with.vott.${id}`).delete(); result = await graph.client(oauth.token.access_token).api('/me/extensions').post(body); } res.json(result); res.end(); next(); } catch (error) { res.status(error.statusCode).json(error).end(); return next(); } }); app.patch('/api/v1.0/cloudconnections/:id', ensureAuthenticatedApi, async (req, res, next) => { try { const id = req.params.id; // careful should only be a domain name pattern. let oauth = oauth2.client(req.user.oauthToken); if (oauth.expired()) { oauth = await oauth.refresh(); } const body = { ...req.body, extensionName: `com.code-with.vott.${id}` }; const result = await graph.client(oauth.token.access_token).api(`/me/extensions/com.code-with.vott.${id}`).patch(body); res.json(result); res.end(); next(); } catch (error) { res.status(error.statusCode).json(error).end(); return next(); } }); app.delete('/api/v1.0/cloudconnections/:id', ensureAuthenticatedApi, async (req, res, next) => { try { const id = req.params.id; // careful should only be a domain name pattern. let oauth = oauth2.client(req.user.oauthToken); if (oauth.expired()) { oauth = await oauth.refresh(); } const result = await graph.client(oauth.token.access_token).api(`/me/extensions/com.code-with.vott.${id}`).delete(); res.end(); return next(); } catch (error) { res.status(error.statusCode).json(error).end(); return next(); } }); app.use('/public', express.static(path.join(__dirname, '../public'))); export const server = app.listen(config.port);
the_stack
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import Database from '@ioc:Adonis/Lucid/Database' import CacheHelper from 'App/Helpers/CacheHelper' import UserServices from 'App/Services/UserServices' import UserValidator from 'App/Validators/UserValidator' import { CACHE_TAGS } from 'Contracts/cache' import { ROLES } from 'Database/data/roles' import querystring from 'querystring' import Logger from '@ioc:Adonis/Core/Logger' import Application from '@ioc:Adonis/Core/Application' import { DateTime } from 'luxon' import FileUploadHelper from 'App/Helpers/FileUploadHelper' import { AttachedFile, FileData } from 'types/file' import FileDeletionHelper from 'App/Helpers/FileDeletionHelper' import User from 'App/Models/User' import UserProfile from 'App/Models/UserProfile' export default class UsersController { public async index({ response, requestedCompany, request, bouncer }: HttpContextContract) { await bouncer.with('UserPolicy').authorize('list', requestedCompany!) const { page, descending, perPage, sortBy, id, email, login_status, is_account_activated, is_email_verified, lifetime_login, last_login_time, account_activated_at, email_verified_at, created_at, updated_at, first_name, last_name, role, } = request.qs() const searchQuery = { id: id ? id : null, email: email ? email : null, login_status: login_status ? login_status : null, is_account_activated: is_account_activated ? is_account_activated : null, is_email_verified: is_email_verified ? is_email_verified : null, lifetime_login: lifetime_login ? lifetime_login : null, last_login_time: last_login_time ? last_login_time : null, account_activated_at: account_activated_at ? account_activated_at : null, email_verified_at: email_verified_at ? email_verified_at : null, created_at: created_at ? created_at : null, updated_at: updated_at ? updated_at : null, first_name: first_name ? first_name : null, last_name: last_name ? last_name : null, role: role ? role : null, } const cacheQuerystring = querystring.stringify(request.qs()) const cacheKey = `company_users_index:${requestedCompany?.id}__`.concat(cacheQuerystring) const sets = [ `${CACHE_TAGS.ALL_COMPANIES_CACHES_TAG}`, `${CACHE_TAGS.ALL_USERS_CACHES_TAG}`, `${CACHE_TAGS.COMPANY_CACHE_TAG_PREFIX}:${requestedCompany?.id}`, `${CACHE_TAGS.COMPANY_USERS_CACHE_TAG_PREFIX}:${requestedCompany?.id}`, `${CACHE_TAGS.COMPANY_USERS_INDEX_CACHE_TAG_PREFIX}:${requestedCompany?.id}`, ] let usersIndex: { meta: any; data: any[] } | null = null await CacheHelper.get(cacheKey) .then(async (result) => { if (result) { usersIndex = result } else { // Compute and set a new key-value pair let subquery = Database.from('users') .select( 'users.id', 'users.email', 'users.login_status', 'users.is_account_activated', 'users.is_email_verified', 'users.lifetime_login', 'users.password_change_required', 'users.last_login_time', 'users.account_activated_at', 'users.email_verified_at', 'users.created_at', 'users.updated_at', 'user_profiles.first_name', 'user_profiles.last_name', 'roles.name as role', 'uploaded_files.url as profile_picture_url', 'uploaded_files.formats as profile_picture_formats' ) .leftJoin('company_user', (query) => { query.on('company_user.user_id', '=', 'users.id') }) .leftJoin('user_profiles', (query) => { query.on('user_profiles.user_id', '=', 'users.id') }) .leftJoin('roles', (query) => { query.on('roles.id', '=', 'users.role_id') }) .leftJoin('uploaded_files', (query) => query.on('uploaded_files.id', '=', 'user_profiles.profile_picture') ) .where({ 'company_user.company_id': requestedCompany?.id }) if (sortBy) { subquery = subquery.orderBy(sortBy, descending === 'true' ? 'desc' : 'asc') } if (searchQuery) { subquery.where((query) => { for (const param in searchQuery) { if (Object.prototype.hasOwnProperty.call(searchQuery, param)) { let value = searchQuery[param] if (value) { if (value === 'true') value = true if (value === 'false') value = false if (param === 'role') query.where('role_id', value) else { //console.log(param, value) query.where(param, value) if (typeof value === 'string') { query.orWhere(param, 'like', `%${value}%`) } } } } } }) } const users = await subquery.paginate(page ? page : 1, perPage ? perPage : 20) const serialisedUsers = users?.toJSON() await CacheHelper.put(cacheKey, serialisedUsers) // Add the `cacheKey` to sets await CacheHelper.tag(sets, cacheKey) usersIndex = serialisedUsers } }) .catch((error) => { Logger.error('Error from App/Controllers/UsersController.index: %o', error) }) return response.ok({ data: usersIndex }) } public async show({ response, requestedCompany, requestedUser, bouncer }: HttpContextContract) { await bouncer.with('UserPolicy').authorize('view', requestedCompany ?? null, requestedUser!) const userService = new UserServices({ id: requestedUser?.id }) const cachedUserDetails = await userService.getFullUserDetails() return response.ok({ data: cachedUserDetails }) } public async store({ response, requestedCompany, requestedUser, request, bouncer, }: HttpContextContract) { const { first_name, last_name, middle_name, phone_number, address, city, email, role_id, state_id, country_id, login_status, profile_picture, } = await request.validate(UserValidator) const requestMethod = request.method() let creationMode = true let userModel: User | undefined let requestedUserProfile: UserProfile | undefined if (requestMethod === 'POST') { await bouncer.with('UserPolicy').authorize('create', requestedCompany!) userModel = await requestedCompany ?.related('users') .create({ email, loginStatus: login_status, roleId: role_id }) requestedUserProfile = await userModel?.related('profile').create({ firstName: first_name, middleName: middle_name && middle_name !== 'null' ? middle_name : '', lastName: last_name, phoneNumber: phone_number, address, city, stateId: state_id || null, countryId: country_id || null, }) } else if (requestMethod === 'PATCH') { creationMode = false await bouncer.with('UserPolicy').authorize('edit', requestedCompany!, requestedUser!) userModel = requestedUser userModel?.merge({ email, loginStatus: login_status }) await userModel?.save() // Ensure that a SuperAdmin does not lose login access await userModel?.load('role') if (userModel?.role?.name !== ROLES.SUPERADMIN) { userModel?.merge({ roleId: role_id }) await userModel?.save() } await userModel?.load('profile') requestedUserProfile = userModel?.profile requestedUserProfile?.merge({ firstName: first_name, middleName: middle_name && middle_name !== 'null' ? middle_name : '', lastName: last_name, phoneNumber: phone_number, address, city, stateId: state_id || null, countryId: country_id || null, }) await requestedUserProfile?.save() await requestedUserProfile?.refresh() } else return response.badRequest({ message: 'This request is not recognised' }) const fileStatus = { fileExists: false, uploaded: false } // Check if user profile already has a profile picture const oldProfilePicture = requestedUserProfile?.profilePicture const hasOldProfilePicture = !!oldProfilePicture // Process uploaded file (if any) if (profile_picture) { fileStatus.fileExists = true const firstName = requestedUserProfile?.firstName! const lastName = requestedUserProfile?.lastName! const firstLetter = firstName.charAt(0) const secondLetter = firstName.charAt(1) const finalUploadDir = `uploads/profile_pictures/${firstLetter}/${secondLetter}`.toLowerCase() const fileName = `${firstName}_${lastName}_${DateTime.now().toMillis()}`.toLowerCase() await profile_picture.move(Application.tmpPath('uploads/user_profile_pictures/'), { name: `${fileName}.${profile_picture.extname}`, overwrite: true, }) // Generate file formats using sharp and persist them const fileObject: AttachedFile = { filePath: profile_picture.filePath, name: fileName, type: profile_picture.type!, size: profile_picture.size!, } const mime = profile_picture.type + '/' + profile_picture.subtype const fileData: FileData = { data: { fileInfo: { ext: '', hash: '', mime, size: fileObject.size, alternativeText: '', caption: '', name: fileObject.name, path: fileObject.filePath, }, }, files: profile_picture, } const fileUploadHelper = new FileUploadHelper( fileData, finalUploadDir, 'local', 'user_profile_picture' ) await fileUploadHelper.upload().then(async (uploadedFileModel) => { fileStatus.uploaded = true // Associate profile picture with the uploaded file requestedUserProfile?.merge({ profilePicture: uploadedFileModel?.id }) await requestedUserProfile?.save() }) if (hasOldProfilePicture) { // Delete old profile picture await new FileDeletionHelper(oldProfilePicture!).delete() } } // Clear the user's entire cache const sets = [ `${CACHE_TAGS.USER_CACHE_TAG_PREFIX}:${requestedUser?.id}`, `${CACHE_TAGS.COMPANY_USERS_CACHE_TAG_PREFIX}:${requestedCompany?.id}`, `${CACHE_TAGS.COMPANY_USERS_INDEX_CACHE_TAG_PREFIX}:${requestedCompany?.id}`, ] await CacheHelper.flushTags(sets) return response.created({ message: `User was successfully ${creationMode ? 'created' : 'edited'}.`, fileStatus, data: userModel?.id, }) } public async destroy({ response, requestedCompany, requestedUser, bouncer, }: HttpContextContract) { await bouncer.with('UserPolicy').authorize('delete', requestedCompany ?? null, requestedUser!) // Ensure that a SuperAdmin is not deleted if (requestedUser?.role?.name !== ROLES.SUPERADMIN) { requestedUser?.delete() // Wipe off all caches for the user const sets = [ `${CACHE_TAGS.USER_CACHE_TAG_PREFIX}:${requestedUser?.id}`, `${CACHE_TAGS.USER_DETAILS_CACHE_TAG_PREFIX}:${requestedUser?.id}`, `${CACHE_TAGS.USER_SUMMARY_CACHE_TAG_PREFIX}:${requestedUser?.id}`, `${CACHE_TAGS.COMPANY_USERS_CACHE_TAG_PREFIX}:${requestedCompany?.id}`, `${CACHE_TAGS.COMPANY_USERS_INDEX_CACHE_TAG_PREFIX}:${requestedCompany?.id}`, ] await CacheHelper.nukeTags(sets) return response.created({ data: requestedUser?.id }) } else { return response.badRequest({ message: 'User cannot be deleted!' }) } } }
the_stack
const page = figma.createPage() page.name = "Icons for export" figma.root.appendChild(page); let nodes if(figma.currentPage.selection && figma.currentPage.selection.length > 0) { // Go over nodes the user has selected nodes = figma.currentPage.selection } else { // Get all nodes that are components and begin with "Icon/" nodes = figma.currentPage.findAll(node => node.name.indexOf('Icon/') === 0 && node.type == 'COMPONENT_SET') } const newNodes = [] const iconData = {} const problematicIcons = {} let processedIcons = 0 let svgX = 0 let svgY = 0 let pngX = 0 let pngY = 0 function toPascalCase(string) { return `${string}` .replace(new RegExp(/[-_]+/, 'g'), ' ') .replace(new RegExp(/[^\w\s]/, 'g'), '') .replace( new RegExp(/\s+(.)(\w+)/, 'g'), ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}` ) .replace(new RegExp(/\s/, 'g'), '') .replace(new RegExp(/\w/), s => s.toUpperCase()); } function exportComponentAsSVG(node, nodeVariant, subFolder) { let nodeInstance = nodeVariant.createInstance() // Position nicely, assuming a 40x40 grid. nodeInstance.x += svgX * 40 nodeInstance.y += svgY * 40 nodeInstance.resize(24, 24) // Finalize name. // "Icon/Bitcoin circle" with variant "Style=Outline" becomes // "outline/bitcoin-circle" let newName = 'svg/' + subFolder + node.name.split('/')[1] newName = newName.toLowerCase().replace(/ /g, '-') nodeInstance.name = newName console.log('newName', newName) nodeInstance.exportSettings = [ { contentsOnly: true, format: 'SVG', suffix: '', svgIdAttribute: false, svgOutlineText: true, svgSimplifyStroke: true } ] // Add instance to our new page. page.appendChild(nodeInstance) // Detach from main component. nodeInstance = nodeInstance.detachInstance() // Delete hidden children deleteHiddenChildren(nodeInstance) flattenBooleanGroups(nodeInstance) flattenRotatedGroupsOnFilledIcon(nodeInstance) outlineStrokesOnFilledIcon(nodeInstance) checkIcon(nodeInstance) // Keep track of instances for selection. newNodes.push(nodeInstance) const iconName = newName.split('/')[2] const folderName = newName.split('/')[1] let iconInfo:any = iconData[iconName] if(!iconInfo) { iconInfo = { name: node.name.split('/')[1] } } iconInfo[folderName] = true iconInfo.svg = true if(node.description) { iconInfo.description = node.description } iconInfo.id = toPascalCase(iconName) iconData[iconName] = iconInfo svgX++ // Reset the row every 10 icons if(svgX >= 10) { svgX = 0 svgY += 1 } } // Deletes hidden children function deleteHiddenChildren(nodeInstance) { let child for(let i=0; i<nodeInstance.children.length; i++) { child = nodeInstance.children[i] if(child.visible !== true) { // Delete invisible child. child.remove() i-- } else if(child.type == 'GROUP') { // If it's a group, go deeper. deleteHiddenChildren(child) } } } // Flattens boolean groups function flattenBooleanGroups(nodeInstance, fullNodeName = null) { if(!fullNodeName) { fullNodeName = nodeInstance.name } else { fullNodeName += '/' + nodeInstance.name } // console.log('flattenBooleanGroups', nodeInstance, fullNodeName) let child, flattenedChild for(let i=0; i<nodeInstance.children.length; i++) { child = nodeInstance.children[i] if(child.type == 'GROUP') { // If it's a group, go deeper. flattenBooleanGroups(child, fullNodeName) } else if(child.type == 'BOOLEAN_OPERATION' && child.visible !== false) { // Flatten boolean groups. if(child.children.length > 0) { try { // console.log('f', child, child.name, child.visible, fullNodeName) flattenedChild = figma.flatten([child], child.parent, i) // console.log('flattenedChild', flattenedChild, flattenedChild.fills, fullNodeName, flattenedChild.name) } catch(error) { console.log('error', error) } } } } } function flattenRotatedGroupsOnFilledIcon(nodeInstance, fullNodeName = null) { if(!fullNodeName) { fullNodeName = nodeInstance.name } else { fullNodeName += '/' + nodeInstance.name } let child, flattenedChild if(nodeInstance.children) { for(let i=0; i<nodeInstance.children.length; i++) { child = nodeInstance.children[i] flattenedChild = null if(child.visible === true) { if(fullNodeName.indexOf('filled') !== -1 && child.rotation != 0) { // Flatten boolean groups. try { flattenedChild = figma.flatten([child], child.parent, i) } catch(error) { console.log('error', error) } } if(flattenedChild) { if(flattenedChild.type == 'GROUP') { // If it's a group, go deeper. flattenRotatedGroupsOnFilledIcon(flattenedChild, fullNodeName) } } else if(child) { if(child.type == 'GROUP') { // If it's a group, go deeper. flattenRotatedGroupsOnFilledIcon(child, fullNodeName) } } } } } } function outlineStrokesOnFilledIcon(nodeInstance, fullNodeName = null) { if(!fullNodeName) { fullNodeName = nodeInstance.name } else { fullNodeName += '/' + nodeInstance.name } // console.log('outlineStrokesOnFilledIcon', nodeInstance, fullNodeName) // console.log('nodeInstance.children', nodeInstance.children) let child, flattenedChild, newChild if(nodeInstance.children) { for(let i=0; i<nodeInstance.children.length; i++) { child = nodeInstance.children[i] // console.log('i', i, fullNodeName, child) // console.log('child.name', child.name) // console.log('child.visible', child.visible) // console.log('child.type', child.type) // console.log('child.strokes', child.strokes) // console.log('child.children', child.children) if(child.visible === true) { if(child.type == 'GROUP') { // If it's a group, go deeper. // console.log('Go deeper', child, fullNodeName, child.children, child.name) outlineStrokesOnFilledIcon(child, fullNodeName) } else if(fullNodeName.indexOf('filled') !== -1 && child.strokes && child.strokes.length > 0) { // Flattening a stroke on a filled icon // console.log('Flatting stroke', fullNodeName, child.name) try { newChild = child.outlineStroke() // console.log('newChild', newChild, child.strokes, child.strokeWeight) child.parent.insertChild(i, newChild) // The new position needs to be offset by half the stroke weight. // Turning the vector into a shape affects the boundary box. newChild.x = child.x - child.strokeWeight / 2 newChild.y = child.y - child.strokeWeight / 2 child.remove() } catch(error) { console.log('error', error) } } } } } } // Checks if icons are clean // Outline icon shapes should not have fills // Filled icon shapes should not have outlines function checkIcon(nodeInstance, fullNodeName = null) { if(!fullNodeName) { fullNodeName = nodeInstance.name } else { fullNodeName += '/' + nodeInstance.name } const trimmedName = fullNodeName.split('/').splice(0, 3).join('/') if(fullNodeName.indexOf('outline') !== -1 && nodeInstance.fills && nodeInstance.fills.length > 0) { // console.log('Outline icon "' + fullNodeName + '" has fills - fix it!') logIconProblem(trimmedName, 'fill-on-outline-icon') } if(fullNodeName.indexOf('filled') !== -1 && nodeInstance.strokes && nodeInstance.strokes.length > 0) { // console.log('Filled icon "' + fullNodeName + '" has strokes - fix it!') logIconProblem(trimmedName, 'outline-on-filled-icon') } if(fullNodeName.indexOf('filled') !== -1 && nodeInstance.type == 'GROUP' && nodeInstance.rotation != 0) { logIconProblem(trimmedName, 'rotated-group') } if(nodeInstance.children) { let child for(let i=0; i<nodeInstance.children.length; i++) { child = nodeInstance.children[i] if(child.visible === true) { checkIcon(child, fullNodeName) } } } } function logIconProblem(name, problem) { if(!problematicIcons[name]) { problematicIcons[name] = {} } problematicIcons[name][problem] = true } function exportComponentAsPNG(node, nodeVariant, subFolder) { const nodeInstance = nodeVariant.createInstance() // Position nicely, assuming a 40x40 grid. nodeInstance.x += (12 + pngX) * 40 nodeInstance.y += pngY * 40 nodeInstance.resize(24, 24) // Finalize name. // "Icon/Bitcoin circle" with variant "Style=Outline" becomes // "outline/bitcoin-circle" let newName = 'png/' + subFolder + node.name.split('/')[1] newName = newName.toLowerCase().replace(/ /g, '-') nodeInstance.name = newName nodeInstance.exportSettings = [ { contentsOnly: true, format: 'PNG' } ] // Add instance to our new page. page.appendChild(nodeInstance) // Keep track of instances for selection. newNodes.push(nodeInstance) const iconName = newName.split('/')[2] iconData[iconName].png = true pngX++ // Reset the row every 10 icons if(pngX >= 10) { pngX = 0 pngY += 1 } } // Create instance of each component and variant for (const node of nodes) { // Only use components with variants. if(node.type === 'COMPONENT_SET') { // Loop all component variants. for(const nodeVariant of node.children) { if(nodeVariant.type === 'COMPONENT') { if(nodeVariant.type === 'COMPONENT') { let exportIcon = false // Variant settings are stored in the instance name. // Use them to figure out whether to export and into which folder. // "Style=Filled, Size=Big" const variantNameBits = nodeVariant.name.split(', ') let subFolder = '' for(const bit of variantNameBits) { const subBits = bit.split('=') switch(subBits[0]) { case 'Style': // Use the style name as folder name subFolder = subBits[1] + '/' break; case 'Size': // Only export Medium sizes for now exportIcon = subBits[1] == 'Medium' break; } } // For testing individual icons. // if(node.name.indexOf('Arrow right') === -1) { // exportIcon = false // } if(exportIcon === true) { processedIcons++ exportComponentAsSVG(node, nodeVariant, subFolder) exportComponentAsPNG(node, nodeVariant, subFolder) } } } } } } console.log('Problematic icons', problematicIcons) console.log('Processed icons', processedIcons) // Select our new instances for easy export. page.selection = newNodes // Go to our new page. figma.currentPage = page // Create a text node to store JSON data. const textNode = figma.createText() textNode.x = 1000 textNode.resize(1000, 1000) figma.loadFontAsync({ family: "Roboto", style: "Regular" }).then(() => { textNode.characters = JSON.stringify(iconData) figma.closePlugin() })
the_stack
module android.graphics.drawable { import Rect = android.graphics.Rect; import PixelFormat = android.graphics.PixelFormat; import WeakReference = java.lang.ref.WeakReference; import Runnable = java.lang.Runnable; import StateSet = android.util.StateSet; import Canvas = android.graphics.Canvas; import Resources = android.content.res.Resources; import NetDrawable = androidui.image.NetDrawable; /** * A Drawable is a general abstraction for "something that can be drawn." Most * often you will deal with Drawable as the type of resource retrieved for * drawing things to the screen; the Drawable class provides a generic API for * dealing with an underlying visual resource that may take a variety of forms. * Unlike a {@link android.view.View}, a Drawable does not have any facility to * receive events or otherwise interact with the user. * * <p>In addition to simple drawing, Drawable provides a number of generic * mechanisms for its client to interact with what is being drawn: * * <ul> * <li> The {@link #setBounds} method <var>must</var> be called to tell the * Drawable where it is drawn and how large it should be. All Drawables * should respect the requested size, often simply by scaling their * imagery. A client can find the preferred size for some Drawables with * the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods. * * <li> The {@link #getPadding} method can return from some Drawables * information about how to frame content that is placed inside of them. * For example, a Drawable that is intended to be the frame for a button * widget would need to return padding that correctly places the label * inside of itself. * * <li> The {@link #setState} method allows the client to tell the Drawable * in which state it is to be drawn, such as "focused", "selected", etc. * Some drawables may modify their imagery based on the selected state. * * <li> The {@link #setLevel} method allows the client to supply a single * continuous controller that can modify the Drawable is displayed, such as * a battery level or progress level. Some drawables may modify their * imagery based on the current level. * * <li> A Drawable can perform animations by calling back to its client * through the {@link Callback} interface. All clients should support this * interface (via {@link #setCallback}) so that animations will work. A * simple way to do this is through the system facilities such as * {@link android.view.View#setBackgroundDrawable(Drawable)} and * {@link android.widget.ImageView}. * </ul> * * Though usually not visible to the application, Drawables may take a variety * of forms: * * <ul> * <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image. * <li> <b>Nine Patch</b>: an extension to the PNG format allows it to * specify information about how to stretch it and place things inside of * it. * <li> <b>Shape</b>: contains simple drawing commands instead of a raw * bitmap, allowing it to resize better in some cases. * <li> <b>Layers</b>: a compound drawable, which draws multiple underlying * drawables on top of each other. * <li> <b>States</b>: a compound drawable that selects one of a set of * drawables based on its state. * <li> <b>Levels</b>: a compound drawable that selects one of a set of * drawables based on its level. * <li> <b>Scale</b>: a compound drawable with a single child drawable, * whose overall size is modified based on the current level. * </ul> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about how to use drawables, read the * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and Drawables</a> developer * guide. For information and examples of creating drawable resources (XML or bitmap files that * can be loaded in code), read the * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a> * document.</p></div> */ export abstract class Drawable { private static ZERO_BOUNDS_RECT = new Rect(); mBounds:Rect = Drawable.ZERO_BOUNDS_RECT;// lazily becomes a new Rect() mStateSet = StateSet.WILD_CARD; mLevel = 0; mVisible = true; mCallback:WeakReference<Drawable.Callback>; private mIgnoreNotifySizeChange = false; constructor() { } /** * Draw in its bounds (set via setBounds) respecting optional effects such * as alpha (set via setAlpha) and color filter (set via setColorFilter). * * @param canvas The canvas to draw into */ abstract draw(canvas:Canvas); /** * Specify a bounding rectangle for the Drawable. This is where the drawable * will draw when its draw() method is called. */ setBounds(rect:Rect); /** * Specify a bounding rectangle for the Drawable. This is where the drawable * will draw when its draw() method is called. */ setBounds(left, top, right, bottom); setBounds(...args) { if (args.length === 1) { let rect = args[0]; return this.setBounds(rect.left, rect.top, rect.right, rect.bottom); } else { let [left=0, top=0, right=0, bottom=0] = args; let oldBounds = this.mBounds; if (oldBounds == Drawable.ZERO_BOUNDS_RECT) { oldBounds = this.mBounds = new Rect(); } if (oldBounds.left != left || oldBounds.top != top || oldBounds.right != right || oldBounds.bottom != bottom) { if (!oldBounds.isEmpty()) { // first invalidate the previous bounds this.invalidateSelf(); } this.mBounds.set(left, top, right, bottom); this.onBoundsChange(this.mBounds); } } } /** * Return a copy of the drawable's bounds in the specified Rect (allocated * by the caller). The bounds specify where this will draw when its draw() * method is called. * * @param bounds Rect to receive the drawable's bounds (allocated by the * caller). */ copyBounds(bounds = new Rect()) { bounds.set(this.mBounds); return bounds; } /** * Return the drawable's bounds Rect. Note: for efficiency, the returned * object may be the same object stored in the drawable (though this is not * guaranteed), so if a persistent copy of the bounds is needed, call * copyBounds(rect) instead. * You should also not change the object returned by this method as it may * be the same object stored in the drawable. * * @return The bounds of the drawable (which may change later, so caller * beware). DO NOT ALTER the returned object as it may change the * stored bounds of this drawable. * * @see #copyBounds() * @see #copyBounds(android.graphics.Rect) */ getBounds():Rect { if (this.mBounds == Drawable.ZERO_BOUNDS_RECT) { this.mBounds = new Rect(); } return this.mBounds; } /** * Set to true to have the drawable dither its colors when drawn to a device * with fewer than 8-bits per color component. This can improve the look on * those devices, but can also slow down the drawing a little. */ setDither(dither:boolean) {} /** * Bind a {@link Callback} object to this Drawable. Required for clients * that want to support animated drawables. * * @param cb The client's Callback implementation. * * @see #getCallback() */ setCallback(cb:Drawable.Callback) { this.mCallback = new WeakReference(cb); } /** * Return the current {@link Callback} implementation attached to this * Drawable. * * @return A {@link Callback} instance or null if no callback was set. * * @see #setCallback(android.graphics.drawable.Drawable.Callback) */ getCallback():Drawable.Callback { if (this.mCallback != null) { return this.mCallback.get(); } return null; } /** * by default, NetDrawable will change it's bound when load image finish. * If you wan lock a bound to a NetDrawable, you shound call this method to ignore it. */ setIgnoreNotifySizeChange(isIgnore:boolean):void { this.mIgnoreNotifySizeChange = isIgnore; } /** * AndroidUI add: notity size change */ notifySizeChangeSelf() { if(this.mIgnoreNotifySizeChange) return; let callback = this.getCallback(); if (callback != null && callback.drawableSizeChange) { callback.drawableSizeChange(this); } } /** * Use the current {@link Callback} implementation to have this Drawable * redrawn. Does nothing if there is no Callback attached to the * Drawable. * * @see Callback#invalidateDrawable * @see #getCallback() * @see #setCallback(android.graphics.drawable.Drawable.Callback) */ invalidateSelf() { let callback = this.getCallback(); if (callback != null) { callback.invalidateDrawable(this); } } /** * Use the current {@link Callback} implementation to have this Drawable * scheduled. Does nothing if there is no Callback attached to the * Drawable. * * @param what The action being scheduled. * @param when The time (in milliseconds) to run. * * @see Callback#scheduleDrawable */ scheduleSelf(what, when) { let callback = this.getCallback(); if (callback != null) { callback.scheduleDrawable(this, what, when); } } /** * Use the current {@link Callback} implementation to have this Drawable * unscheduled. Does nothing if there is no Callback attached to the * Drawable. * * @param what The runnable that you no longer want called. * * @see Callback#unscheduleDrawable */ unscheduleSelf(what) { let callback = this.getCallback(); if (callback != null) { callback.unscheduleDrawable(this, what); } } /** * Specify an alpha value for the drawable. 0 means fully transparent, and * 255 means fully opaque. */ abstract setAlpha(alpha:number):void; /** * Gets the current alpha value for the drawable. 0 means fully transparent, * 255 means fully opaque. This method is implemented by * Drawable subclasses and the value returned is specific to how that class treats alpha. * The default return value is 255 if the class does not override this method to return a value * specific to its use of alpha. */ getAlpha():number { return 0xFF; } /** * Indicates whether this view will change its appearance based on state. * Clients can use this to determine whether it is necessary to calculate * their state and call setState. * * @return True if this view changes its appearance based on state, false * otherwise. * * @see #setState(int[]) */ isStateful():boolean { return false; } /** * Specify a set of states for the drawable. These are use-case specific, * so see the relevant documentation. As an example, the background for * widgets like Button understand the following states: * [{@link android.R.attr#state_focused}, * {@link android.R.attr#state_pressed}]. * * <p>If the new state you are supplying causes the appearance of the * Drawable to change, then it is responsible for calling * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em> * true will be returned from this function. * * <p>Note: The Drawable holds a reference on to <var>stateSet</var> * until a new state array is given to it, so you must not modify this * array during that time.</p> * * @param stateSet The new set of states to be displayed. * * @return Returns true if this change in state has caused the appearance * of the Drawable to change (hence requiring an invalidate), otherwise * returns false. */ setState(stateSet:Array<number>) { if (this.mStateSet+'' !== stateSet+'') { this.mStateSet = stateSet; return this.onStateChange(stateSet); } return false; } /** * Describes the current state, as a union of primitve states, such as * {@link android.R.attr#state_focused}, * {@link android.R.attr#state_selected}, etc. * Some drawables may modify their imagery based on the selected state. * @return An array of resource Ids describing the current state. */ getState():Array<number> { return this.mStateSet; } /** * If this Drawable does transition animations between states, ask that * it immediately jump to the current state and skip any active animations. */ jumpToCurrentState() { } /** * @return The current drawable that will be used by this drawable. For simple drawables, this * is just the drawable itself. For drawables that change state like * {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable * currently in use. */ getCurrent():Drawable { return this; } /** * Specify the level for the drawable. This allows a drawable to vary its * imagery based on a continuous controller, for example to show progress * or volume level. * * <p>If the new level you are supplying causes the appearance of the * Drawable to change, then it is responsible for calling * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em> * true will be returned from this function. * * @param level The new level, from 0 (minimum) to 10000 (maximum). * * @return Returns true if this change in level has caused the appearance * of the Drawable to change (hence requiring an invalidate), otherwise * returns false. */ setLevel(level:number):boolean { if (this.mLevel != level) { this.mLevel = level; return this.onLevelChange(level); } return false; } /** * Retrieve the current level. * * @return int Current level, from 0 (minimum) to 10000 (maximum). */ getLevel():number { return this.mLevel; } /** * Set whether this Drawable is visible. This generally does not impact * the Drawable's behavior, but is a hint that can be used by some * Drawables, for example, to decide whether run animations. * * @param visible Set to true if visible, false if not. * @param restart You can supply true here to force the drawable to behave * as if it has just become visible, even if it had last * been set visible. Used for example to force animations * to restart. * * @return boolean Returns true if the new visibility is different than * its previous state. */ setVisible(visible:boolean, restart:boolean) { let changed = this.mVisible != visible; if (changed) { this.mVisible = visible; this.invalidateSelf(); } return changed; } isVisible():boolean { return this.mVisible; } /** * Set whether this Drawable is automatically mirrored when its layout direction is RTL * (right-to left). See {@link android.util.LayoutDirection}. * * @param mirrored Set to true if the Drawable should be mirrored, false if not. */ setAutoMirrored(mirrored:boolean) { } /** * Tells if this Drawable will be automatically mirrored when its layout direction is RTL * right-to-left. See {@link android.util.LayoutDirection}. * * @return boolean Returns true if this Drawable will be automatically mirrored. */ isAutoMirrored():boolean { return false; } /** * Return the opacity/transparency of this Drawable. The returned value is * one of the abstract format constants in * {@link android.graphics.PixelFormat}: * {@link android.graphics.PixelFormat#UNKNOWN}, * {@link android.graphics.PixelFormat#TRANSLUCENT}, * {@link android.graphics.PixelFormat#TRANSPARENT}, or * {@link android.graphics.PixelFormat#OPAQUE}. * * <p>Generally a Drawable should be as conservative as possible with the * value it returns. For example, if it contains multiple child drawables * and only shows one of them at a time, if only one of the children is * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be * returned. You can use the method {@link #resolveOpacity} to perform a * standard reduction of two opacities to the appropriate single output. * * <p>Note that the returned value does <em>not</em> take into account a * custom alpha or color filter that has been applied by the client through * the {@link #setAlpha} or {@link #setColorFilter} methods. * * @return int The opacity class of the Drawable. * * @see android.graphics.PixelFormat */ //abstract getOpacity():number { return PixelFormat.TRANSLUCENT; } /** * Return the appropriate opacity value for two source opacities. If * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT, * that is returned; else, if either is TRANSPARENT, that is returned; * else, OPAQUE is returned. * * <p>This is to help in implementing {@link #getOpacity}. * * @param op1 One opacity value. * @param op2 Another opacity value. * * @return int The combined opacity value. * * @see #getOpacity */ static resolveOpacity(op1:number, op2:number) { if (op1 == op2) { return op1; } if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) { return PixelFormat.UNKNOWN; } if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) { return PixelFormat.TRANSLUCENT; } if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) { return PixelFormat.TRANSPARENT; } return PixelFormat.OPAQUE; } /** * Override this in your subclass to change appearance if you recognize the * specified state. * * @return Returns true if the state change has caused the appearance of * the Drawable to change (that is, it needs to be drawn), else false * if it looks the same and there is no need to redraw it since its * last state. */ protected onStateChange(state:Array<number>):boolean { return false; } /** Override this in your subclass to change appearance if you vary based * on level. * @return Returns true if the level change has caused the appearance of * the Drawable to change (that is, it needs to be drawn), else false * if it looks the same and there is no need to redraw it since its * last level. */ protected onLevelChange(level:number):boolean { return false; } /** * Override this in your subclass to change appearance if you recognize the * specified state. */ protected onBoundsChange(bounds:Rect):void { } /** * Return the intrinsic width of the underlying drawable object. Returns * -1 if it has no intrinsic width, such as with a solid color. */ getIntrinsicWidth():number { return -1; } /** * Return the intrinsic height of the underlying drawable object. Returns * -1 if it has no intrinsic height, such as with a solid color. */ getIntrinsicHeight():number { return -1; } /** * Returns the minimum width suggested by this Drawable. If a View uses this * Drawable as a background, it is suggested that the View use at least this * value for its width. (There will be some scenarios where this will not be * possible.) This value should INCLUDE any padding. * * @return The minimum width suggested by this Drawable. If this Drawable * doesn't have a suggested minimum width, 0 is returned. */ getMinimumWidth() { let intrinsicWidth = this.getIntrinsicWidth(); return intrinsicWidth > 0 ? intrinsicWidth : 0; } /** * Returns the minimum height suggested by this Drawable. If a View uses this * Drawable as a background, it is suggested that the View use at least this * value for its height. (There will be some scenarios where this will not be * possible.) This value should INCLUDE any padding. * * @return The minimum height suggested by this Drawable. If this Drawable * doesn't have a suggested minimum height, 0 is returned. */ getMinimumHeight() { let intrinsicHeight = this.getIntrinsicHeight(); return intrinsicHeight > 0 ? intrinsicHeight : 0; } /** * Return in padding the insets suggested by this Drawable for placing * content inside the drawable's bounds. Positive values move toward the * center of the Drawable (set Rect.inset). Returns true if this drawable * actually has a padding, else false. When false is returned, the padding * is always set to 0. */ getPadding(padding:Rect):boolean { padding.set(0, 0, 0, 0); return false; } /** * Make this drawable mutable. This operation cannot be reversed. A mutable * drawable is guaranteed to not share its state with any other drawable. * This is especially useful when you need to modify properties of drawables * loaded from resources. By default, all drawables instances loaded from * the same resource share a common state; if you modify the state of one * instance, all the other instances will receive the same modification. * * Calling this method on a mutable Drawable will have no effect. * * @return This drawable. * @see ConstantState * @see #getConstantState() */ mutate(): Drawable { return this; } /** * Return a {@link ConstantState} instance that holds the shared state of this Drawable. *q * @return The ConstantState associated to that Drawable. * @see ConstantState * @see Drawable#mutate() */ getConstantState():Drawable.ConstantState { return null; } /** * Create a drawable from an XML document. For more information on how to * create resources in XML, see * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. */ static createFromXml(r:Resources, parser:HTMLElement):Drawable { let drawable:Drawable; let name = parser.tagName.toLowerCase(); switch (name) { case "selector": drawable = new StateListDrawable(); break; // case "animated-selector": // drawable = new AnimatedStateListDrawable(); // break; // case "level-list": // drawable = new LevelListDrawable(); // break; case "layer-list": drawable = new LayerDrawable(null); break; // case "transition": // drawable = new TransitionDrawable(); // break; // case "ripple": // drawable = new RippleDrawable(); // break; case "color": drawable = new ColorDrawable(); break; // case "shape": // drawable = new GradientDrawable(); // break; // case "vector": // drawable = new VectorDrawable(); // break; // case "animated-vector": // drawable = new AnimatedVectorDrawable(); // break; case "scale": drawable = new ScaleDrawable(); break; case "clip": drawable = new ClipDrawable(); break; case "rotate": drawable = new RotateDrawable(); break; // case "animated-rotate": // drawable = new AnimatedRotateDrawable(); // break; case "animation-list": drawable = new AnimationDrawable(); break; case "inset": drawable = new InsetDrawable(null, 0); break; case "bitmap": let srcAttr = parser.getAttribute('src'); if(!srcAttr) throw Error("XmlPullParserException: bitmap tag must have 'src' attribute"); drawable = r.getDrawable(srcAttr); break; // case "bitmap": // drawable = new BitmapDrawable(r); // if (r != null) { // ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); // } // break; // case "nine-patch": // drawable = new NinePatchDrawable(); // if (r != null) { // ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); // } // break; default: throw Error("XmlPullParserException: invalid drawable tag " + name); } drawable.inflate(r, parser); return drawable; } inflate(r:Resources, parser:HTMLElement):void { this.mVisible = (parser.getAttribute('android:visible') !== 'false'); } } export module Drawable{ /** * Implement this interface if you want to create an animated drawable that * extends {@link android.graphics.drawable.Drawable Drawable}. * Upon retrieving a drawable, use * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)} * to supply your implementation of the interface to the drawable; it uses * this interface to schedule and execute animation changes. */ export interface Callback{ /** * Called when the drawable needs to be redrawn. A view at this point * should invalidate itself (or at least the part of itself where the * drawable appears). * * @param who The drawable that is requesting the update. */ invalidateDrawable(who : Drawable):void; /** * androidui add: when drawable size change, view's size may change */ drawableSizeChange?(who : Drawable):void; /** * A Drawable can call this to schedule the next frame of its * animation. An implementation can generally simply call * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with * the parameters <var>(what, who, when)</var> to perform the * scheduling. * * @param who The drawable being scheduled. * @param what The action to execute. * @param when The time (in milliseconds) to run. The timebase is * {@link android.os.SystemClock#uptimeMillis} */ scheduleDrawable(who : Drawable, what:Runnable, when:number):void; /** * A Drawable can call this to unschedule an action previously * scheduled with {@link #scheduleDrawable}. An implementation can * generally simply call * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with * the parameters <var>(what, who)</var> to unschedule the drawable. * * @param who The drawable being unscheduled. * @param what The action being unscheduled. */ unscheduleDrawable(who: Drawable, what:Runnable):void; } /** * This abstract class is used by {@link Drawable}s to store shared constant state and data * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance * share a unique bitmap stored in their ConstantState. * * <p> * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances * from this ConstantState. * </p> * * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that * Drawable. */ export interface ConstantState{ /** * Create a new drawable without supplying resources the caller * is running in. Note that using this means the density-dependent * drawables (like bitmaps) will not be able to update their target * density correctly. One should use {@link #newDrawable(Resources)} * instead to provide a resource. */ newDrawable():Drawable; } } }
the_stack
"use strict"; import { Server, Socket, Namespace } from ".."; import { createServer } from "http"; import fs = require("fs"); import { join } from "path"; import { exec } from "child_process"; import request from "supertest"; import expect from "expect.js"; import type { AddressInfo } from "net"; import * as io_v2 from "socket.io-client-v2"; import type { SocketId } from "socket.io-adapter"; import { io as ioc, Socket as ClientSocket } from "socket.io-client"; import "./support/util"; import "./utility-methods"; // Creates a socket.io client for the given server function client(srv, nsp?: string | object, opts?: object): ClientSocket { if ("object" == typeof nsp) { opts = nsp; nsp = undefined; } let addr = srv.address(); if (!addr) addr = srv.listen().address(); const url = "ws://localhost:" + addr.port + (nsp || ""); return ioc(url, opts); } const success = (sio, clientSocket, done) => { sio.close(); clientSocket.close(); done(); }; const waitFor = (emitter, event) => { return new Promise((resolve) => { emitter.once(event, resolve); }); }; const getPort = (io: Server): number => { // @ts-ignore return io.httpServer.address().port; }; describe("socket.io", () => { it("should be the same version as client", () => { const version = require("../package").version; expect(version).to.be(require("socket.io-client/package.json").version); }); describe("server attachment", () => { describe("http.Server", () => { const clientVersion = require("socket.io-client/package.json").version; const testSource = (filename) => (done) => { const srv = createServer(); new Server(srv); request(srv) .get("/socket.io/" + filename) .buffer(true) .end((err, res) => { if (err) return done(err); expect(res.headers["content-type"]).to.be("application/javascript"); expect(res.headers.etag).to.be('"' + clientVersion + '"'); expect(res.headers["x-sourcemap"]).to.be(undefined); expect(res.text).to.match(/engine\.io/); expect(res.status).to.be(200); done(); }); }; const testSourceMap = (filename) => (done) => { const srv = createServer(); new Server(srv); request(srv) .get("/socket.io/" + filename) .buffer(true) .end((err, res) => { if (err) return done(err); expect(res.headers["content-type"]).to.be("application/json"); expect(res.headers.etag).to.be('"' + clientVersion + '"'); expect(res.text).to.match(/engine\.io/); expect(res.status).to.be(200); done(); }); }; it("should serve client", testSource("socket.io.js")); it( "should serve client with query string", testSource("socket.io.js?buster=" + Date.now()) ); it("should serve source map", testSourceMap("socket.io.js.map")); it("should serve client (min)", testSource("socket.io.min.js")); it( "should serve source map (min)", testSourceMap("socket.io.min.js.map") ); it("should serve client (gzip)", (done) => { const srv = createServer(); new Server(srv); request(srv) .get("/socket.io/socket.io.js") .set("accept-encoding", "gzip,br,deflate") .buffer(true) .end((err, res) => { if (err) return done(err); expect(res.headers["content-encoding"]).to.be("gzip"); expect(res.status).to.be(200); done(); }); }); it( "should serve bundle with msgpack parser", testSource("socket.io.msgpack.min.js") ); it( "should serve source map for bundle with msgpack parser", testSourceMap("socket.io.msgpack.min.js.map") ); it("should serve the ESM bundle", testSource("socket.io.esm.min.js")); it( "should serve the source map for the ESM bundle", testSourceMap("socket.io.esm.min.js.map") ); it("should handle 304", (done) => { const srv = createServer(); new Server(srv); request(srv) .get("/socket.io/socket.io.js") .set("If-None-Match", '"' + clientVersion + '"') .end((err, res) => { if (err) return done(err); expect(res.statusCode).to.be(304); done(); }); }); it("should handle 304", (done) => { const srv = createServer(); new Server(srv); request(srv) .get("/socket.io/socket.io.js") .set("If-None-Match", 'W/"' + clientVersion + '"') .end((err, res) => { if (err) return done(err); expect(res.statusCode).to.be(304); done(); }); }); it("should not serve static files", (done) => { const srv = createServer(); new Server(srv, { serveClient: false }); request(srv).get("/socket.io/socket.io.js").expect(400, done); }); it("should work with #attach", (done) => { const srv = createServer((req, res) => { res.writeHead(404); res.end(); }); const sockets = new Server(); sockets.attach(srv); request(srv) .get("/socket.io/socket.io.js") .end((err, res) => { if (err) return done(err); expect(res.status).to.be(200); done(); }); }); it("should work with #attach (and merge options)", () => { const srv = createServer((req, res) => { res.writeHead(404); res.end(); }); const server = new Server({ pingTimeout: 6000, }); server.attach(srv, { pingInterval: 24000, }); // @ts-ignore expect(server.eio.opts.pingTimeout).to.eql(6000); // @ts-ignore expect(server.eio.opts.pingInterval).to.eql(24000); server.close(); }); }); describe("port", () => { it("should be bound", (done) => { const io = new Server(0); request(`http://localhost:${getPort(io)}`) .get("/socket.io/socket.io.js") .expect(200, done); }); it("with listen", (done) => { const io = new Server().listen(0); request(`http://localhost:${getPort(io)}`) .get("/socket.io/socket.io.js") .expect(200, done); }); }); }); describe("handshake", () => { const request = require("superagent"); it("should send the Access-Control-Allow-xxx headers on OPTIONS request", (done) => { const io = new Server(0, { cors: { origin: "http://localhost:54023", methods: ["GET", "POST"], allowedHeaders: ["content-type"], credentials: true, }, }); request .options(`http://localhost:${getPort(io)}/socket.io/default/`) .query({ transport: "polling", EIO: 4 }) .set("Origin", "http://localhost:54023") .end((err, res) => { expect(res.status).to.be(204); expect(res.headers["access-control-allow-origin"]).to.be( "http://localhost:54023" ); expect(res.headers["access-control-allow-methods"]).to.be("GET,POST"); expect(res.headers["access-control-allow-headers"]).to.be( "content-type" ); expect(res.headers["access-control-allow-credentials"]).to.be("true"); done(); }); }); it("should send the Access-Control-Allow-xxx headers on GET request", (done) => { const io = new Server(0, { cors: { origin: "http://localhost:54024", methods: ["GET", "POST"], allowedHeaders: ["content-type"], credentials: true, }, }); request .get(`http://localhost:${getPort(io)}/socket.io/default/`) .query({ transport: "polling", EIO: 4 }) .set("Origin", "http://localhost:54024") .end((err, res) => { expect(res.status).to.be(200); expect(res.headers["access-control-allow-origin"]).to.be( "http://localhost:54024" ); expect(res.headers["access-control-allow-credentials"]).to.be("true"); done(); }); }); it("should allow request if custom function in opts.allowRequest returns true", (done) => { const io = new Server(0, { allowRequest: (req, callback) => callback(null, true), }); request .get(`http://localhost:${getPort(io)}/socket.io/default/`) .query({ transport: "polling", EIO: 4 }) .end((err, res) => { expect(res.status).to.be(200); done(); }); }); it("should disallow request if custom function in opts.allowRequest returns false", (done) => { const io = new Server(0, { allowRequest: (req, callback) => callback(null, false), }); request .get(`http://localhost:${getPort(io)}/socket.io/default/`) .set("origin", "http://foo.example") .query({ transport: "polling", EIO: 4 }) .end((err, res) => { expect(res.status).to.be(403); done(); }); }); }); describe("close", () => { it("should be able to close sio sending a srv", (done) => { const httpServer = createServer().listen(0); const io = new Server(httpServer); const port = getPort(io); const net = require("net"); const server = net.createServer(); const clientSocket = client(httpServer, { reconnection: false }); clientSocket.on("disconnect", () => { expect(io.sockets.sockets.size).to.equal(0); server.listen(port); }); clientSocket.on("connect", () => { expect(io.sockets.sockets.size).to.equal(1); io.close(); }); server.once("listening", () => { // PORT should be free server.close((error) => { expect(error).to.be(undefined); done(); }); }); }); it("should be able to close sio sending a srv", (done) => { const io = new Server(0); const port = getPort(io); const net = require("net"); const server = net.createServer(); const clientSocket = ioc("ws://0.0.0.0:" + port, { reconnection: false, }); clientSocket.on("disconnect", () => { expect(io.sockets.sockets.size).to.equal(0); server.listen(port); }); clientSocket.on("connect", () => { expect(io.sockets.sockets.size).to.equal(1); io.close(); }); server.once("listening", () => { // PORT should be free server.close((error) => { expect(error).to.be(undefined); done(); }); }); }); describe("graceful close", () => { function fixture(filename) { return ( '"' + process.execPath + '" "' + join(__dirname, "fixtures", filename) + '"' ); } it("should stop socket and timers", (done) => { exec(fixture("server-close.ts"), done); }); }); }); describe("namespaces", () => { it("should be accessible through .sockets", () => { const sio = new Server(); expect(sio.sockets).to.be.a(Namespace); }); it("should be aliased", () => { const sio = new Server(); expect(sio.use).to.be.a("function"); expect(sio.to).to.be.a("function"); expect(sio["in"]).to.be.a("function"); expect(sio.emit).to.be.a("function"); expect(sio.send).to.be.a("function"); expect(sio.write).to.be.a("function"); expect(sio.allSockets).to.be.a("function"); expect(sio.compress).to.be.a("function"); }); it("should return an immutable broadcast operator", () => { const sio = new Server(); const operator = sio.local.to(["room1", "room2"]).except("room3"); operator.compress(true).emit("hello"); operator.volatile.emit("hello"); operator.to("room4").emit("hello"); operator.except("room5").emit("hello"); sio.to("room6").emit("hello"); // @ts-ignore expect(operator.rooms).to.contain("room1", "room2"); // @ts-ignore expect(operator.exceptRooms).to.contain("room3"); // @ts-ignore expect(operator.flags).to.eql({ local: true }); }); it("should automatically connect", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); socket.on("connect", () => { done(); }); }); }); it("should fire a `connection` event", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (socket: Socket) => { expect(socket).to.be.a(Socket); done(); }); }); }); it("should fire a `connect` event", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connect", (socket) => { expect(socket).to.be.a(Socket); done(); }); }); }); it("should work with many sockets", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { sio.of("/chat"); sio.of("/news"); const chat = client(srv, "/chat"); const news = client(srv, "/news"); let total = 2; chat.on("connect", () => { --total || done(); }); news.on("connect", () => { --total || done(); }); }); }); it('should be able to equivalently start with "" or "/" on server', (done) => { const srv = createServer(); const sio = new Server(srv); let total = 2; sio.of("").on("connection", () => { --total || done(); }); sio.of("abc").on("connection", () => { --total || done(); }); const c1 = client(srv, "/"); const c2 = client(srv, "/abc"); }); it('should be equivalent for "" and "/" on client', (done) => { const srv = createServer(); const sio = new Server(srv); sio.of("/").on("connection", () => { done(); }); const c1 = client(srv, ""); }); it("should work with `of` and many sockets", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const chat = client(srv, "/chat"); const news = client(srv, "/news"); let total = 2; sio.of("/news").on("connection", (socket) => { expect(socket).to.be.a(Socket); --total || done(); }); sio.of("/news").on("connection", (socket) => { expect(socket).to.be.a(Socket); --total || done(); }); }); }); it("should work with `of` second param", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const chat = client(srv, "/chat"); const news = client(srv, "/news"); let total = 2; sio.of("/news", (socket) => { expect(socket).to.be.a(Socket); --total || done(); }); sio.of("/news", (socket) => { expect(socket).to.be.a(Socket); --total || done(); }); }); }); it("should disconnect upon transport disconnection", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const chat = client(srv, "/chat"); const news = client(srv, "/news"); let total = 2; let totald = 2; let s; sio.of("/news", (socket) => { socket.on("disconnect", (reason) => { --totald || done(); }); --total || close(); }); sio.of("/chat", (socket) => { s = socket; socket.on("disconnect", (reason) => { --totald || done(); }); --total || close(); }); function close() { s.disconnect(true); } }); }); it("should fire a `disconnecting` event just before leaving all rooms", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.join("a"); // FIXME not sure why process.nextTick() is needed here process.nextTick(() => s.disconnect()); let total = 2; s.on("disconnecting", (reason) => { expect(s.rooms).to.contain(s.id, "a"); total--; }); s.on("disconnect", (reason) => { expect(s.rooms.size).to.eql(0); --total || done(); }); }); }); }); it("should return error connecting to non-existent namespace", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, "/doesnotexist"); socket.on("connect_error", (err) => { expect(err.message).to.be("Invalid namespace"); done(); }); }); }); it("should not reuse same-namespace connections", (done) => { const srv = createServer(); const sio = new Server(srv); let connections = 0; srv.listen(() => { const clientSocket1 = client(srv); const clientSocket2 = client(srv); sio.on("connection", () => { connections++; if (connections === 2) { done(); } }); }); }); it("should find all clients in a namespace", (done) => { const srv = createServer(); const sio = new Server(srv); const chatSids: string[] = []; let otherSid: SocketId | null = null; srv.listen(() => { const c1 = client(srv, "/chat"); const c2 = client(srv, "/chat", { forceNew: true }); const c3 = client(srv, "/other", { forceNew: true }); let total = 3; sio.of("/chat").on("connection", (socket) => { chatSids.push(socket.id); --total || getSockets(); }); sio.of("/other").on("connection", (socket) => { otherSid = socket.id; --total || getSockets(); }); }); async function getSockets() { const sids = await sio.of("/chat").allSockets(); expect(sids).to.contain(chatSids[0], chatSids[1]); expect(sids).to.not.contain(otherSid); done(); } }); it("should find all clients in a namespace room", (done) => { const srv = createServer(); const sio = new Server(srv); let chatFooSid: SocketId | null = null; let chatBarSid: SocketId | null = null; let otherSid: SocketId | null = null; srv.listen(() => { const c1 = client(srv, "/chat"); const c2 = client(srv, "/chat", { forceNew: true }); const c3 = client(srv, "/other", { forceNew: true }); let chatIndex = 0; let total = 3; sio.of("/chat").on("connection", (socket) => { if (chatIndex++) { socket.join("foo"); chatFooSid = socket.id; --total || getSockets(); } else { socket.join("bar"); chatBarSid = socket.id; --total || getSockets(); } }); sio.of("/other").on("connection", (socket) => { socket.join("foo"); otherSid = socket.id; --total || getSockets(); }); }); async function getSockets() { const sids = await sio.of("/chat").in("foo").allSockets(); expect(sids).to.contain(chatFooSid); expect(sids).to.not.contain(chatBarSid); expect(sids).to.not.contain(otherSid); done(); } }); it("should find all clients across namespace rooms", (done) => { const srv = createServer(); const sio = new Server(srv); let chatFooSid: SocketId | null = null; let chatBarSid: SocketId | null = null; let otherSid: SocketId | null = null; srv.listen(() => { const c1 = client(srv, "/chat"); const c2 = client(srv, "/chat", { forceNew: true }); const c3 = client(srv, "/other", { forceNew: true }); let chatIndex = 0; let total = 3; sio.of("/chat").on("connection", (socket) => { if (chatIndex++) { socket.join("foo"); chatFooSid = socket.id; --total || getSockets(); } else { socket.join("bar"); chatBarSid = socket.id; --total || getSockets(); } }); sio.of("/other").on("connection", (socket) => { socket.join("foo"); otherSid = socket.id; --total || getSockets(); }); }); async function getSockets() { const sids = await sio.of("/chat").allSockets(); expect(sids).to.contain(chatFooSid, chatBarSid); expect(sids).to.not.contain(otherSid); done(); } }); it("should not emit volatile event after regular event", (done) => { const srv = createServer(); const sio = new Server(srv); let counter = 0; srv.listen(() => { sio.of("/chat").on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { sio.of("/chat").emit("ev", "data"); sio.of("/chat").volatile.emit("ev", "data"); }, 50); }); const socket = client(srv, "/chat"); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 500); }); it("should emit volatile event", (done) => { const srv = createServer(); const sio = new Server(srv); let counter = 0; srv.listen(() => { sio.of("/chat").on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { sio.of("/chat").volatile.emit("ev", "data"); }, 100); }); const socket = client(srv, "/chat"); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 500); }); it("should enable compression by default", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, "/chat"); sio.of("/chat").on("connection", (s) => { s.conn.once("packetCreate", (packet) => { expect(packet.options.compress).to.be(true); done(); }); sio.of("/chat").emit("woot", "hi"); }); }); }); it("should disable compression", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, "/chat"); sio.of("/chat").on("connection", (s) => { s.conn.once("packetCreate", (packet) => { expect(packet.options.compress).to.be(false); done(); }); sio.of("/chat").compress(false).emit("woot", "hi"); }); }); }); it("should throw on reserved event", () => { const sio = new Server(); expect(() => sio.emit("connect")).to.throwException( /"connect" is a reserved event name/ ); }); it("should close a client without namespace", (done) => { const srv = createServer(); const sio = new Server(srv, { connectTimeout: 10, }); srv.listen(() => { const socket = client(srv); // @ts-ignore socket.io.engine.write = () => {}; // prevent the client from sending a CONNECT packet socket.on("disconnect", () => { socket.close(); sio.close(); done(); }); }); }); it("should close a client without namespace (2)", (done) => { const srv = createServer(); const sio = new Server(srv, { connectTimeout: 100, }); sio.use((_, next) => { next(new Error("nope")); }); srv.listen(() => { const socket = client(srv); const success = () => { socket.close(); sio.close(); done(); }; socket.on("disconnect", success); }); }); it("should exclude a specific socket when emitting", (done) => { const srv = createServer(); const io = new Server(srv); srv.listen(() => { const socket1 = client(srv, "/"); const socket2 = client(srv, "/"); socket2.on("a", () => { done(new Error("should not happen")); }); socket1.on("a", () => { done(); }); socket2.on("connect", () => { io.except(socket2.id).emit("a"); }); }); }); it("should exclude a specific socket when emitting (in a namespace)", (done) => { const srv = createServer(); const sio = new Server(srv); const nsp = sio.of("/nsp"); srv.listen(() => { const socket1 = client(srv, "/nsp"); const socket2 = client(srv, "/nsp"); socket2.on("a", () => { done(new Error("not")); }); socket1.on("a", () => { done(); }); socket2.on("connect", () => { nsp.except(socket2.id).emit("a"); }); }); }); it("should exclude a specific room when emitting", (done) => { const srv = createServer(); const sio = new Server(srv); const nsp = sio.of("/nsp"); srv.listen(() => { const socket1 = client(srv, "/nsp"); const socket2 = client(srv, "/nsp"); socket1.on("a", () => { done(); }); socket2.on("a", () => { done(new Error("not")); }); nsp.on("connection", (socket) => { socket.on("broadcast", () => { socket.join("room1"); nsp.except("room1").emit("a"); }); }); socket2.emit("broadcast"); }); }); it("should emit an 'new_namespace' event", (done) => { const sio = new Server(); sio.on("new_namespace", (namespace) => { expect(namespace.name).to.eql("/nsp"); done(); }); sio.of("/nsp"); }); describe("dynamic namespaces", () => { it("should allow connections to dynamic namespaces with a regex", (done) => { const srv = createServer(); const sio = new Server(srv); let count = 0; srv.listen(() => { const socket = client(srv, "/dynamic-101"); let dynamicNsp = sio .of(/^\/dynamic-\d+$/) .on("connect", (socket) => { expect(socket.nsp.name).to.be("/dynamic-101"); dynamicNsp.emit("hello", 1, "2", { 3: "4" }); if (++count === 4) done(); }) .use((socket, next) => { next(); if (++count === 4) done(); }); socket.on("connect_error", (err) => { expect().fail(); }); socket.on("connect", () => { if (++count === 4) done(); }); socket.on("hello", (a, b, c) => { expect(a).to.eql(1); expect(b).to.eql("2"); expect(c).to.eql({ 3: "4" }); if (++count === 4) done(); }); }); }); it("should allow connections to dynamic namespaces with a function", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, "/dynamic-101"); sio.of((name, query, next) => next(null, "/dynamic-101" === name)); socket.on("connect", done); }); }); it("should disallow connections when no dynamic namespace matches", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, "/abc"); sio.of(/^\/dynamic-\d+$/); sio.of((name, query, next) => next(null, "/dynamic-101" === name)); socket.on("connect_error", (err) => { expect(err.message).to.be("Invalid namespace"); done(); }); }); }); it("should emit an 'new_namespace' event for a dynamic namespace", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { sio.of(/^\/dynamic-\d+$/); sio.on("new_namespace", (namespace) => { expect(namespace.name).to.be("/dynamic-101"); socket.disconnect(); srv.close(); done(); }); const socket = client(srv, "/dynamic-101"); }); }); }); }); describe("socket", () => { it("should not fire events more than once after manually reconnecting", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const clientSocket = client(srv, { reconnection: false }); clientSocket.on("connect", function init() { clientSocket.off("connect", init); clientSocket.io.engine.close(); process.nextTick(() => { clientSocket.connect(); }); clientSocket.on("connect", () => { done(); }); }); }); }); it("should not fire reconnect_failed event more than once when server closed", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const clientSocket = client(srv, { reconnectionAttempts: 3, reconnectionDelay: 100, }); clientSocket.on("connect", () => { srv.close(); }); clientSocket.io.on("reconnect_failed", () => { done(); }); }); }); it("should receive events", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("random", (a, b, c) => { expect(a).to.be(1); expect(b).to.be("2"); expect(c).to.eql([3]); done(); }); socket.emit("random", 1, "2", [3]); }); }); }); it("should receive message events through `send`", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("message", (a) => { expect(a).to.be(1337); done(); }); socket.send(1337); }); }); }); it("should error with null messages", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("message", (a) => { expect(a).to.be(null); done(); }); socket.send(null); }); }); }); it("should handle transport null messages", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { reconnection: false }); sio.on("connection", (s) => { s.on("error", (err) => { expect(err).to.be.an(Error); s.on("disconnect", (reason) => { expect(reason).to.be("forced close"); done(); }); }); (s as any).client.ondata(null); }); }); }); it("should emit events", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); socket.on("woot", (a) => { expect(a).to.be("tobi"); done(); }); sio.on("connection", (s) => { s.emit("woot", "tobi"); }); }); }); it("should emit events with utf8 multibyte character", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); let i = 0; socket.on("hoot", (a) => { expect(a).to.be("utf8 — string"); i++; if (3 == i) { done(); } }); sio.on("connection", (s) => { s.emit("hoot", "utf8 — string"); s.emit("hoot", "utf8 — string"); s.emit("hoot", "utf8 — string"); }); }); }); it("should emit events with binary data", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); let imageData; socket.on("doge", (a) => { expect(Buffer.isBuffer(a)).to.be(true); expect(imageData.length).to.equal(a.length); expect(imageData[0]).to.equal(a[0]); expect(imageData[imageData.length - 1]).to.equal(a[a.length - 1]); done(); }); sio.on("connection", (s) => { fs.readFile(join(__dirname, "support", "doge.jpg"), (err, data) => { if (err) return done(err); imageData = data; s.emit("doge", data); }); }); }); }); it("should emit events with several types of data (including binary)", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); socket.on("multiple", (a, b, c, d, e, f) => { expect(a).to.be(1); expect(Buffer.isBuffer(b)).to.be(true); expect(c).to.be("3"); expect(d).to.eql([4]); expect(Buffer.isBuffer(e)).to.be(true); expect(Buffer.isBuffer(f[0])).to.be(true); expect(f[1]).to.be("swag"); expect(Buffer.isBuffer(f[2])).to.be(true); done(); }); sio.on("connection", (s) => { fs.readFile(join(__dirname, "support", "doge.jpg"), (err, data) => { if (err) return done(err); const buf = Buffer.from("asdfasdf", "utf8"); s.emit("multiple", 1, data, "3", [4], buf, [data, "swag", buf]); }); }); }); }); it("should receive events with binary data", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("buff", (a) => { expect(Buffer.isBuffer(a)).to.be(true); done(); }); const buf = Buffer.from("abcdefg", "utf8"); socket.emit("buff", buf); }); }); }); it("should receive events with several types of data (including binary)", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("multiple", (a, b, c, d, e, f) => { expect(a).to.be(1); expect(Buffer.isBuffer(b)).to.be(true); expect(c).to.be("3"); expect(d).to.eql([4]); expect(Buffer.isBuffer(e)).to.be(true); expect(Buffer.isBuffer(f[0])).to.be(true); expect(f[1]).to.be("swag"); expect(Buffer.isBuffer(f[2])).to.be(true); done(); }); fs.readFile(join(__dirname, "support", "doge.jpg"), (err, data) => { if (err) return done(err); const buf = Buffer.from("asdfasdf", "utf8"); socket.emit("multiple", 1, data, "3", [4], buf, [ data, "swag", buf, ]); }); }); }); }); it("should not emit volatile event after regular event (polling)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["polling"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { s.emit("ev", "data"); s.volatile.emit("ev", "data"); }); const socket = client(srv, { transports: ["polling"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 200); }); it("should not emit volatile event after regular event (ws)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["websocket"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { s.emit("ev", "data"); s.volatile.emit("ev", "data"); }); const socket = client(srv, { transports: ["websocket"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 200); }); it("should emit volatile event (polling)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["polling"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { s.volatile.emit("ev", "data"); }, 100); }); const socket = client(srv, { transports: ["polling"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 500); }); it("should emit volatile event (ws)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["websocket"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { s.volatile.emit("ev", "data"); }, 20); }); const socket = client(srv, { transports: ["websocket"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 200); }); it("should emit only one consecutive volatile event (polling)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["polling"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { s.volatile.emit("ev", "data"); s.volatile.emit("ev", "data"); }, 100); }); const socket = client(srv, { transports: ["polling"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 500); }); it("should emit only one consecutive volatile event (ws)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["websocket"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { s.volatile.emit("ev", "data"); s.volatile.emit("ev", "data"); }, 20); }); const socket = client(srv, { transports: ["websocket"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 200); }); it("should emit only one consecutive volatile event with binary (ws)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["websocket"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { s.volatile.emit("ev", Buffer.from([1, 2, 3])); s.volatile.emit("ev", Buffer.from([4, 5, 6])); }, 20); }); const socket = client(srv, { transports: ["websocket"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(1); done(); }, 200); }); it("should emit regular events after trying a failed volatile event (polling)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["polling"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { s.emit("ev", "data"); s.volatile.emit("ev", "data"); s.emit("ev", "data"); }, 20); }); const socket = client(srv, { transports: ["polling"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(2); done(); }, 200); }); it("should emit regular events after trying a failed volatile event (ws)", (done) => { const srv = createServer(); const sio = new Server(srv, { transports: ["websocket"] }); let counter = 0; srv.listen(() => { sio.on("connection", (s) => { // Wait to make sure there are no packets being sent for opening the connection setTimeout(() => { s.emit("ev", "data"); s.volatile.emit("ev", "data"); s.emit("ev", "data"); }, 20); }); const socket = client(srv, { transports: ["websocket"] }); socket.on("ev", () => { counter++; }); }); setTimeout(() => { expect(counter).to.be(2); done(); }, 200); }); it("should emit message events through `send`", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); socket.on("message", (a) => { expect(a).to.be("a"); done(); }); sio.on("connection", (s) => { s.send("a"); }); }); }); it("should receive event with callbacks", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("woot", (fn) => { fn(1, 2); }); socket.emit("woot", (a, b) => { expect(a).to.be(1); expect(b).to.be(2); done(); }); }); }); }); it("should receive all events emitted from namespaced client immediately and in order", (done) => { const srv = createServer(); const sio = new Server(srv); let total = 0; srv.listen(() => { sio.of("/chat", (s) => { s.on("hi", (letter) => { total++; if (total == 2 && letter == "b") { done(); } else if (total == 1 && letter != "a") { throw new Error("events out of order"); } }); }); const chat = client(srv, "/chat"); chat.emit("hi", "a"); setTimeout(() => { chat.emit("hi", "b"); }, 50); }); }); it("should emit events with callbacks", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { socket.on("hi", (fn) => { fn(); }); s.emit("hi", () => { done(); }); }); }); }); it("should receive events with args and callback", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("woot", (a, b, fn) => { expect(a).to.be(1); expect(b).to.be(2); fn(); }); socket.emit("woot", 1, 2, () => { done(); }); }); }); }); it("should emit events with args and callback", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { socket.on("hi", (a, b, fn) => { expect(a).to.be(1); expect(b).to.be(2); fn(); }); s.emit("hi", 1, 2, () => { done(); }); }); }); }); it("should receive events with binary args and callbacks", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("woot", (buf, fn) => { expect(Buffer.isBuffer(buf)).to.be(true); fn(1, 2); }); socket.emit("woot", Buffer.alloc(3), (a, b) => { expect(a).to.be(1); expect(b).to.be(2); done(); }); }); }); }); it("should emit events with binary args and callback", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { socket.on("hi", (a, fn) => { expect(Buffer.isBuffer(a)).to.be(true); fn(); }); s.emit("hi", Buffer.alloc(4), () => { done(); }); }); }); }); it("should emit events and receive binary data in a callback", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { socket.on("hi", (fn) => { fn(Buffer.alloc(1)); }); s.emit("hi", (a) => { expect(Buffer.isBuffer(a)).to.be(true); done(); }); }); }); }); it("should receive events and pass binary data in a callback", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.on("woot", (fn) => { fn(Buffer.alloc(2)); }); socket.emit("woot", (a) => { expect(Buffer.isBuffer(a)).to.be(true); done(); }); }); }); }); it("should have access to the client", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { expect(s.client).to.be.an("object"); done(); }); }); }); it("should have access to the connection", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { expect(s.client.conn).to.be.an("object"); expect(s.conn).to.be.an("object"); done(); }); }); }); it("should have access to the request", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { expect(s.client.request.headers).to.be.an("object"); expect(s.request.headers).to.be.an("object"); done(); }); }); }); it("should see query parameters in the request", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { query: { key1: 1, key2: 2 } }); sio.on("connection", (s) => { const parsed = require("url").parse(s.request.url); const query = require("querystring").parse(parsed.query); expect(query.key1).to.be("1"); expect(query.key2).to.be("2"); done(); }); }); }); it("should see query parameters sent from secondary namespace connections in handshake object", (done) => { const srv = createServer(); const sio = new Server(srv); const client1 = client(srv); const client2 = client(srv, "/connection2", { auth: { key1: "aa", key2: "&=bb" }, }); sio.on("connection", (s) => {}); sio.of("/connection2").on("connection", (s) => { expect(s.handshake.query.key1).to.be(undefined); expect(s.handshake.query.EIO).to.be("4"); expect(s.handshake.auth.key1).to.be("aa"); expect(s.handshake.auth.key2).to.be("&=bb"); done(); }); }); it("should handle very large json", function (done) { this.timeout(30000); const srv = createServer(); const sio = new Server(srv, { perMessageDeflate: false }); let received = 0; srv.listen(() => { const socket = client(srv); socket.on("big", (a) => { expect(Buffer.isBuffer(a.json)).to.be(false); if (++received == 3) done(); else socket.emit("big", a); }); sio.on("connection", (s) => { fs.readFile( join(__dirname, "fixtures", "big.json"), (err, data: any) => { if (err) return done(err); data = JSON.parse(data); s.emit("big", { hello: "friend", json: data }); } ); s.on("big", (a) => { s.emit("big", a); }); }); }); }); it("should handle very large binary data", function (done) { this.timeout(30000); const srv = createServer(); const sio = new Server(srv, { perMessageDeflate: false }); let received = 0; srv.listen(() => { const socket = client(srv); socket.on("big", (a) => { expect(Buffer.isBuffer(a.image)).to.be(true); if (++received == 3) done(); else socket.emit("big", a); }); sio.on("connection", (s) => { fs.readFile(join(__dirname, "fixtures", "big.jpg"), (err, data) => { if (err) return done(err); s.emit("big", { hello: "friend", image: data }); }); s.on("big", (a) => { expect(Buffer.isBuffer(a.image)).to.be(true); s.emit("big", a); }); }); }); }); it("should be able to emit after server close and restart", (done) => { const srv = createServer(); const sio = new Server(srv); sio.on("connection", (socket) => { socket.on("ev", (data) => { expect(data).to.be("payload"); done(); }); }); srv.listen(() => { const { port } = srv.address() as AddressInfo; const clientSocket = client(srv, { reconnectionAttempts: 10, reconnectionDelay: 100, }); clientSocket.once("connect", () => { srv.close(() => { clientSocket.io.on("reconnect", () => { clientSocket.emit("ev", "payload"); }); sio.listen(port); }); }); }); }); it("should enable compression by default", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, "/chat"); sio.of("/chat").on("connection", (s) => { s.conn.once("packetCreate", (packet) => { expect(packet.options.compress).to.be(true); done(); }); sio.of("/chat").emit("woot", "hi"); }); }); }); it("should disable compression", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, "/chat"); sio.of("/chat").on("connection", (s) => { s.conn.once("packetCreate", (packet) => { expect(packet.options.compress).to.be(false); done(); }); sio.of("/chat").compress(false).emit("woot", "hi"); }); }); }); it("should error with raw binary and warn", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { reconnection: false }); sio.on("connection", (s) => { s.conn.on("upgrade", () => { console.log( "\u001b[96mNote: warning expected and normal in test.\u001b[39m" ); // @ts-ignore socket.io.engine.write("5woooot"); setTimeout(() => { done(); }, 100); }); }); }); }); it("should not crash when receiving an error packet without handler", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { reconnection: false }); sio.on("connection", (s) => { s.conn.on("upgrade", () => { console.log( "\u001b[96mNote: warning expected and normal in test.\u001b[39m" ); // @ts-ignore socket.io.engine.write('44["handle me please"]'); setTimeout(() => { done(); }, 100); }); }); }); }); it("should not crash with raw binary", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { reconnection: false }); sio.on("connection", (s) => { s.once("error", (err) => { expect(err.message).to.match(/Illegal attachments/); done(); }); s.conn.on("upgrade", () => { // @ts-ignore socket.io.engine.write("5woooot"); }); }); }); }); it("should handle empty binary packet", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { reconnection: false }); sio.on("connection", (s) => { s.once("error", (err) => { expect(err.message).to.match(/Illegal attachments/); done(); }); s.conn.on("upgrade", () => { // @ts-ignore socket.io.engine.write("5"); }); }); }); }); it("should not crash when messing with Object prototype (and other globals)", (done) => { // @ts-ignore Object.prototype.foo = "bar"; // @ts-ignore global.File = ""; // @ts-ignore global.Blob = []; const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.disconnect(true); sio.close(); setTimeout(() => { done(); }, 100); }); }); }); it("should throw on reserved event", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { expect(() => s.emit("connect_error")).to.throwException( /"connect_error" is a reserved event name/ ); socket.close(); done(); }); }); }); it("should ignore a packet received after disconnection", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const clientSocket = client(srv); const success = () => { clientSocket.close(); sio.close(); done(); }; sio.on("connection", (socket) => { socket.on("test", () => { done(new Error("should not happen")); }); socket.on("disconnect", success); }); clientSocket.on("connect", () => { clientSocket.emit("test", Buffer.alloc(10)); clientSocket.disconnect(); }); }); }); describe("onAny", () => { it("should call listener", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { multiplex: false }); socket.emit("my-event", "123"); sio.on("connection", (socket: Socket) => { socket.onAny((event, arg1) => { expect(event).to.be("my-event"); expect(arg1).to.be("123"); done(); }); }); }); }); it("should prepend listener", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { multiplex: false }); socket.emit("my-event", "123"); sio.on("connection", (socket: Socket) => { let count = 0; socket.onAny((event, arg1) => { expect(count).to.be(2); done(); }); socket.prependAny(() => { expect(count++).to.be(1); }); socket.prependAny(() => { expect(count++).to.be(0); }); }); }); }); it("should remove listener", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { multiplex: false }); socket.emit("my-event", "123"); sio.on("connection", (socket: Socket) => { const fail = () => done(new Error("fail")); socket.onAny(fail); socket.offAny(fail); expect(socket.listenersAny.length).to.be(0); socket.onAny(() => { done(); }); }); }); }); }); }); describe("messaging many", () => { it("emits to a namespace", (done) => { const srv = createServer(); const sio = new Server(srv); let total = 2; srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); const socket3 = client(srv, "/test"); socket1.on("a", (a) => { expect(a).to.be("b"); --total || done(); }); socket2.on("a", (a) => { expect(a).to.be("b"); --total || done(); }); socket3.on("a", () => { done(new Error("not")); }); let sockets = 3; sio.on("connection", (socket) => { --sockets || emit(); }); sio.of("/test", (socket) => { --sockets || emit(); }); function emit() { sio.emit("a", "b"); } }); }); it("emits binary data to a namespace", (done) => { const srv = createServer(); const sio = new Server(srv); let total = 2; srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); const socket3 = client(srv, "/test"); socket1.on("bin", (a) => { expect(Buffer.isBuffer(a)).to.be(true); --total || done(); }); socket2.on("bin", (a) => { expect(Buffer.isBuffer(a)).to.be(true); --total || done(); }); socket3.on("bin", () => { done(new Error("not")); }); let sockets = 3; sio.on("connection", (socket) => { --sockets || emit(); }); sio.of("/test", (socket) => { --sockets || emit(); }); function emit() { sio.emit("bin", Buffer.alloc(10)); } }); }); it("emits to the rest", (done) => { const srv = createServer(); const sio = new Server(srv); const total = 2; srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); const socket3 = client(srv, "/test"); socket1.on("a", (a) => { expect(a).to.be("b"); socket1.emit("finish"); }); socket2.emit("broadcast"); socket2.on("a", () => { done(new Error("done")); }); socket3.on("a", () => { done(new Error("not")); }); const sockets = 2; sio.on("connection", (socket) => { socket.on("broadcast", () => { socket.broadcast.emit("a", "b"); }); socket.on("finish", () => { done(); }); }); }); }); it("emits to rooms", (done) => { const srv = createServer(); const sio = new Server(srv); const total = 2; srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); socket2.on("a", () => { done(new Error("not")); }); socket1.on("a", () => { done(); }); socket1.emit("join", "woot"); socket1.emit("emit", "woot"); sio.on("connection", (socket) => { socket.on("join", (room, fn) => { socket.join(room); fn && fn(); }); socket.on("emit", (room) => { sio.in(room).emit("a"); }); }); }); }); it("emits to rooms avoiding dupes", (done) => { const srv = createServer(); const sio = new Server(srv); let total = 2; srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); socket2.on("a", () => { done(new Error("not")); }); socket1.on("a", () => { --total || done(); }); socket2.on("b", () => { --total || done(); }); socket1.emit("join", "woot"); socket1.emit("join", "test"); socket2.emit("join", "third", () => { socket2.emit("emit"); }); sio.on("connection", (socket) => { socket.on("join", (room, fn) => { socket.join(room); fn && fn(); }); socket.on("emit", (room) => { sio.in("woot").in("test").emit("a"); sio.in("third").emit("b"); }); }); }); }); it("broadcasts to rooms", (done) => { const srv = createServer(); const sio = new Server(srv); let total = 2; srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); const socket3 = client(srv, { multiplex: false }); socket1.emit("join", "woot"); socket2.emit("join", "test"); socket3.emit("join", "test", () => { socket3.emit("broadcast"); }); socket1.on("a", () => { done(new Error("not")); }); socket2.on("a", () => { --total || done(); }); socket3.on("a", () => { done(new Error("not")); }); socket3.on("b", () => { --total || done(); }); sio.on("connection", (socket) => { socket.on("join", (room, fn) => { socket.join(room); fn && fn(); }); socket.on("broadcast", () => { socket.broadcast.to("test").emit("a"); socket.emit("b"); }); }); }); }); it("broadcasts binary data to rooms", (done) => { const srv = createServer(); const sio = new Server(srv); let total = 2; srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); const socket3 = client(srv, { multiplex: false }); socket1.emit("join", "woot"); socket2.emit("join", "test"); socket3.emit("join", "test", () => { socket3.emit("broadcast"); }); socket1.on("bin", (data) => { throw new Error("got bin in socket1"); }); socket2.on("bin", (data) => { expect(Buffer.isBuffer(data)).to.be(true); --total || done(); }); socket2.on("bin2", (data) => { throw new Error("socket2 got bin2"); }); socket3.on("bin", (data) => { throw new Error("socket3 got bin"); }); socket3.on("bin2", (data) => { expect(Buffer.isBuffer(data)).to.be(true); --total || done(); }); sio.on("connection", (socket) => { socket.on("join", (room, fn) => { socket.join(room); fn && fn(); }); socket.on("broadcast", () => { socket.broadcast.to("test").emit("bin", Buffer.alloc(5)); socket.emit("bin2", Buffer.alloc(5)); }); }); }); }); it("keeps track of rooms", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.join("a"); expect(s.rooms).to.contain(s.id, "a"); s.join("b"); expect(s.rooms).to.contain(s.id, "a", "b"); s.join("c"); expect(s.rooms).to.contain(s.id, "a", "b", "c"); s.leave("b"); expect(s.rooms).to.contain(s.id, "a", "c"); (s as any).leaveAll(); expect(s.rooms.size).to.eql(0); done(); }); }); }); it("deletes empty rooms", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.join("a"); expect(s.nsp.adapter.rooms).to.contain("a"); s.leave("a"); expect(s.nsp.adapter.rooms).to.not.contain("a"); done(); }); }); }); it("should properly cleanup left rooms", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.join("a"); expect(s.rooms).to.contain(s.id, "a"); s.join("b"); expect(s.rooms).to.contain(s.id, "a", "b"); s.leave("unknown"); expect(s.rooms).to.contain(s.id, "a", "b"); (s as any).leaveAll(); expect(s.rooms.size).to.eql(0); done(); }); }); }); it("allows to join several rooms at once", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv); sio.on("connection", (s) => { s.join(["a", "b", "c"]); expect(s.rooms).to.contain(s.id, "a", "b", "c"); done(); }); }); }); it("should exclude specific sockets when broadcasting", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); const socket3 = client(srv, { multiplex: false }); socket2.on("a", () => { done(new Error("not")); }); socket3.on("a", () => { done(new Error("not")); }); socket1.on("a", () => { done(); }); sio.on("connection", (socket) => { socket.on("exclude", (id) => { socket.broadcast.except(id).emit("a"); }); }); socket2.on("connect", () => { socket3.emit("exclude", socket2.id); }); }); }); it("should exclude a specific room when broadcasting", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket1 = client(srv, { multiplex: false }); const socket2 = client(srv, { multiplex: false }); const socket3 = client(srv, { multiplex: false }); socket2.on("a", () => { done(new Error("not")); }); socket3.on("a", () => { done(new Error("not")); }); socket1.on("a", () => { done(); }); sio.on("connection", (socket) => { socket.on("join", (room, cb) => { socket.join(room); cb(); }); socket.on("broadcast", () => { socket.broadcast.except("room1").emit("a"); }); }); socket2.emit("join", "room1", () => { socket3.emit("broadcast"); }); }); }); it("should return an immutable broadcast operator", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const clientSocket = client(srv, { multiplex: false }); sio.on("connection", (socket: Socket) => { const operator = socket.local .compress(false) .to(["room1", "room2"]) .except("room3"); operator.compress(true).emit("hello"); operator.volatile.emit("hello"); operator.to("room4").emit("hello"); operator.except("room5").emit("hello"); socket.emit("hello"); socket.to("room6").emit("hello"); // @ts-ignore expect(operator.rooms).to.contain("room1", "room2"); // @ts-ignore expect(operator.rooms).to.not.contain("room4", "room5", "room6"); // @ts-ignore expect(operator.exceptRooms).to.contain("room3"); // @ts-ignore expect(operator.flags).to.eql({ local: true, compress: false }); clientSocket.close(); sio.close(); done(); }); }); }); it("should pre encode a broadcast packet", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const clientSocket = client(srv, { multiplex: false }); sio.on("connection", (socket) => { socket.conn.on("packetCreate", (packet) => { expect(packet.data).to.eql('2["hello","world"]'); expect(packet.options.wsPreEncoded).to.eql('42["hello","world"]'); clientSocket.close(); sio.close(); done(); }); sio.emit("hello", "world"); }); }); }); }); describe("middleware", () => { it("should call functions", (done) => { const srv = createServer(); const sio = new Server(srv); let run = 0; sio.use((socket, next) => { expect(socket).to.be.a(Socket); run++; next(); }); sio.use((socket, next) => { expect(socket).to.be.a(Socket); run++; next(); }); srv.listen(() => { const socket = client(srv); socket.on("connect", () => { expect(run).to.be(2); done(); }); }); }); it("should pass errors", (done) => { const srv = createServer(); const sio = new Server(srv); const run = 0; sio.use((socket, next) => { next(new Error("Authentication error")); }); sio.use((socket, next) => { done(new Error("nope")); }); srv.listen(() => { const socket = client(srv); socket.on("connect", () => { done(new Error("nope")); }); socket.on("connect_error", (err) => { expect(err.message).to.be("Authentication error"); done(); }); }); }); it("should pass an object", (done) => { const srv = createServer(); const sio = new Server(srv); sio.use((socket, next) => { const err = new Error("Authentication error"); // @ts-ignore err.data = { a: "b", c: 3 }; next(err); }); srv.listen(() => { const socket = client(srv); socket.on("connect", () => { done(new Error("nope")); }); socket.on("connect_error", (err) => { expect(err).to.be.an(Error); expect(err.message).to.eql("Authentication error"); // @ts-ignore expect(err.data).to.eql({ a: "b", c: 3 }); done(); }); }); }); it("should only call connection after fns", (done) => { const srv = createServer(); const sio = new Server(srv); sio.use((socket: any, next) => { socket.name = "guillermo"; next(); }); srv.listen(() => { const socket = client(srv); sio.on("connection", (socket) => { expect((socket as any).name).to.be("guillermo"); done(); }); }); }); it("should only call connection after (lengthy) fns", (done) => { const srv = createServer(); const sio = new Server(srv); let authenticated = false; sio.use((socket, next) => { setTimeout(() => { authenticated = true; next(); }, 300); }); srv.listen(() => { const socket = client(srv); socket.on("connect", () => { expect(authenticated).to.be(true); done(); }); }); }); it("should be ignored if socket gets closed", (done) => { const srv = createServer(); const sio = new Server(srv); let socket; sio.use((s, next) => { socket.io.engine.close(); s.client.conn.on("close", () => { process.nextTick(next); setTimeout(() => { done(); }, 50); }); }); srv.listen(() => { socket = client(srv); sio.on("connection", (socket) => { done(new Error("should not fire")); }); }); }); it("should call functions in expected order", (done) => { const srv = createServer(); const sio = new Server(srv); const result: number[] = []; sio.use(() => { done(new Error("should not fire")); }); sio.of("/chat").use((socket, next) => { result.push(1); setTimeout(next, 50); }); sio.of("/chat").use((socket, next) => { result.push(2); setTimeout(next, 50); }); sio.of("/chat").use((socket, next) => { result.push(3); setTimeout(next, 50); }); srv.listen(() => { const chat = client(srv, "/chat"); chat.on("connect", () => { expect(result).to.eql([1, 2, 3]); done(); }); }); }); it("should disable the merge of handshake packets", (done) => { const srv = createServer(); const sio = new Server(); sio.use((socket, next) => { next(); }); sio.listen(srv); const socket = client(srv); socket.on("connect", () => { done(); }); }); it("should work with a custom namespace", (done) => { const srv = createServer(); const sio = new Server(); sio.listen(srv); sio.of("/chat").use((socket, next) => { next(); }); let count = 0; client(srv, "/").on("connect", () => { if (++count === 2) done(); }); client(srv, "/chat").on("connect", () => { if (++count === 2) done(); }); }); }); describe("socket middleware", () => { it("should call functions", (done) => { const srv = createServer(); const sio = new Server(srv); let run = 0; srv.listen(() => { const socket = client(srv, { multiplex: false }); socket.emit("join", "woot"); sio.on("connection", (socket) => { socket.use((event, next) => { expect(event).to.eql(["join", "woot"]); event.unshift("wrap"); run++; next(); }); socket.use((event, next) => { expect(event).to.eql(["wrap", "join", "woot"]); run++; next(); }); socket.on("wrap", (data1, data2) => { expect(data1).to.be("join"); expect(data2).to.be("woot"); expect(run).to.be(2); done(); }); }); }); }); it("should pass errors", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const socket = client(srv, { multiplex: false }); socket.emit("join", "woot"); const success = () => { socket.close(); sio.close(); done(); }; sio.on("connection", (socket) => { socket.use((event, next) => { next(new Error("Authentication error")); }); socket.use((event, next) => { done(new Error("should not happen")); }); socket.on("join", () => { done(new Error("should not happen")); }); socket.on("error", (err) => { expect(err).to.be.an(Error); expect(err.message).to.eql("Authentication error"); success(); }); }); }); }); }); describe("v2 compatibility", () => { it("should connect if `allowEIO3` is true", (done) => { const srv = createServer(); const sio = new Server(srv, { allowEIO3: true, }); srv.listen(async () => { const port = (srv.address() as AddressInfo).port; const clientSocket = io_v2.connect(`http://localhost:${port}`, { multiplex: false, }); const [socket]: Array<any> = await Promise.all([ waitFor(sio, "connection"), waitFor(clientSocket, "connect"), ]); expect(socket.id).to.eql(clientSocket.id); success(sio, clientSocket, done); }); }); it("should be able to connect to a namespace with a query", (done) => { const srv = createServer(); const sio = new Server(srv, { allowEIO3: true, }); srv.listen(async () => { const port = (srv.address() as AddressInfo).port; const clientSocket = io_v2.connect( `http://localhost:${port}/the-namespace`, { multiplex: false, } ); clientSocket.query = { test: "123" }; const [socket]: Array<any> = await Promise.all([ waitFor(sio.of("/the-namespace"), "connection"), waitFor(clientSocket, "connect"), ]); expect(socket.handshake.auth).to.eql({ test: "123" }); success(sio, clientSocket, done); }); }); it("should not connect if `allowEIO3` is false (default)", (done) => { const srv = createServer(); const sio = new Server(srv); srv.listen(() => { const port = (srv.address() as AddressInfo).port; const clientSocket = io_v2.connect(`http://localhost:${port}`, { multiplex: false, }); clientSocket.on("connect", () => { done(new Error("should not happen")); }); clientSocket.on("connect_error", () => { success(sio, clientSocket, done); }); }); }); }); });
the_stack
import {API} from '../../src/schema/api'; import * as protos from '../../../protos'; import * as assert from 'assert'; import {afterEach, describe, it} from 'mocha'; import * as sinon from 'sinon'; import * as proto from '../../src/schema/proto'; describe('src/schema/api.ts', () => { it('should construct an API object and return list of protos', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/test/v1/test.proto'; fd.package = 'google.cloud.test.v1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'ZService'; fd.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const api = new API([fd], 'google.cloud.test.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(api.filesToGenerate, [ 'google/cloud/test/v1/test.proto', ]); }); it('throw error if an api does not have default host', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/test/v1/test.proto'; fd.package = 'google.cloud.test.v1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'ZService'; assert.throws(() => { new API([fd], 'google.cloud.test.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); }, /service "google.cloud.test.v1.ZService" is missing option google.api.default_host/); }); it('should not return common protos in the list of protos', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'google/cloud/test/v1/test.proto'; fd1.package = 'google.cloud.test.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'ZService'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const fd2 = new protos.google.protobuf.FileDescriptorProto(); fd2.name = 'google/longrunning/operation.proto'; fd2.package = 'google.longrunning'; fd2.service = [new protos.google.protobuf.ServiceDescriptorProto()]; const fd3 = new protos.google.protobuf.FileDescriptorProto(); fd3.name = 'google/iam/v1/iam_policy.proto'; fd3.package = 'google.iam.v1'; fd3.service = [new protos.google.protobuf.ServiceDescriptorProto()]; const api = new API([fd1, fd2, fd3], 'google.cloud.test.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(api.filesToGenerate, [ 'google/cloud/test/v1/test.proto', ]); }); it('should be able to generate google.iam.v1 alone', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/iam/v1/iam_policy.proto'; fd.package = 'google.iam.v1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'IAMPolicy'; fd.service[0].options = { '.google.api.defaultHost': 'iam.googleapis.com', }; const api = new API([fd], 'google.iam.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(api.filesToGenerate, [ 'google/iam/v1/iam_policy.proto', ]); }); it('should not return common protos in the proto list', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'google/cloud/test/v1/test.proto'; fd1.package = 'google.cloud.test.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'ZService'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const fd2 = new protos.google.protobuf.FileDescriptorProto(); fd2.name = 'google/api/annotations.proto'; fd2.package = 'google.api'; const fd3 = new protos.google.protobuf.FileDescriptorProto(); fd3.name = 'google/orgpolicy/v1/orgpolicy.proto'; fd3.package = 'google.orgpolicy.v1'; const fd4 = new protos.google.protobuf.FileDescriptorProto(); fd4.name = 'google/cloud/common_resources.proto'; fd4.package = 'google.cloud'; const fd5 = new protos.google.protobuf.FileDescriptorProto(); fd5.name = 'google/api/servicemanagement/v1/servicemanager.proto'; fd5.package = 'google.api.servicemanager.v1'; const api = new API([fd1, fd2, fd3, fd4, fd5], 'google', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(api.filesToGenerate, [ 'google/cloud/test/v1/test.proto', 'google/orgpolicy/v1/orgpolicy.proto', 'google/api/servicemanagement/v1/servicemanager.proto', ]); }); it('should include the protos has no service and different package name', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'google/cloud/example/v1/test.proto'; fd1.package = 'google.cloud.example.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'Service'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const fd2 = new protos.google.protobuf.FileDescriptorProto(); fd2.name = 'google/cloud/example/v1/error.proto'; fd2.package = 'google.cloud.example.v1.errors'; const api = new API([fd1, fd2], 'google.cloud.example.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(JSON.parse(api.protoFilesToGenerateJSON), [ '../../protos/google/cloud/example/v1/error.proto', '../../protos/google/cloud/example/v1/test.proto', ]); }); it('should return lexicographically first service name as mainServiceName', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'google/cloud/test/v1/test.proto'; fd1.package = 'google.cloud.test.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'ZService'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const fd2 = new protos.google.protobuf.FileDescriptorProto(); fd2.name = 'google/cloud/example/v1/example.proto'; fd2.package = 'google.cloud.example.v1'; fd2.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd2.service[0].name = 'AService'; fd2.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const api = new API([fd1, fd2], 'google.cloud.test.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(api.mainServiceName, 'AService'); }); it('should return correct mainServiceName for API without namespace', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'service/v1/test.proto'; fd1.package = 'service.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'Service'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const api = new API([fd1], 'service.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(api.mainServiceName, 'Service'); }); it('should return main service name specificed as an option', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'google/cloud/test/v1/test.proto'; fd1.package = 'google.cloud.test.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'ZService'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const fd2 = new protos.google.protobuf.FileDescriptorProto(); fd2.name = 'google/cloud/example/v1/example.proto'; fd2.package = 'google.cloud.example.v1'; fd2.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd2.service[0].name = 'AService'; fd2.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const api = new API([fd1, fd2], 'google.cloud.test.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), mainServiceName: 'OverriddenName', }); assert.deepStrictEqual(api.mainServiceName, 'OverriddenName'); }); it('should return list of protos in lexicographical order', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'google/cloud/example/v1/test.proto'; fd1.package = 'google.cloud.example.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'Service'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; const fd2 = new protos.google.protobuf.FileDescriptorProto(); fd2.name = 'google/cloud/example/v1/example.proto'; fd2.package = 'google.cloud.example.v1'; fd2.service = []; const api = new API([fd1, fd2], 'google.cloud.example.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert.deepStrictEqual(JSON.parse(api.protoFilesToGenerateJSON), [ '../../protos/google/cloud/example/v1/example.proto', '../../protos/google/cloud/example/v1/test.proto', ]); }); it('should throw error when the service name is not found', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/test/v1/test.proto'; fd.package = 'google.cloud.test.v1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; assert.throws(() => { const api = new API([fd], 'google.cloud.test.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert(api); }); }); describe('Calling Proto constructor', () => { afterEach(() => { sinon.restore(); }); it('should pass all messages to Proto constructor', () => { const fd1 = new protos.google.protobuf.FileDescriptorProto(); fd1.name = 'google/cloud/example/v1/test.proto'; fd1.package = 'google.cloud.example.v1'; fd1.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd1.service[0].name = 'Service'; fd1.service[0].options = { '.google.api.defaultHost': 'hostname.example.com:443', }; fd1.messageType = [new protos.google.protobuf.MethodDescriptorProto()]; fd1.messageType[0].name = 'MessageA'; const fd2 = new protos.google.protobuf.FileDescriptorProto(); fd2.name = 'google/cloud/example/v1/example.proto'; fd2.package = 'google.cloud.example.v1'; fd2.messageType = [new protos.google.protobuf.MethodDescriptorProto()]; fd2.messageType[0].name = 'MessageB'; const spy = sinon.spy(proto, 'Proto'); new API([fd1, fd2], 'google.cloud.example.v1', { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }); assert(spy.calledWithNew()); assert.strictEqual(spy.callCount, 2); // one Proto object created for each fd const firstCallMessages = spy.getCall(0).args[0].allMessages; const secondCallMessages = spy.getCall(1).args[0].allMessages; assert('.google.cloud.example.v1.MessageA' in firstCallMessages); assert('.google.cloud.example.v1.MessageB' in firstCallMessages); assert('.google.cloud.example.v1.MessageA' in secondCallMessages); assert('.google.cloud.example.v1.MessageB' in secondCallMessages); }); }); });
the_stack
import { Browser, EventHandler, createElement, EmitType } from '@syncfusion/ej2-base'; import { ILoadedEventArgs, ILoadEventArgs, IAnimationCompleteEventArgs } from '../../src/linear-gauge/model/interface'; import { LinearGauge } from '../../src/linear-gauge/linear-gauge'; import { MouseEvents } from '../base/events.spec'; import { GaugeTooltip } from '../../src/linear-gauge/user-interaction/tooltip'; import {profile , inMB, getMemoryProfile} from '../common.spec'; LinearGauge.Inject(GaugeTooltip); describe('Linear gauge control', () => { beforeAll(() => { 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; } }); describe('Checking user interaction - marker drag', () => { let gauge: LinearGauge; let element: HTMLElement; let svg: HTMLElement; let timeout: number; let trigger: MouseEvents = new MouseEvents(); beforeAll((): void => { element = createElement('div', { id: 'container' }); document.body.appendChild(element); gauge = new LinearGauge(); gauge.appendTo('#container'); }); afterAll((): void => { element.remove(); gauge.destroy(); }); it('checking drag and drop - marker drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); trigger.dragAndDropEvent(svg, 668.5, 223, (223 + 10), (668.5 + 10), '', gauge); done(); }; gauge.axes[0].pointers[0].value = 50; gauge.axes[0].pointers[0].enableDrag = true; gauge.refresh(); }); it('checking drag and drop - marker drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.refresh(); }); // it('checking drag and drop - horizontal', (done: Function): void => { // gauge.loaded = (args: ILoadedEventArgs): void => { // debugger; // let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); // trigger.dragAndDropEvent(svg, 630, 255, (630 + 10), (255 + 10), 'touchstart', gauge); // done(); // }; // gauge.orientation = 'Horizontal'; // gauge.refresh(); // }); it('checking drag and drop - horizontal - axis inversed', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); trigger.dragAndDropEvent(svg, 630, 255, (630 + 10), (255 + 10), '', gauge); done(); }; gauge.axes[0].isInversed = true; gauge.refresh(); }); it('checking drag and drop - vertical - axis inversed', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); trigger.dragAndDropEvent(svg, 688.5, 223, (668.5 + 10), (223 + 10), '', gauge); done(); }; gauge.orientation = 'Vertical'; gauge.refresh(); }); it('checking drag and drop - Cursor-style', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('cursor'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('cursor')).toBe(true); done(); }; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking drag and drop - Cursor-style-over the pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('cursor'); trigger.mouseoverEvent(svg); expect(x == svg.getAttribute('cursor')).toBe(true); done(); }; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking drag and drop - circle-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('cy'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('cy')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking drag and drop - circle-pointer - axis-inversed', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('cy'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('cy')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].isInversed = false; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking drag and drop - circle-pointer - horizontal', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('cx'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 600.5, 63.75, '', gauge); expect(x != svg.getAttribute('cx')).toBe(true); done(); }; gauge.orientation = 'Horizontal'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Circle'; gauge.refresh(); }); it('checking drag and drop - Arrow-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('d'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('d')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].isInversed = true; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Arrow'; gauge.refresh(); }); it('checking drag and drop - Diamond-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('d'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('d')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Diamond'; gauge.refresh(); }); it('checking drag and drop - Image-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('y'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('y')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Image'; gauge.refresh(); }); it('checking drag and drop - Image-pointer - multiple element', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: number = svg.childElementCount; trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); trigger.dragAndDropEvent(svg, 511.5, 82, 511.5, 200, '', gauge); expect(x == svg.childElementCount).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Image'; gauge.refresh(); }); it('checking drag and drop - InvertedArrow-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('d'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('d')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'InvertedArrow'; gauge.refresh(); }); it('checking drag and drop - InvertedTriangle-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('d'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('d')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'InvertedTriangle'; gauge.refresh(); }); it('checking drag and drop - Rectangle-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('d'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('d')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Rectangle'; gauge.refresh(); }); it('checking drag and drop - Triangle-pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; let x: string = svg.getAttribute('d'); trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); expect(x != svg.getAttribute('d')).toBe(true); done(); }; gauge.orientation = 'Vertical'; gauge.axes[0].pointers[0].value = 0; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].type = 'Marker'; gauge.axes[0].pointers[0].markerType = 'Triangle'; gauge.refresh(); }); it('checking drag and drop - multiple pointer Triangle marker and circle marker', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); done(); }; gauge.axes = [{ pointers: [{ value: 0, type: 'Marker', markerType: 'Triangle', enableDrag: false }] }, { pointers: [{ enableDrag: true }] }] gauge.refresh(); }); it('checking drag and drop - multiple pointer Triangle marker and Triangle marker', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); done(); }; gauge.axes = [{ pointers: [{ value: 0, type: 'Marker', markerType: 'Triangle', enableDrag: false }] }, { pointers: [{ markerType: 'Triangle', enableDrag: true }] }] gauge.refresh(); }); it('checking drag and drop - multiple pointer marker and bar', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; trigger.dragAndDropEvent(svg, 511.5, 63.75, 511.5, 100, '', gauge); done(); }; gauge.axes = [{ pointers: [{ value: 0, type: 'Marker', markerType: 'Triangle', enableDrag: false }] }, { pointers: [{ type: 'Bar', enableDrag: true }] }] gauge.refresh(); }); // it('checking drag and drop - touch move - axis inversed', (done: Function): void => { // gauge.loaded = (args: ILoadedEventArgs): void => { // debugger; // let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); // trigger.dragAndDropEvent(svg, (630 + 20), 255, (630 + 20 + 10), 255, 'touchmove', gauge); // done(); // }; // gauge.axes[0].isInversed = false; // gauge.orientation = 'Horizontal'; // gauge.refresh(); // }); // it('checking drag and drop - touch move - pointer image', (done: Function): void => { // gauge.loaded = (args: ILoadedEventArgs): void => { // debugger; // svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; // let x: string = svg.getAttribute('x'); // trigger.dragAndDropEvent(svg, 200, 255, 300, 255, 'touchmove', gauge); // svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; // expect(x != svg.getAttribute('x')).toBe(true); // done(); // }; // gauge.axes[0].pointers[0].type = 'Marker'; // gauge.axes[0].pointers[0].markerType = 'Image'; // gauge.axes[0].pointers[0].imageUrl = '../img/img1.jpg' // gauge.axes[0].pointers[0].animationDuration = 0; // gauge.refresh(); // }); // it('checking pointer image position', (): void => { // gauge.loaded = null; // svg = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; // let x: string = svg.getAttribute('x'); // expect(x).toBe('282'); // }); }); describe('Checking user interaction - bar drag', () => { let gauge: LinearGauge; let element: HTMLElement; let svg: HTMLElement; let timeout: number; let trigger: MouseEvents = new MouseEvents(); beforeAll((): void => { element = createElement('div', { id: 'container' }); document.body.appendChild(element); gauge = new LinearGauge(); gauge.appendTo('#container'); }); afterAll((): void => { element.remove(); }); it('checking drag and drop - bar drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); trigger.dragAndDropEvent(<Element>svg.childNodes[0], 677.5, 233, 677.5, (233 + 5), '', gauge); done(); }; gauge.axes[0].pointers[0].type = 'Bar'; gauge.axes[0].pointers[0].value = 50; gauge.axes[0].pointers[0].enableDrag = true; gauge.refresh(); }); it('checking with touch move event - bar drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.refresh(); }); it('checking drag and drop - RoundedRectangle drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { debugger; let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); trigger.dragAndDropEvent(<Element>svg.childNodes[0], 677.5, 233, (677.5), (233 + 5), '', gauge); done(); }; gauge.container.type = 'RoundedRectangle'; gauge.refresh(); }); it('checking drag and drop - Thermometer drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.container.type = 'Thermometer'; gauge.refresh(); }); it('checking drag and drop - Rounded rectangle drag - axis inversed', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); trigger.dragAndDropEvent(<Element>svg.childNodes[0], 677.5, (71.5 + 161.25), (677.5), ((71.5 + 161.25) - 5), '', gauge); done(); }; gauge.container.type = 'RoundedRectangle'; gauge.axes[0].isInversed = true; gauge.refresh(); }); it('checking drag and drop - Normal container drag - axis inversed', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); trigger.dragAndDropEvent(<Element>svg.childNodes[0], 677.5, (71.75 + 161.25), (677.5), ((71.75 + 161.25) - 5), '', gauge); done(); }; gauge.container.type = 'Normal'; gauge.refresh(); }); it('checking drag and drop - bar drag in horizontal orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); // done(); }; gauge.axes[0].isInversed = false; gauge.orientation = 'Horizontal'; gauge.refresh(); }); it('checking drag and drop - Rounded rectangle bar drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.container.type = 'RoundedRectangle'; gauge.refresh(); }); it('checking drag and drop - Thermometer bar drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.container.type = 'Thermometer'; gauge.refresh(); }); it('checking drag and drop - bar drag - inversed axis', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.axes[0].isInversed = true; gauge.container.type = 'Normal'; gauge.refresh(); }); it('checking drag and drop - Rounded Rectangle bar drag - inversed axis', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.container.type = 'RoundedRectangle'; gauge.refresh(); }); it('checking with mouse leave from element', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { trigger.mouseLeaveEvent(args.gauge.element); done(); }; gauge.tooltip.enable = true; gauge.mouseElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); gauge.refresh(); }); it('checking with mouse move while pointer dragged', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { gauge.pointerDrag = true; trigger.mousemoveEvent(args.gauge.element, 0, 0, 10, 10); done(); }; gauge.mouseElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); gauge.refresh(); }); it('checking drag and drop - image drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { debugger; let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); trigger.dragAndDropEvent(<Element>svg.childNodes[0], 677.5, 233, 677.5, (233 + 5), '', gauge); done(); }; gauge.axes[0].pointers[0].value = 50; debugger; gauge.axes[0].pointers[0].type = "Marker"; gauge.axes[0].pointers[0].enableDrag = true; gauge.axes[0].pointers[0].markerType ="Image"; gauge.axes[0].pointers[0].imageUrl ="hello.png"; gauge.refresh(); }); it('checking drag and drop - bar Horizontal drag', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_BarPointer_0'); let bounds: ClientRect = svg.getBoundingClientRect(); trigger.dragAndDropEvent(svg,bounds.left, bounds.top, (bounds.left), (bounds.top), '', gauge); done(); }; gauge.axes[0].pointers[0].type = 'Bar'; gauge.orientation ="Horizontal"; gauge.axes[0].pointers[0].value = 50; gauge.axes[0].pointers[0].enableDrag = true; gauge.refresh(); }); it('checking drag and drop - multiple pointer bar and marker', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_BarPointer_0').children[0]; trigger.mousedownEvent(svg, 501.5, 245, 501.5, 245); trigger.dragAndDropEvent(svg, 501.5, 245, 450, 245, '', gauge); done(); }; gauge.axes = [{ pointers: [{ value: 50, type: 'Bar', enableDrag: false }] }, { pointers: [{ enableDrag: true }] }]; gauge.refresh(); }); it('checking drag and drop - multiple pointer bar and bar', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_BarPointer_0').children[0]; trigger.mousedownEvent(svg, 501.5, 245, 501.5, 245); trigger.dragAndDropEvent(svg, 501.5, 245, 450, 245, '', gauge); done(); }; gauge.axes = [{ pointers: [{ value: 50, type: 'Bar', enableDrag: false }] }, { pointers: [{ type: 'Bar', enableDrag: true }] }]; gauge.refresh(); }); it('checking drag and drop - In a middle of Horizontal Bar pointer', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = <HTMLElement>document.getElementById('container_AxisIndex_0_BarPointer_0').children[0]; let path = svg.getAttribute('d'); trigger.mousedownEvent(svg, 501.5, 245, 501.5, 245); trigger.dragAndDropEvent(svg, 501.5, 245, 450, 245, '', gauge); expect(path == svg.getAttribute('d')).toBe(true); done(); }; gauge.axes = [{ pointers: [{ value: 50, type: 'Bar', enableDrag: false }] }]; gauge.refresh(); }); it('checking drag and drop - Bar pointer with align attribute', (done: Function): void => { gauge.loaded = (args: ILoadedEventArgs): void => { document.getElementById('container').setAttribute('align','center'); svg = <HTMLElement>document.getElementById('container_AxisIndex_0_BarPointer_0').children[0]; let path = svg.getAttribute('d'); trigger.mousedownEvent(svg, 112.5, 255, 112.5, 255); trigger.dragAndDropEvent(svg, 112.5, 255, 200, 255, '', gauge); expect(path == svg.getAttribute('d')).toBe(true); done(); document.getElementById('container').removeAttribute('align'); }; gauge.orientation = 'Horizontal', gauge.axes = [{ pointers: [{ value: 50, type: 'Bar', enableDrag: true }] }]; gauge.refresh(); }); }); 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); }); });
the_stack
import { BadRequestException, ConflictException, Injectable, NotFoundException, UnauthorizedException, UnprocessableEntityException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { Prisma } from '@prisma/client'; import { Email, MfaMethod, User } from '@prisma/client'; import { compare, hash } from 'bcrypt'; import { createHash } from 'crypto'; import got from 'got/dist/source'; import anonymize from 'ip-anonymize'; import { authenticator } from 'otplib'; import { createRandomBytes, createDigest } from '@otplib/plugin-crypto'; import { keyEncoder, keyDecoder } from '@otplib/plugin-thirty-two'; import qrcode from 'qrcode'; import randomColor from 'randomcolor'; import UAParser from 'ua-parser-js'; import { COMPROMISED_PASSWORD, EMAIL_USER_CONFLICT, EMAIL_VERIFIED_CONFLICT, INVALID_CREDENTIALS, INVALID_MFA_CODE, MFA_BACKUP_CODE_USED, MFA_ENABLED_CONFLICT, MFA_NOT_ENABLED, MFA_PHONE_NOT_FOUND, NO_EMAILS, NO_TOKEN_PROVIDED, SESSION_NOT_FOUND, UNVERIFIED_EMAIL, UNVERIFIED_LOCATION, USER_NOT_FOUND, } from '../../errors/errors.constants'; import { safeEmail } from '../../helpers/safe-email'; import { GeolocationService } from '../../providers/geolocation/geolocation.service'; import { MailService } from '../../providers/mail/mail.service'; import { Expose } from '../../providers/prisma/prisma.interface'; import { PrismaService } from '../../providers/prisma/prisma.service'; import { PwnedService } from '../../providers/pwned/pwned.service'; import { APPROVE_SUBNET_TOKEN, EMAIL_MFA_TOKEN, EMAIL_VERIFY_TOKEN, LOGIN_ACCESS_TOKEN, MERGE_ACCOUNTS_TOKEN, MULTI_FACTOR_TOKEN, PASSWORD_RESET_TOKEN, } from '../../providers/tokens/tokens.constants'; import { TokensService } from '../../providers/tokens/tokens.service'; import { TwilioService } from '../../providers/twilio/twilio.service'; import { ApprovedSubnetsService } from '../approved-subnets/approved-subnets.service'; import { RegisterDto } from './auth.dto'; import { AccessTokenClaims, MfaTokenPayload, TokenResponse, TotpTokenResponse, } from './auth.interface'; import { groupAdminScopes, groupMemberScopes, groupOwnerScopes, userScopes, } from '../../helpers/scopes'; import axios from 'axios'; @Injectable() export class AuthService { authenticator: typeof authenticator; constructor( private prisma: PrismaService, private email: MailService, private configService: ConfigService, private pwnedService: PwnedService, private tokensService: TokensService, private geolocationService: GeolocationService, private approvedSubnetsService: ApprovedSubnetsService, private twilioService: TwilioService, ) { this.authenticator = authenticator.create({ window: [ this.configService.get<number>('security.totpWindowPast') ?? 0, this.configService.get<number>('security.totpWindowFuture') ?? 0, ], keyEncoder, keyDecoder, createDigest, createRandomBytes, }); } async login( ipAddress: string, userAgent: string, email: string, password?: string, code?: string, origin?: string, ): Promise<TokenResponse | TotpTokenResponse> { const emailSafe = safeEmail(email); const user = await this.prisma.user.findFirst({ where: { emails: { some: { emailSafe } } }, include: { emails: true, prefersEmail: true, }, }); if (!user) throw new NotFoundException(USER_NOT_FOUND); if (!user.active) await this.prisma.user.update({ where: { id: user.id }, data: { active: true }, }); if (!user.emails.find((i) => i.emailSafe === emailSafe)?.isVerified) throw new UnauthorizedException(UNVERIFIED_EMAIL); if (!password || !user.password) return this.mfaResponse(user, 'EMAIL'); if (!user.prefersEmail) throw new BadRequestException(NO_EMAILS); if (!(await compare(password, user.password))) throw new UnauthorizedException(INVALID_CREDENTIALS); if (code) return this.loginUserWithTotpCode( ipAddress, userAgent, user.id, code, origin, ); if (user.twoFactorMethod !== 'NONE') return this.mfaResponse(user); await this.checkLoginSubnet( ipAddress, userAgent, user.checkLocationOnLogin, user.id, origin, ); return this.loginResponse(ipAddress, userAgent, user); } async register(ipAddress: string, _data: RegisterDto): Promise<Expose<User>> { const { email, origin, ...data } = _data; const emailSafe = safeEmail(email); const testUser = await this.prisma.user.findFirst({ where: { emails: { some: { emailSafe } } }, }); if (testUser) throw new ConflictException(EMAIL_USER_CONFLICT); const ignorePwnedPassword = !!data.ignorePwnedPassword; delete data.ignorePwnedPassword; if (data.name) data.name = data.name .split(' ') .map((word, index) => index === 0 || index === data.name.split(' ').length ? (word.charAt(0) ?? '').toUpperCase() + (word.slice(1) ?? '').toLowerCase() : word, ) .join(' '); if (data.password) data.password = await this.hashAndValidatePassword( data.password, ignorePwnedPassword, ); let initials = data.name.trim().substr(0, 2).toUpperCase(); if (data.name.includes(' ')) initials = data.name .split(' ') .map((i) => i.trim().substr(0, 1)) .join('') .toUpperCase(); data.profilePictureUrl = data.profilePictureUrl ?? `https://ui-avatars.com/api/?name=${initials}&background=${randomColor({ luminosity: 'light', }).replace('#', '')}&color=000000`; if (!data.gender) { try { const prediction = await axios.get<{ name: string; gender: 'male' | 'female'; probability: number; count: number; }>(`https://api.genderize.io/?name=${data.name.split(' ')[0]}`); if ( prediction.data.probability > 0.5 && prediction.data.gender === 'male' ) data.gender = 'MALE'; if ( prediction.data.probability > 0.5 && prediction.data.gender === 'female' ) data.gender = 'FEMALE'; } catch (error) {} } if (this.configService.get<boolean>('gravatar.enabled')) { for await (const emailString of [email, emailSafe]) { const md5Email = createHash('md5').update(emailString).digest('hex'); try { const img = await got( `https://www.gravatar.com/avatar/${md5Email}?d=404`, { responseType: 'buffer' }, ); if (img.body.byteLength > 1) data.profilePictureUrl = `https://www.gravatar.com/avatar/${md5Email}?d=mp`; } catch (error) {} } } let id: number | undefined = undefined; while (!id) { id = Number( `10${await this.tokensService.generateRandomString(6, 'numeric')}`, ); const users = await this.prisma.user.findMany({ where: { id }, take: 1 }); if (users.length) id = undefined; } const user = await this.prisma.user.create({ data: { ...data, id, emails: { create: { email: email, emailSafe }, }, }, include: { emails: { select: { id: true } } }, }); if (user.emails[0]?.id) await this.prisma.user.update({ where: { id: user.id }, data: { prefersEmail: { connect: { id: user.emails[0].id } } }, }); // In testing, we auto-approve the email if (process.env.TEST) { const emailId = user.emails[0]?.id; if (emailId) await this.prisma.email.update({ where: { id: emailId }, data: { isVerified: true }, }); } else await this.sendEmailVerification(email, false, origin); await this.approvedSubnetsService.approveNewSubnet(user.id, ipAddress); return this.prisma.expose(user); } async sendEmailVerification(email: string, resend = false, origin?: string) { const emailSafe = safeEmail(email); const emailDetails = await this.prisma.email.findFirst({ where: { emailSafe }, include: { user: true }, }); if (!emailDetails) throw new NotFoundException(USER_NOT_FOUND); if (emailDetails.isVerified) throw new ConflictException(EMAIL_VERIFIED_CONFLICT); this.email.send({ to: `"${emailDetails.user.name}" <${email}>`, template: resend ? 'auth/resend-email-verification' : 'auth/email-verification', data: { name: emailDetails.user.name, days: 7, link: `${ origin ?? this.configService.get<string>('frontendUrl') }/auth/link/verify-email?token=${this.tokensService.signJwt( EMAIL_VERIFY_TOKEN, { id: emailDetails.id }, '7d', )}`, }, }); return { queued: true }; } async refresh( ipAddress: string, userAgent: string, token: string, ): Promise<TokenResponse> { if (!token) throw new UnprocessableEntityException(NO_TOKEN_PROVIDED); const session = await this.prisma.session.findFirst({ where: { token }, include: { user: true }, }); if (!session) throw new NotFoundException(SESSION_NOT_FOUND); await this.prisma.session.updateMany({ where: { token }, data: { ipAddress, userAgent }, }); return { accessToken: await this.getAccessToken(session.user, session.id), refreshToken: token, }; } async logout(token: string): Promise<void> { if (!token) throw new UnprocessableEntityException(NO_TOKEN_PROVIDED); const session = await this.prisma.session.findFirst({ where: { token }, select: { id: true, user: { select: { id: true } } }, }); if (!session) throw new NotFoundException(SESSION_NOT_FOUND); await this.prisma.session.delete({ where: { id: session.id }, }); } async approveSubnet( ipAddress: string, userAgent: string, token: string, ): Promise<TokenResponse> { if (!token) throw new UnprocessableEntityException(NO_TOKEN_PROVIDED); const { id } = this.tokensService.verify<{ id: number }>( APPROVE_SUBNET_TOKEN, token, ); const user = await this.prisma.user.findUnique({ where: { id } }); if (!user) throw new NotFoundException(USER_NOT_FOUND); await this.approvedSubnetsService.approveNewSubnet(id, ipAddress); return this.loginResponse(ipAddress, userAgent, user); } /** * Get the two-factor authentication QR code * @returns Data URI string with QR code image */ async getTotpQrCode(userId: number): Promise<string> { const secret = this.authenticator.generateSecret(); await this.prisma.user.update({ where: { id: userId }, data: { twoFactorSecret: secret }, }); const otpauth = this.authenticator.keyuri( userId.toString(), this.configService.get<string>('meta.appName') ?? '', secret, ); return qrcode.toDataURL(otpauth); } /** Enable two-factor authentication */ async enableMfaMethod( method: MfaMethod, userId: number, code: string, ): Promise<Expose<User>> { const user = await this.prisma.user.findUnique({ where: { id: userId }, select: { twoFactorSecret: true, twoFactorMethod: true }, }); if (!user) throw new NotFoundException(USER_NOT_FOUND); if (user.twoFactorMethod !== 'NONE') throw new ConflictException(MFA_ENABLED_CONFLICT); if (!user.twoFactorSecret) user.twoFactorSecret = this.authenticator.generateSecret(); if (!this.authenticator.check(code, user.twoFactorSecret)) throw new UnauthorizedException(INVALID_MFA_CODE); const result = await this.prisma.user.update({ where: { id: userId }, data: { twoFactorMethod: method, twoFactorSecret: user.twoFactorSecret }, }); return this.prisma.expose<User>(result); } async loginWithTotp( ipAddress: string, userAgent: string, token: string, code: string, origin?: string, ): Promise<TokenResponse> { const { id } = this.tokensService.verify<MfaTokenPayload>( MULTI_FACTOR_TOKEN, token, ); return this.loginUserWithTotpCode(ipAddress, userAgent, id, code, origin); } async loginWithEmailToken( ipAddress: string, userAgent: string, token: string, ): Promise<TokenResponse> { const { id } = this.tokensService.verify<MfaTokenPayload>( EMAIL_MFA_TOKEN, token, ); const user = await this.prisma.user.findUnique({ where: { id } }); if (!user) throw new NotFoundException(USER_NOT_FOUND); await this.approvedSubnetsService.upsertNewSubnet(id, ipAddress); return this.loginResponse(ipAddress, userAgent, user); } async requestPasswordReset(email: string, origin?: string) { const emailSafe = safeEmail(email); const emailDetails = await this.prisma.email.findFirst({ where: { emailSafe }, include: { user: true }, }); if (!emailDetails) throw new NotFoundException(USER_NOT_FOUND); this.email.send({ to: `"${emailDetails.user.name}" <${email}>`, template: 'auth/password-reset', data: { name: emailDetails.user.name, minutes: 30, link: `${ origin ?? this.configService.get<string>('frontendUrl') }/auth/link/reset-password?token=${this.tokensService.signJwt( PASSWORD_RESET_TOKEN, { id: emailDetails.user.id }, '30m', )}`, }, }); return { queued: true }; } async resetPassword( ipAddress: string, userAgent: string, token: string, password: string, ignorePwnedPassword?: boolean, ): Promise<TokenResponse> { const { id } = this.tokensService.verify<{ id: number }>( PASSWORD_RESET_TOKEN, token, ); const user = await this.prisma.user.findUnique({ where: { id }, include: { prefersEmail: true }, }); if (!user) throw new NotFoundException(USER_NOT_FOUND); password = await this.hashAndValidatePassword( password, !!ignorePwnedPassword, ); await this.prisma.user.update({ where: { id }, data: { password } }); await this.approvedSubnetsService.upsertNewSubnet(id, ipAddress); this.email.send({ to: `"${user.name}" <${user.prefersEmail.email}>`, template: 'users/password-changed', data: { name: user.name, }, }); return this.loginResponse(ipAddress, userAgent, user); } async verifyEmail( ipAddress: string, userAgent: string, token: string, origin?: string, ): Promise<TokenResponse> { const { id } = this.tokensService.verify<{ id: number }>( EMAIL_VERIFY_TOKEN, token, ); const result = await this.prisma.email.update({ where: { id }, data: { isVerified: true }, include: { user: true }, }); const groupsToJoin = await this.prisma.group.findMany({ where: { autoJoinDomain: true, domains: { some: { isVerified: true, domain: result.emailSafe.split('@')[1] }, }, }, select: { id: true, name: true }, }); for await (const group of groupsToJoin) { await this.prisma.membership.create({ data: { user: { connect: { id: result.user.id } }, group: { connect: { id: group.id } }, role: 'MEMBER', }, }); this.email.send({ to: `"${result.user.name}" <${result.email}>`, template: 'groups/invitation', data: { name: result.user.name, group: group.name, link: `${ origin ?? this.configService.get<string>('frontendUrl') }/groups/${group.id}`, }, }); } return this.loginResponse(ipAddress, userAgent, result.user); } getOneTimePassword(secret: string): string { return this.authenticator.generate(secret); } private async loginUserWithTotpCode( ipAddress: string, userAgent: string, id: number, code: string, origin?: string, ): Promise<TokenResponse> { const user = await this.prisma.user.findUnique({ where: { id }, include: { prefersEmail: true }, }); if (!user) throw new NotFoundException(USER_NOT_FOUND); if (user.twoFactorMethod === 'NONE' || !user.twoFactorSecret) throw new BadRequestException(MFA_NOT_ENABLED); if (this.authenticator.check(code, user.twoFactorSecret)) return this.loginResponse(ipAddress, userAgent, user); const backupCodes = await this.prisma.backupCode.findMany({ where: { user: { id } }, }); let usedBackupCode = false; for await (const backupCode of backupCodes) { if (await compare(code, backupCode.code)) { if (!usedBackupCode) { if (backupCode.isUsed) throw new UnauthorizedException(MFA_BACKUP_CODE_USED); usedBackupCode = true; await this.prisma.backupCode.update({ where: { id: backupCode.id }, data: { isUsed: true }, }); const location = await this.geolocationService.getLocation(ipAddress); const locationName = [ location?.city?.names?.en, (location?.subdivisions ?? [])[0]?.names?.en, location?.country?.names?.en, ] .filter((i) => i) .join(', ') || 'Unknown location'; if (user.prefersEmail) this.email.send({ to: `"${user.name}" <${user.prefersEmail.email}>`, template: 'auth/used-backup-code', data: { name: user.name, locationName, link: `${ origin ?? this.configService.get<string>('frontendUrl') }/users/${id}/sessions`, }, }); } } } if (!usedBackupCode) throw new UnauthorizedException(INVALID_MFA_CODE); return this.loginResponse(ipAddress, userAgent, user); } private async getAccessToken(user: User, sessionId: number): Promise<string> { const scopes = await this.getScopes(user); const payload: AccessTokenClaims = { id: user.id, sessionId, scopes, role: user.role, }; return this.tokensService.signJwt( LOGIN_ACCESS_TOKEN, payload, this.configService.get<string>('security.accessTokenExpiry'), ); } private async loginResponse( ipAddress: string, userAgent: string, user: User, ): Promise<TokenResponse> { const token = await this.tokensService.generateRandomString(64); const ua = new UAParser(userAgent); const location = await this.geolocationService.getLocation(ipAddress); const { id } = await this.prisma.session.create({ data: { token, ipAddress, city: location?.city?.names?.en, region: location?.subdivisions?.pop()?.names?.en, timezone: location?.location?.time_zone, countryCode: location?.country?.iso_code, userAgent, browser: `${ua.getBrowser().name ?? ''} ${ ua.getBrowser().version ?? '' }`.trim() || undefined, operatingSystem: `${ua.getOS().name ?? ''} ${ua.getOS().version ?? ''}` .replace('Mac OS', 'macOS') .trim() || undefined, user: { connect: { id: user.id } }, }, }); return { accessToken: await this.getAccessToken(user, id), refreshToken: token, }; } private async mfaResponse( user: User & { prefersEmail: Email; }, forceMethod?: MfaMethod, ): Promise<TotpTokenResponse> { const mfaTokenPayload: MfaTokenPayload = { type: user.twoFactorMethod, id: user.id, }; const totpToken = this.tokensService.signJwt( MULTI_FACTOR_TOKEN, mfaTokenPayload, this.configService.get<string>('security.mfaTokenExpiry'), ); if (user.twoFactorMethod === 'EMAIL' || forceMethod === 'EMAIL') { this.email.send({ to: `"${user.name}" <${user.prefersEmail.email}>`, template: 'auth/login-link', data: { name: user.name, minutes: parseInt( this.configService.get<string>('security.mfaTokenExpiry') ?? '', ), link: `${this.configService.get<string>( 'frontendUrl', )}/auth/link/login%2Ftoken?token=${this.tokensService.signJwt( EMAIL_MFA_TOKEN, { id: user.id }, '30m', )}`, }, }); } else if (user.twoFactorMethod === 'SMS' || forceMethod === 'SMS') { if (!user.twoFactorPhone) throw new BadRequestException(MFA_PHONE_NOT_FOUND); this.twilioService.send({ to: user.twoFactorPhone, body: `${this.getOneTimePassword(user.twoFactorSecret)} is your ${ this.configService.get<string>('meta.appName') ?? '' } verification code.`, }); } return { totpToken, type: forceMethod || user.twoFactorMethod, multiFactorRequired: true, }; } private async checkLoginSubnet( ipAddress: string, _: string, // userAgent checkLocationOnLogin: boolean, id: number, origin?: string, ): Promise<void> { if (!checkLocationOnLogin) return; const subnet = anonymize(ipAddress); const previousSubnets = await this.prisma.approvedSubnet.findMany({ where: { user: { id } }, }); let isApproved = false; for await (const item of previousSubnets) { if (!isApproved) if (await compare(subnet, item.subnet)) isApproved = true; } if (!isApproved) { const user = await this.prisma.user.findUnique({ where: { id }, select: { name: true, prefersEmail: true, checkLocationOnLogin: true }, }); if (!user) throw new NotFoundException(USER_NOT_FOUND); if (!user.checkLocationOnLogin) return; const location = await this.geolocationService.getLocation(ipAddress); const locationName = [ location?.city?.names?.en, (location?.subdivisions ?? [])[0]?.names?.en, location?.country?.names?.en, ] .filter((i) => i) .join(', ') || 'Unknown location'; if (user.prefersEmail) this.email.send({ to: `"${user.name}" <${user.prefersEmail.email}>`, template: 'auth/approve-subnet', data: { name: user.name, locationName, minutes: 30, link: `${ origin ?? this.configService.get<string>('frontendUrl') }/auth/link/approve-subnet?token=${this.tokensService.signJwt( APPROVE_SUBNET_TOKEN, { id }, '30m', )}`, }, }); throw new UnauthorizedException(UNVERIFIED_LOCATION); } } async hashAndValidatePassword( password: string, ignorePwnedPassword: boolean, ): Promise<string> { if (!ignorePwnedPassword) { if (!this.configService.get<boolean>('security.passwordPwnedCheck')) return await hash( password, this.configService.get<number>('security.saltRounds') ?? 10, ); if (!(await this.pwnedService.isPasswordSafe(password))) throw new BadRequestException(COMPROMISED_PASSWORD); } return await hash( password, this.configService.get<number>('security.saltRounds') ?? 10, ); } /** Get logging in scopes for a user */ async getScopes(user: User): Promise<string[]> { // Superadmins can do anything if (user.role === 'SUDO') return ['*']; // Add all scopes for user self const scopes: string[] = Object.keys(userScopes).map((scope) => scope.replace('{userId}', user.id.toString()), ); // Add scopes for groups user is part of const memberships = await this.prisma.membership.findMany({ where: { user: { id: user.id } }, select: { id: true, role: true, group: { select: { id: true } } }, }); for await (const membership of memberships) { scopes.push(`membership-${membership.id}:*`); const ids = [ membership.group.id, ...(await this.recursivelyGetSubgroupIds(membership.group.id)), ]; ids.forEach((id) => { if (membership.role === 'OWNER') scopes.push( ...Object.keys(groupOwnerScopes).map((i) => i.replace('{groupId}', id.toString()), ), ); if (membership.role === 'ADMIN') scopes.push( ...Object.keys(groupAdminScopes).map((i) => i.replace('{groupId}', id.toString()), ), ); if (membership.role === 'MEMBER') scopes.push( ...Object.keys(groupMemberScopes).map((i) => i.replace('{groupId}', id.toString()), ), ); }); } return scopes; } private async recursivelyGetSubgroupIds(groupId: number) { const subgroups = await this.prisma.group.findMany({ where: { parent: { id: groupId } }, select: { id: true, parent: { select: { id: true } }, subgroups: { select: { id: true } }, }, }); const ids = subgroups.map((i) => i.id); for await (const group of subgroups) { for await (const subgroup of group.subgroups) { const recurisiveIds = await this.recursivelyGetSubgroupIds(subgroup.id); ids.push(...recurisiveIds); } } return ids; } async mergeUsers(token: string): Promise<{ success: true }> { let baseUserId: number | undefined = undefined; let mergeUserId: number | undefined = undefined; try { const result = this.tokensService.verify<{ baseUserId: number; mergeUserId: number; }>(MERGE_ACCOUNTS_TOKEN, token); baseUserId = result.baseUserId; mergeUserId = result.mergeUserId; } catch (error) {} if (!baseUserId || !mergeUserId) throw new BadRequestException(USER_NOT_FOUND); return this.merge(baseUserId, mergeUserId); } private async merge( baseUserId: number, mergeUserId: number, ): Promise<{ success: true }> { const baseUser = await this.prisma.user.findUnique({ where: { id: baseUserId }, }); const mergeUser = await this.prisma.user.findUnique({ where: { id: mergeUserId }, }); if (!baseUser || !mergeUser) throw new NotFoundException(USER_NOT_FOUND); const combinedUser: Record<string, any> = {}; [ 'checkLocationOnLogin', 'countryCode', 'gender', 'name', 'notificationEmails', 'active', 'prefersLanguage', 'prefersColorScheme', 'prefersReducedMotion', 'profilePictureUrl', 'role', 'timezone', 'twoFactorMethod', 'twoFactorPhone', 'twoFactorSecret', 'attributes', ].forEach((key) => { if (mergeUser[key] != null) combinedUser[key] = mergeUser[key]; }); await this.prisma.user.update({ where: { id: baseUserId }, data: combinedUser, }); for await (const dataType of [ this.prisma.membership as Prisma.EmailDelegate, this.prisma.email as Prisma.EmailDelegate, this.prisma.session as Prisma.EmailDelegate, this.prisma.approvedSubnet as Prisma.EmailDelegate, this.prisma.backupCode as Prisma.EmailDelegate, this.prisma.identity as Prisma.EmailDelegate, this.prisma.auditLog as Prisma.EmailDelegate, this.prisma.apiKey as Prisma.EmailDelegate, ] as Prisma.EmailDelegate[]) { for await (const item of await (dataType as Prisma.EmailDelegate).findMany( { where: { user: { id: mergeUserId } }, select: { id: true }, }, )) await (dataType as Prisma.EmailDelegate).update({ where: { id: item.id }, data: { user: { connect: { id: baseUserId } } }, }); } await this.prisma.user.delete({ where: { id: mergeUser.id } }); return { success: true }; } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AuditManagerClient } from "./AuditManagerClient"; import { AssociateAssessmentReportEvidenceFolderCommand, AssociateAssessmentReportEvidenceFolderCommandInput, AssociateAssessmentReportEvidenceFolderCommandOutput, } from "./commands/AssociateAssessmentReportEvidenceFolderCommand"; import { BatchAssociateAssessmentReportEvidenceCommand, BatchAssociateAssessmentReportEvidenceCommandInput, BatchAssociateAssessmentReportEvidenceCommandOutput, } from "./commands/BatchAssociateAssessmentReportEvidenceCommand"; import { BatchCreateDelegationByAssessmentCommand, BatchCreateDelegationByAssessmentCommandInput, BatchCreateDelegationByAssessmentCommandOutput, } from "./commands/BatchCreateDelegationByAssessmentCommand"; import { BatchDeleteDelegationByAssessmentCommand, BatchDeleteDelegationByAssessmentCommandInput, BatchDeleteDelegationByAssessmentCommandOutput, } from "./commands/BatchDeleteDelegationByAssessmentCommand"; import { BatchDisassociateAssessmentReportEvidenceCommand, BatchDisassociateAssessmentReportEvidenceCommandInput, BatchDisassociateAssessmentReportEvidenceCommandOutput, } from "./commands/BatchDisassociateAssessmentReportEvidenceCommand"; import { BatchImportEvidenceToAssessmentControlCommand, BatchImportEvidenceToAssessmentControlCommandInput, BatchImportEvidenceToAssessmentControlCommandOutput, } from "./commands/BatchImportEvidenceToAssessmentControlCommand"; import { CreateAssessmentCommand, CreateAssessmentCommandInput, CreateAssessmentCommandOutput, } from "./commands/CreateAssessmentCommand"; import { CreateAssessmentFrameworkCommand, CreateAssessmentFrameworkCommandInput, CreateAssessmentFrameworkCommandOutput, } from "./commands/CreateAssessmentFrameworkCommand"; import { CreateAssessmentReportCommand, CreateAssessmentReportCommandInput, CreateAssessmentReportCommandOutput, } from "./commands/CreateAssessmentReportCommand"; import { CreateControlCommand, CreateControlCommandInput, CreateControlCommandOutput, } from "./commands/CreateControlCommand"; import { DeleteAssessmentCommand, DeleteAssessmentCommandInput, DeleteAssessmentCommandOutput, } from "./commands/DeleteAssessmentCommand"; import { DeleteAssessmentFrameworkCommand, DeleteAssessmentFrameworkCommandInput, DeleteAssessmentFrameworkCommandOutput, } from "./commands/DeleteAssessmentFrameworkCommand"; import { DeleteAssessmentReportCommand, DeleteAssessmentReportCommandInput, DeleteAssessmentReportCommandOutput, } from "./commands/DeleteAssessmentReportCommand"; import { DeleteControlCommand, DeleteControlCommandInput, DeleteControlCommandOutput, } from "./commands/DeleteControlCommand"; import { DeregisterAccountCommand, DeregisterAccountCommandInput, DeregisterAccountCommandOutput, } from "./commands/DeregisterAccountCommand"; import { DeregisterOrganizationAdminAccountCommand, DeregisterOrganizationAdminAccountCommandInput, DeregisterOrganizationAdminAccountCommandOutput, } from "./commands/DeregisterOrganizationAdminAccountCommand"; import { DisassociateAssessmentReportEvidenceFolderCommand, DisassociateAssessmentReportEvidenceFolderCommandInput, DisassociateAssessmentReportEvidenceFolderCommandOutput, } from "./commands/DisassociateAssessmentReportEvidenceFolderCommand"; import { GetAccountStatusCommand, GetAccountStatusCommandInput, GetAccountStatusCommandOutput, } from "./commands/GetAccountStatusCommand"; import { GetAssessmentCommand, GetAssessmentCommandInput, GetAssessmentCommandOutput, } from "./commands/GetAssessmentCommand"; import { GetAssessmentFrameworkCommand, GetAssessmentFrameworkCommandInput, GetAssessmentFrameworkCommandOutput, } from "./commands/GetAssessmentFrameworkCommand"; import { GetAssessmentReportUrlCommand, GetAssessmentReportUrlCommandInput, GetAssessmentReportUrlCommandOutput, } from "./commands/GetAssessmentReportUrlCommand"; import { GetChangeLogsCommand, GetChangeLogsCommandInput, GetChangeLogsCommandOutput, } from "./commands/GetChangeLogsCommand"; import { GetControlCommand, GetControlCommandInput, GetControlCommandOutput } from "./commands/GetControlCommand"; import { GetDelegationsCommand, GetDelegationsCommandInput, GetDelegationsCommandOutput, } from "./commands/GetDelegationsCommand"; import { GetEvidenceByEvidenceFolderCommand, GetEvidenceByEvidenceFolderCommandInput, GetEvidenceByEvidenceFolderCommandOutput, } from "./commands/GetEvidenceByEvidenceFolderCommand"; import { GetEvidenceCommand, GetEvidenceCommandInput, GetEvidenceCommandOutput } from "./commands/GetEvidenceCommand"; import { GetEvidenceFolderCommand, GetEvidenceFolderCommandInput, GetEvidenceFolderCommandOutput, } from "./commands/GetEvidenceFolderCommand"; import { GetEvidenceFoldersByAssessmentCommand, GetEvidenceFoldersByAssessmentCommandInput, GetEvidenceFoldersByAssessmentCommandOutput, } from "./commands/GetEvidenceFoldersByAssessmentCommand"; import { GetEvidenceFoldersByAssessmentControlCommand, GetEvidenceFoldersByAssessmentControlCommandInput, GetEvidenceFoldersByAssessmentControlCommandOutput, } from "./commands/GetEvidenceFoldersByAssessmentControlCommand"; import { GetOrganizationAdminAccountCommand, GetOrganizationAdminAccountCommandInput, GetOrganizationAdminAccountCommandOutput, } from "./commands/GetOrganizationAdminAccountCommand"; import { GetServicesInScopeCommand, GetServicesInScopeCommandInput, GetServicesInScopeCommandOutput, } from "./commands/GetServicesInScopeCommand"; import { GetSettingsCommand, GetSettingsCommandInput, GetSettingsCommandOutput } from "./commands/GetSettingsCommand"; import { ListAssessmentFrameworksCommand, ListAssessmentFrameworksCommandInput, ListAssessmentFrameworksCommandOutput, } from "./commands/ListAssessmentFrameworksCommand"; import { ListAssessmentReportsCommand, ListAssessmentReportsCommandInput, ListAssessmentReportsCommandOutput, } from "./commands/ListAssessmentReportsCommand"; import { ListAssessmentsCommand, ListAssessmentsCommandInput, ListAssessmentsCommandOutput, } from "./commands/ListAssessmentsCommand"; import { ListControlsCommand, ListControlsCommandInput, ListControlsCommandOutput, } from "./commands/ListControlsCommand"; import { ListKeywordsForDataSourceCommand, ListKeywordsForDataSourceCommandInput, ListKeywordsForDataSourceCommandOutput, } from "./commands/ListKeywordsForDataSourceCommand"; import { ListNotificationsCommand, ListNotificationsCommandInput, ListNotificationsCommandOutput, } from "./commands/ListNotificationsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { RegisterAccountCommand, RegisterAccountCommandInput, RegisterAccountCommandOutput, } from "./commands/RegisterAccountCommand"; import { RegisterOrganizationAdminAccountCommand, RegisterOrganizationAdminAccountCommandInput, RegisterOrganizationAdminAccountCommandOutput, } from "./commands/RegisterOrganizationAdminAccountCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateAssessmentCommand, UpdateAssessmentCommandInput, UpdateAssessmentCommandOutput, } from "./commands/UpdateAssessmentCommand"; import { UpdateAssessmentControlCommand, UpdateAssessmentControlCommandInput, UpdateAssessmentControlCommandOutput, } from "./commands/UpdateAssessmentControlCommand"; import { UpdateAssessmentControlSetStatusCommand, UpdateAssessmentControlSetStatusCommandInput, UpdateAssessmentControlSetStatusCommandOutput, } from "./commands/UpdateAssessmentControlSetStatusCommand"; import { UpdateAssessmentFrameworkCommand, UpdateAssessmentFrameworkCommandInput, UpdateAssessmentFrameworkCommandOutput, } from "./commands/UpdateAssessmentFrameworkCommand"; import { UpdateAssessmentStatusCommand, UpdateAssessmentStatusCommandInput, UpdateAssessmentStatusCommandOutput, } from "./commands/UpdateAssessmentStatusCommand"; import { UpdateControlCommand, UpdateControlCommandInput, UpdateControlCommandOutput, } from "./commands/UpdateControlCommand"; import { UpdateSettingsCommand, UpdateSettingsCommandInput, UpdateSettingsCommandOutput, } from "./commands/UpdateSettingsCommand"; import { ValidateAssessmentReportIntegrityCommand, ValidateAssessmentReportIntegrityCommandInput, ValidateAssessmentReportIntegrityCommandOutput, } from "./commands/ValidateAssessmentReportIntegrityCommand"; /** * <p>Welcome to the Audit Manager API reference. This guide is for developers who need detailed information about the Audit Manager API operations, data types, and errors. </p> * <p>Audit Manager is a service that provides automated evidence collection so that you * can continuously audit your Amazon Web Services usage, and assess the effectiveness of your controls to * better manage risk and simplify compliance.</p> * <p>Audit Manager provides pre-built frameworks that structure and automate assessments * for a given compliance standard. Frameworks include a pre-built collection of controls with * descriptions and testing procedures, which are grouped according to the requirements of the * specified compliance standard or regulation. You can also customize frameworks and controls * to support internal audits with unique requirements. </p> * * <p>Use the following links to get started with the Audit Manager API:</p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Operations.html">Actions</a>: An alphabetical list of all Audit Manager API operations.</p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Types.html">Data types</a>: An alphabetical list of all Audit Manager data types.</p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonParameters.html">Common parameters</a>: Parameters that all Query operations can use.</p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonErrors.html">Common errors</a>: Client and server errors that all operations can return.</p> * </li> * </ul> * * <p>If you're new to Audit Manager, we recommend that you review the <a href="https://docs.aws.amazon.com/audit-manager/latest/userguide/what-is.html"> Audit Manager User Guide</a>.</p> */ export class AuditManager extends AuditManagerClient { /** * <p> * Associates an evidence folder to the specified assessment report in Audit Manager. * </p> */ public associateAssessmentReportEvidenceFolder( args: AssociateAssessmentReportEvidenceFolderCommandInput, options?: __HttpHandlerOptions ): Promise<AssociateAssessmentReportEvidenceFolderCommandOutput>; public associateAssessmentReportEvidenceFolder( args: AssociateAssessmentReportEvidenceFolderCommandInput, cb: (err: any, data?: AssociateAssessmentReportEvidenceFolderCommandOutput) => void ): void; public associateAssessmentReportEvidenceFolder( args: AssociateAssessmentReportEvidenceFolderCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AssociateAssessmentReportEvidenceFolderCommandOutput) => void ): void; public associateAssessmentReportEvidenceFolder( args: AssociateAssessmentReportEvidenceFolderCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: AssociateAssessmentReportEvidenceFolderCommandOutput) => void), cb?: (err: any, data?: AssociateAssessmentReportEvidenceFolderCommandOutput) => void ): Promise<AssociateAssessmentReportEvidenceFolderCommandOutput> | void { const command = new AssociateAssessmentReportEvidenceFolderCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Associates a list of evidence to an assessment report in an Audit Manager assessment. * </p> */ public batchAssociateAssessmentReportEvidence( args: BatchAssociateAssessmentReportEvidenceCommandInput, options?: __HttpHandlerOptions ): Promise<BatchAssociateAssessmentReportEvidenceCommandOutput>; public batchAssociateAssessmentReportEvidence( args: BatchAssociateAssessmentReportEvidenceCommandInput, cb: (err: any, data?: BatchAssociateAssessmentReportEvidenceCommandOutput) => void ): void; public batchAssociateAssessmentReportEvidence( args: BatchAssociateAssessmentReportEvidenceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchAssociateAssessmentReportEvidenceCommandOutput) => void ): void; public batchAssociateAssessmentReportEvidence( args: BatchAssociateAssessmentReportEvidenceCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: BatchAssociateAssessmentReportEvidenceCommandOutput) => void), cb?: (err: any, data?: BatchAssociateAssessmentReportEvidenceCommandOutput) => void ): Promise<BatchAssociateAssessmentReportEvidenceCommandOutput> | void { const command = new BatchAssociateAssessmentReportEvidenceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Create a batch of delegations for a specified assessment in Audit Manager. * </p> */ public batchCreateDelegationByAssessment( args: BatchCreateDelegationByAssessmentCommandInput, options?: __HttpHandlerOptions ): Promise<BatchCreateDelegationByAssessmentCommandOutput>; public batchCreateDelegationByAssessment( args: BatchCreateDelegationByAssessmentCommandInput, cb: (err: any, data?: BatchCreateDelegationByAssessmentCommandOutput) => void ): void; public batchCreateDelegationByAssessment( args: BatchCreateDelegationByAssessmentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchCreateDelegationByAssessmentCommandOutput) => void ): void; public batchCreateDelegationByAssessment( args: BatchCreateDelegationByAssessmentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchCreateDelegationByAssessmentCommandOutput) => void), cb?: (err: any, data?: BatchCreateDelegationByAssessmentCommandOutput) => void ): Promise<BatchCreateDelegationByAssessmentCommandOutput> | void { const command = new BatchCreateDelegationByAssessmentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Deletes the delegations in the specified Audit Manager assessment. * </p> */ public batchDeleteDelegationByAssessment( args: BatchDeleteDelegationByAssessmentCommandInput, options?: __HttpHandlerOptions ): Promise<BatchDeleteDelegationByAssessmentCommandOutput>; public batchDeleteDelegationByAssessment( args: BatchDeleteDelegationByAssessmentCommandInput, cb: (err: any, data?: BatchDeleteDelegationByAssessmentCommandOutput) => void ): void; public batchDeleteDelegationByAssessment( args: BatchDeleteDelegationByAssessmentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchDeleteDelegationByAssessmentCommandOutput) => void ): void; public batchDeleteDelegationByAssessment( args: BatchDeleteDelegationByAssessmentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchDeleteDelegationByAssessmentCommandOutput) => void), cb?: (err: any, data?: BatchDeleteDelegationByAssessmentCommandOutput) => void ): Promise<BatchDeleteDelegationByAssessmentCommandOutput> | void { const command = new BatchDeleteDelegationByAssessmentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Disassociates a list of evidence from the specified assessment report in Audit Manager. * </p> */ public batchDisassociateAssessmentReportEvidence( args: BatchDisassociateAssessmentReportEvidenceCommandInput, options?: __HttpHandlerOptions ): Promise<BatchDisassociateAssessmentReportEvidenceCommandOutput>; public batchDisassociateAssessmentReportEvidence( args: BatchDisassociateAssessmentReportEvidenceCommandInput, cb: (err: any, data?: BatchDisassociateAssessmentReportEvidenceCommandOutput) => void ): void; public batchDisassociateAssessmentReportEvidence( args: BatchDisassociateAssessmentReportEvidenceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchDisassociateAssessmentReportEvidenceCommandOutput) => void ): void; public batchDisassociateAssessmentReportEvidence( args: BatchDisassociateAssessmentReportEvidenceCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: BatchDisassociateAssessmentReportEvidenceCommandOutput) => void), cb?: (err: any, data?: BatchDisassociateAssessmentReportEvidenceCommandOutput) => void ): Promise<BatchDisassociateAssessmentReportEvidenceCommandOutput> | void { const command = new BatchDisassociateAssessmentReportEvidenceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Uploads one or more pieces of evidence to the specified control in the assessment in Audit Manager. * </p> */ public batchImportEvidenceToAssessmentControl( args: BatchImportEvidenceToAssessmentControlCommandInput, options?: __HttpHandlerOptions ): Promise<BatchImportEvidenceToAssessmentControlCommandOutput>; public batchImportEvidenceToAssessmentControl( args: BatchImportEvidenceToAssessmentControlCommandInput, cb: (err: any, data?: BatchImportEvidenceToAssessmentControlCommandOutput) => void ): void; public batchImportEvidenceToAssessmentControl( args: BatchImportEvidenceToAssessmentControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchImportEvidenceToAssessmentControlCommandOutput) => void ): void; public batchImportEvidenceToAssessmentControl( args: BatchImportEvidenceToAssessmentControlCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: BatchImportEvidenceToAssessmentControlCommandOutput) => void), cb?: (err: any, data?: BatchImportEvidenceToAssessmentControlCommandOutput) => void ): Promise<BatchImportEvidenceToAssessmentControlCommandOutput> | void { const command = new BatchImportEvidenceToAssessmentControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Creates an assessment in Audit Manager. * </p> */ public createAssessment( args: CreateAssessmentCommandInput, options?: __HttpHandlerOptions ): Promise<CreateAssessmentCommandOutput>; public createAssessment( args: CreateAssessmentCommandInput, cb: (err: any, data?: CreateAssessmentCommandOutput) => void ): void; public createAssessment( args: CreateAssessmentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateAssessmentCommandOutput) => void ): void; public createAssessment( args: CreateAssessmentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAssessmentCommandOutput) => void), cb?: (err: any, data?: CreateAssessmentCommandOutput) => void ): Promise<CreateAssessmentCommandOutput> | void { const command = new CreateAssessmentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Creates a custom framework in Audit Manager. * </p> */ public createAssessmentFramework( args: CreateAssessmentFrameworkCommandInput, options?: __HttpHandlerOptions ): Promise<CreateAssessmentFrameworkCommandOutput>; public createAssessmentFramework( args: CreateAssessmentFrameworkCommandInput, cb: (err: any, data?: CreateAssessmentFrameworkCommandOutput) => void ): void; public createAssessmentFramework( args: CreateAssessmentFrameworkCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateAssessmentFrameworkCommandOutput) => void ): void; public createAssessmentFramework( args: CreateAssessmentFrameworkCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAssessmentFrameworkCommandOutput) => void), cb?: (err: any, data?: CreateAssessmentFrameworkCommandOutput) => void ): Promise<CreateAssessmentFrameworkCommandOutput> | void { const command = new CreateAssessmentFrameworkCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Creates an assessment report for the specified assessment. * </p> */ public createAssessmentReport( args: CreateAssessmentReportCommandInput, options?: __HttpHandlerOptions ): Promise<CreateAssessmentReportCommandOutput>; public createAssessmentReport( args: CreateAssessmentReportCommandInput, cb: (err: any, data?: CreateAssessmentReportCommandOutput) => void ): void; public createAssessmentReport( args: CreateAssessmentReportCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateAssessmentReportCommandOutput) => void ): void; public createAssessmentReport( args: CreateAssessmentReportCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAssessmentReportCommandOutput) => void), cb?: (err: any, data?: CreateAssessmentReportCommandOutput) => void ): Promise<CreateAssessmentReportCommandOutput> | void { const command = new CreateAssessmentReportCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Creates a new custom control in Audit Manager. * </p> */ public createControl( args: CreateControlCommandInput, options?: __HttpHandlerOptions ): Promise<CreateControlCommandOutput>; public createControl( args: CreateControlCommandInput, cb: (err: any, data?: CreateControlCommandOutput) => void ): void; public createControl( args: CreateControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateControlCommandOutput) => void ): void; public createControl( args: CreateControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateControlCommandOutput) => void), cb?: (err: any, data?: CreateControlCommandOutput) => void ): Promise<CreateControlCommandOutput> | void { const command = new CreateControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Deletes an assessment in Audit Manager. * </p> */ public deleteAssessment( args: DeleteAssessmentCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteAssessmentCommandOutput>; public deleteAssessment( args: DeleteAssessmentCommandInput, cb: (err: any, data?: DeleteAssessmentCommandOutput) => void ): void; public deleteAssessment( args: DeleteAssessmentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteAssessmentCommandOutput) => void ): void; public deleteAssessment( args: DeleteAssessmentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAssessmentCommandOutput) => void), cb?: (err: any, data?: DeleteAssessmentCommandOutput) => void ): Promise<DeleteAssessmentCommandOutput> | void { const command = new DeleteAssessmentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Deletes a custom framework in Audit Manager. * </p> */ public deleteAssessmentFramework( args: DeleteAssessmentFrameworkCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteAssessmentFrameworkCommandOutput>; public deleteAssessmentFramework( args: DeleteAssessmentFrameworkCommandInput, cb: (err: any, data?: DeleteAssessmentFrameworkCommandOutput) => void ): void; public deleteAssessmentFramework( args: DeleteAssessmentFrameworkCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteAssessmentFrameworkCommandOutput) => void ): void; public deleteAssessmentFramework( args: DeleteAssessmentFrameworkCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAssessmentFrameworkCommandOutput) => void), cb?: (err: any, data?: DeleteAssessmentFrameworkCommandOutput) => void ): Promise<DeleteAssessmentFrameworkCommandOutput> | void { const command = new DeleteAssessmentFrameworkCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Deletes an assessment report from an assessment in Audit Manager. * </p> */ public deleteAssessmentReport( args: DeleteAssessmentReportCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteAssessmentReportCommandOutput>; public deleteAssessmentReport( args: DeleteAssessmentReportCommandInput, cb: (err: any, data?: DeleteAssessmentReportCommandOutput) => void ): void; public deleteAssessmentReport( args: DeleteAssessmentReportCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteAssessmentReportCommandOutput) => void ): void; public deleteAssessmentReport( args: DeleteAssessmentReportCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAssessmentReportCommandOutput) => void), cb?: (err: any, data?: DeleteAssessmentReportCommandOutput) => void ): Promise<DeleteAssessmentReportCommandOutput> | void { const command = new DeleteAssessmentReportCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Deletes a custom control in Audit Manager. * </p> */ public deleteControl( args: DeleteControlCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteControlCommandOutput>; public deleteControl( args: DeleteControlCommandInput, cb: (err: any, data?: DeleteControlCommandOutput) => void ): void; public deleteControl( args: DeleteControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteControlCommandOutput) => void ): void; public deleteControl( args: DeleteControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteControlCommandOutput) => void), cb?: (err: any, data?: DeleteControlCommandOutput) => void ): Promise<DeleteControlCommandOutput> | void { const command = new DeleteControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Deregisters an account in Audit Manager. * </p> */ public deregisterAccount( args: DeregisterAccountCommandInput, options?: __HttpHandlerOptions ): Promise<DeregisterAccountCommandOutput>; public deregisterAccount( args: DeregisterAccountCommandInput, cb: (err: any, data?: DeregisterAccountCommandOutput) => void ): void; public deregisterAccount( args: DeregisterAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeregisterAccountCommandOutput) => void ): void; public deregisterAccount( args: DeregisterAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeregisterAccountCommandOutput) => void), cb?: (err: any, data?: DeregisterAccountCommandOutput) => void ): Promise<DeregisterAccountCommandOutput> | void { const command = new DeregisterAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the specified member account as a delegated administrator for Audit Manager. </p> * <important> * <p>When you remove a delegated administrator from your Audit Manager settings, or when you * deregister a delegated administrator from Organizations, you continue to have access * to the evidence that you previously collected under that account. However, Audit Manager * will stop collecting and attaching evidence to that delegated administrator account * moving forward.</p> * </important> */ public deregisterOrganizationAdminAccount( args: DeregisterOrganizationAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<DeregisterOrganizationAdminAccountCommandOutput>; public deregisterOrganizationAdminAccount( args: DeregisterOrganizationAdminAccountCommandInput, cb: (err: any, data?: DeregisterOrganizationAdminAccountCommandOutput) => void ): void; public deregisterOrganizationAdminAccount( args: DeregisterOrganizationAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeregisterOrganizationAdminAccountCommandOutput) => void ): void; public deregisterOrganizationAdminAccount( args: DeregisterOrganizationAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeregisterOrganizationAdminAccountCommandOutput) => void), cb?: (err: any, data?: DeregisterOrganizationAdminAccountCommandOutput) => void ): Promise<DeregisterOrganizationAdminAccountCommandOutput> | void { const command = new DeregisterOrganizationAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Disassociates an evidence folder from the specified assessment report in Audit Manager. * </p> */ public disassociateAssessmentReportEvidenceFolder( args: DisassociateAssessmentReportEvidenceFolderCommandInput, options?: __HttpHandlerOptions ): Promise<DisassociateAssessmentReportEvidenceFolderCommandOutput>; public disassociateAssessmentReportEvidenceFolder( args: DisassociateAssessmentReportEvidenceFolderCommandInput, cb: (err: any, data?: DisassociateAssessmentReportEvidenceFolderCommandOutput) => void ): void; public disassociateAssessmentReportEvidenceFolder( args: DisassociateAssessmentReportEvidenceFolderCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisassociateAssessmentReportEvidenceFolderCommandOutput) => void ): void; public disassociateAssessmentReportEvidenceFolder( args: DisassociateAssessmentReportEvidenceFolderCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: DisassociateAssessmentReportEvidenceFolderCommandOutput) => void), cb?: (err: any, data?: DisassociateAssessmentReportEvidenceFolderCommandOutput) => void ): Promise<DisassociateAssessmentReportEvidenceFolderCommandOutput> | void { const command = new DisassociateAssessmentReportEvidenceFolderCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns the registration status of an account in Audit Manager. * </p> */ public getAccountStatus( args: GetAccountStatusCommandInput, options?: __HttpHandlerOptions ): Promise<GetAccountStatusCommandOutput>; public getAccountStatus( args: GetAccountStatusCommandInput, cb: (err: any, data?: GetAccountStatusCommandOutput) => void ): void; public getAccountStatus( args: GetAccountStatusCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAccountStatusCommandOutput) => void ): void; public getAccountStatus( args: GetAccountStatusCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAccountStatusCommandOutput) => void), cb?: (err: any, data?: GetAccountStatusCommandOutput) => void ): Promise<GetAccountStatusCommandOutput> | void { const command = new GetAccountStatusCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns an assessment from Audit Manager. * </p> */ public getAssessment( args: GetAssessmentCommandInput, options?: __HttpHandlerOptions ): Promise<GetAssessmentCommandOutput>; public getAssessment( args: GetAssessmentCommandInput, cb: (err: any, data?: GetAssessmentCommandOutput) => void ): void; public getAssessment( args: GetAssessmentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAssessmentCommandOutput) => void ): void; public getAssessment( args: GetAssessmentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAssessmentCommandOutput) => void), cb?: (err: any, data?: GetAssessmentCommandOutput) => void ): Promise<GetAssessmentCommandOutput> | void { const command = new GetAssessmentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a framework from Audit Manager. * </p> */ public getAssessmentFramework( args: GetAssessmentFrameworkCommandInput, options?: __HttpHandlerOptions ): Promise<GetAssessmentFrameworkCommandOutput>; public getAssessmentFramework( args: GetAssessmentFrameworkCommandInput, cb: (err: any, data?: GetAssessmentFrameworkCommandOutput) => void ): void; public getAssessmentFramework( args: GetAssessmentFrameworkCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAssessmentFrameworkCommandOutput) => void ): void; public getAssessmentFramework( args: GetAssessmentFrameworkCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAssessmentFrameworkCommandOutput) => void), cb?: (err: any, data?: GetAssessmentFrameworkCommandOutput) => void ): Promise<GetAssessmentFrameworkCommandOutput> | void { const command = new GetAssessmentFrameworkCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns the URL of a specified assessment report in Audit Manager. * </p> */ public getAssessmentReportUrl( args: GetAssessmentReportUrlCommandInput, options?: __HttpHandlerOptions ): Promise<GetAssessmentReportUrlCommandOutput>; public getAssessmentReportUrl( args: GetAssessmentReportUrlCommandInput, cb: (err: any, data?: GetAssessmentReportUrlCommandOutput) => void ): void; public getAssessmentReportUrl( args: GetAssessmentReportUrlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAssessmentReportUrlCommandOutput) => void ): void; public getAssessmentReportUrl( args: GetAssessmentReportUrlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAssessmentReportUrlCommandOutput) => void), cb?: (err: any, data?: GetAssessmentReportUrlCommandOutput) => void ): Promise<GetAssessmentReportUrlCommandOutput> | void { const command = new GetAssessmentReportUrlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of changelogs from Audit Manager. * </p> */ public getChangeLogs( args: GetChangeLogsCommandInput, options?: __HttpHandlerOptions ): Promise<GetChangeLogsCommandOutput>; public getChangeLogs( args: GetChangeLogsCommandInput, cb: (err: any, data?: GetChangeLogsCommandOutput) => void ): void; public getChangeLogs( args: GetChangeLogsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetChangeLogsCommandOutput) => void ): void; public getChangeLogs( args: GetChangeLogsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetChangeLogsCommandOutput) => void), cb?: (err: any, data?: GetChangeLogsCommandOutput) => void ): Promise<GetChangeLogsCommandOutput> | void { const command = new GetChangeLogsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a control from Audit Manager. * </p> */ public getControl(args: GetControlCommandInput, options?: __HttpHandlerOptions): Promise<GetControlCommandOutput>; public getControl(args: GetControlCommandInput, cb: (err: any, data?: GetControlCommandOutput) => void): void; public getControl( args: GetControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetControlCommandOutput) => void ): void; public getControl( args: GetControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetControlCommandOutput) => void), cb?: (err: any, data?: GetControlCommandOutput) => void ): Promise<GetControlCommandOutput> | void { const command = new GetControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of delegations from an audit owner to a delegate. * </p> */ public getDelegations( args: GetDelegationsCommandInput, options?: __HttpHandlerOptions ): Promise<GetDelegationsCommandOutput>; public getDelegations( args: GetDelegationsCommandInput, cb: (err: any, data?: GetDelegationsCommandOutput) => void ): void; public getDelegations( args: GetDelegationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetDelegationsCommandOutput) => void ): void; public getDelegations( args: GetDelegationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDelegationsCommandOutput) => void), cb?: (err: any, data?: GetDelegationsCommandOutput) => void ): Promise<GetDelegationsCommandOutput> | void { const command = new GetDelegationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns evidence from Audit Manager. * </p> */ public getEvidence(args: GetEvidenceCommandInput, options?: __HttpHandlerOptions): Promise<GetEvidenceCommandOutput>; public getEvidence(args: GetEvidenceCommandInput, cb: (err: any, data?: GetEvidenceCommandOutput) => void): void; public getEvidence( args: GetEvidenceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEvidenceCommandOutput) => void ): void; public getEvidence( args: GetEvidenceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetEvidenceCommandOutput) => void), cb?: (err: any, data?: GetEvidenceCommandOutput) => void ): Promise<GetEvidenceCommandOutput> | void { const command = new GetEvidenceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns all evidence from a specified evidence folder in Audit Manager. * </p> */ public getEvidenceByEvidenceFolder( args: GetEvidenceByEvidenceFolderCommandInput, options?: __HttpHandlerOptions ): Promise<GetEvidenceByEvidenceFolderCommandOutput>; public getEvidenceByEvidenceFolder( args: GetEvidenceByEvidenceFolderCommandInput, cb: (err: any, data?: GetEvidenceByEvidenceFolderCommandOutput) => void ): void; public getEvidenceByEvidenceFolder( args: GetEvidenceByEvidenceFolderCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEvidenceByEvidenceFolderCommandOutput) => void ): void; public getEvidenceByEvidenceFolder( args: GetEvidenceByEvidenceFolderCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetEvidenceByEvidenceFolderCommandOutput) => void), cb?: (err: any, data?: GetEvidenceByEvidenceFolderCommandOutput) => void ): Promise<GetEvidenceByEvidenceFolderCommandOutput> | void { const command = new GetEvidenceByEvidenceFolderCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns an evidence folder from the specified assessment in Audit Manager. * </p> */ public getEvidenceFolder( args: GetEvidenceFolderCommandInput, options?: __HttpHandlerOptions ): Promise<GetEvidenceFolderCommandOutput>; public getEvidenceFolder( args: GetEvidenceFolderCommandInput, cb: (err: any, data?: GetEvidenceFolderCommandOutput) => void ): void; public getEvidenceFolder( args: GetEvidenceFolderCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEvidenceFolderCommandOutput) => void ): void; public getEvidenceFolder( args: GetEvidenceFolderCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetEvidenceFolderCommandOutput) => void), cb?: (err: any, data?: GetEvidenceFolderCommandOutput) => void ): Promise<GetEvidenceFolderCommandOutput> | void { const command = new GetEvidenceFolderCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns the evidence folders from a specified assessment in Audit Manager. * </p> */ public getEvidenceFoldersByAssessment( args: GetEvidenceFoldersByAssessmentCommandInput, options?: __HttpHandlerOptions ): Promise<GetEvidenceFoldersByAssessmentCommandOutput>; public getEvidenceFoldersByAssessment( args: GetEvidenceFoldersByAssessmentCommandInput, cb: (err: any, data?: GetEvidenceFoldersByAssessmentCommandOutput) => void ): void; public getEvidenceFoldersByAssessment( args: GetEvidenceFoldersByAssessmentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEvidenceFoldersByAssessmentCommandOutput) => void ): void; public getEvidenceFoldersByAssessment( args: GetEvidenceFoldersByAssessmentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetEvidenceFoldersByAssessmentCommandOutput) => void), cb?: (err: any, data?: GetEvidenceFoldersByAssessmentCommandOutput) => void ): Promise<GetEvidenceFoldersByAssessmentCommandOutput> | void { const command = new GetEvidenceFoldersByAssessmentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of evidence folders associated with a specified control of an assessment in Audit Manager. * </p> */ public getEvidenceFoldersByAssessmentControl( args: GetEvidenceFoldersByAssessmentControlCommandInput, options?: __HttpHandlerOptions ): Promise<GetEvidenceFoldersByAssessmentControlCommandOutput>; public getEvidenceFoldersByAssessmentControl( args: GetEvidenceFoldersByAssessmentControlCommandInput, cb: (err: any, data?: GetEvidenceFoldersByAssessmentControlCommandOutput) => void ): void; public getEvidenceFoldersByAssessmentControl( args: GetEvidenceFoldersByAssessmentControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEvidenceFoldersByAssessmentControlCommandOutput) => void ): void; public getEvidenceFoldersByAssessmentControl( args: GetEvidenceFoldersByAssessmentControlCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: GetEvidenceFoldersByAssessmentControlCommandOutput) => void), cb?: (err: any, data?: GetEvidenceFoldersByAssessmentControlCommandOutput) => void ): Promise<GetEvidenceFoldersByAssessmentControlCommandOutput> | void { const command = new GetEvidenceFoldersByAssessmentControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns the name of the delegated Amazon Web Services administrator account for the organization. * </p> */ public getOrganizationAdminAccount( args: GetOrganizationAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<GetOrganizationAdminAccountCommandOutput>; public getOrganizationAdminAccount( args: GetOrganizationAdminAccountCommandInput, cb: (err: any, data?: GetOrganizationAdminAccountCommandOutput) => void ): void; public getOrganizationAdminAccount( args: GetOrganizationAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetOrganizationAdminAccountCommandOutput) => void ): void; public getOrganizationAdminAccount( args: GetOrganizationAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetOrganizationAdminAccountCommandOutput) => void), cb?: (err: any, data?: GetOrganizationAdminAccountCommandOutput) => void ): Promise<GetOrganizationAdminAccountCommandOutput> | void { const command = new GetOrganizationAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of the in-scope Amazon Web Services services for the specified assessment. * </p> */ public getServicesInScope( args: GetServicesInScopeCommandInput, options?: __HttpHandlerOptions ): Promise<GetServicesInScopeCommandOutput>; public getServicesInScope( args: GetServicesInScopeCommandInput, cb: (err: any, data?: GetServicesInScopeCommandOutput) => void ): void; public getServicesInScope( args: GetServicesInScopeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetServicesInScopeCommandOutput) => void ): void; public getServicesInScope( args: GetServicesInScopeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetServicesInScopeCommandOutput) => void), cb?: (err: any, data?: GetServicesInScopeCommandOutput) => void ): Promise<GetServicesInScopeCommandOutput> | void { const command = new GetServicesInScopeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns the settings for the specified account. * </p> */ public getSettings(args: GetSettingsCommandInput, options?: __HttpHandlerOptions): Promise<GetSettingsCommandOutput>; public getSettings(args: GetSettingsCommandInput, cb: (err: any, data?: GetSettingsCommandOutput) => void): void; public getSettings( args: GetSettingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetSettingsCommandOutput) => void ): void; public getSettings( args: GetSettingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSettingsCommandOutput) => void), cb?: (err: any, data?: GetSettingsCommandOutput) => void ): Promise<GetSettingsCommandOutput> | void { const command = new GetSettingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of the frameworks available in the Audit Manager framework library. * </p> */ public listAssessmentFrameworks( args: ListAssessmentFrameworksCommandInput, options?: __HttpHandlerOptions ): Promise<ListAssessmentFrameworksCommandOutput>; public listAssessmentFrameworks( args: ListAssessmentFrameworksCommandInput, cb: (err: any, data?: ListAssessmentFrameworksCommandOutput) => void ): void; public listAssessmentFrameworks( args: ListAssessmentFrameworksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAssessmentFrameworksCommandOutput) => void ): void; public listAssessmentFrameworks( args: ListAssessmentFrameworksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAssessmentFrameworksCommandOutput) => void), cb?: (err: any, data?: ListAssessmentFrameworksCommandOutput) => void ): Promise<ListAssessmentFrameworksCommandOutput> | void { const command = new ListAssessmentFrameworksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of assessment reports created in Audit Manager. * </p> */ public listAssessmentReports( args: ListAssessmentReportsCommandInput, options?: __HttpHandlerOptions ): Promise<ListAssessmentReportsCommandOutput>; public listAssessmentReports( args: ListAssessmentReportsCommandInput, cb: (err: any, data?: ListAssessmentReportsCommandOutput) => void ): void; public listAssessmentReports( args: ListAssessmentReportsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAssessmentReportsCommandOutput) => void ): void; public listAssessmentReports( args: ListAssessmentReportsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAssessmentReportsCommandOutput) => void), cb?: (err: any, data?: ListAssessmentReportsCommandOutput) => void ): Promise<ListAssessmentReportsCommandOutput> | void { const command = new ListAssessmentReportsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of current and past assessments from Audit Manager. * </p> */ public listAssessments( args: ListAssessmentsCommandInput, options?: __HttpHandlerOptions ): Promise<ListAssessmentsCommandOutput>; public listAssessments( args: ListAssessmentsCommandInput, cb: (err: any, data?: ListAssessmentsCommandOutput) => void ): void; public listAssessments( args: ListAssessmentsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAssessmentsCommandOutput) => void ): void; public listAssessments( args: ListAssessmentsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAssessmentsCommandOutput) => void), cb?: (err: any, data?: ListAssessmentsCommandOutput) => void ): Promise<ListAssessmentsCommandOutput> | void { const command = new ListAssessmentsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of controls from Audit Manager. * </p> */ public listControls( args: ListControlsCommandInput, options?: __HttpHandlerOptions ): Promise<ListControlsCommandOutput>; public listControls(args: ListControlsCommandInput, cb: (err: any, data?: ListControlsCommandOutput) => void): void; public listControls( args: ListControlsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListControlsCommandOutput) => void ): void; public listControls( args: ListControlsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListControlsCommandOutput) => void), cb?: (err: any, data?: ListControlsCommandOutput) => void ): Promise<ListControlsCommandOutput> | void { const command = new ListControlsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of keywords that pre-mapped to the specified control data source. * </p> */ public listKeywordsForDataSource( args: ListKeywordsForDataSourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListKeywordsForDataSourceCommandOutput>; public listKeywordsForDataSource( args: ListKeywordsForDataSourceCommandInput, cb: (err: any, data?: ListKeywordsForDataSourceCommandOutput) => void ): void; public listKeywordsForDataSource( args: ListKeywordsForDataSourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListKeywordsForDataSourceCommandOutput) => void ): void; public listKeywordsForDataSource( args: ListKeywordsForDataSourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListKeywordsForDataSourceCommandOutput) => void), cb?: (err: any, data?: ListKeywordsForDataSourceCommandOutput) => void ): Promise<ListKeywordsForDataSourceCommandOutput> | void { const command = new ListKeywordsForDataSourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of all Audit Manager notifications. * </p> */ public listNotifications( args: ListNotificationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListNotificationsCommandOutput>; public listNotifications( args: ListNotificationsCommandInput, cb: (err: any, data?: ListNotificationsCommandOutput) => void ): void; public listNotifications( args: ListNotificationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListNotificationsCommandOutput) => void ): void; public listNotifications( args: ListNotificationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListNotificationsCommandOutput) => void), cb?: (err: any, data?: ListNotificationsCommandOutput) => void ): Promise<ListNotificationsCommandOutput> | void { const command = new ListNotificationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Returns a list of tags for the specified resource in Audit Manager. * </p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Enables Audit Manager for the specified account. * </p> */ public registerAccount( args: RegisterAccountCommandInput, options?: __HttpHandlerOptions ): Promise<RegisterAccountCommandOutput>; public registerAccount( args: RegisterAccountCommandInput, cb: (err: any, data?: RegisterAccountCommandOutput) => void ): void; public registerAccount( args: RegisterAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RegisterAccountCommandOutput) => void ): void; public registerAccount( args: RegisterAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RegisterAccountCommandOutput) => void), cb?: (err: any, data?: RegisterAccountCommandOutput) => void ): Promise<RegisterAccountCommandOutput> | void { const command = new RegisterAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Enables an account within the organization as the delegated administrator for Audit Manager. * </p> */ public registerOrganizationAdminAccount( args: RegisterOrganizationAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<RegisterOrganizationAdminAccountCommandOutput>; public registerOrganizationAdminAccount( args: RegisterOrganizationAdminAccountCommandInput, cb: (err: any, data?: RegisterOrganizationAdminAccountCommandOutput) => void ): void; public registerOrganizationAdminAccount( args: RegisterOrganizationAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RegisterOrganizationAdminAccountCommandOutput) => void ): void; public registerOrganizationAdminAccount( args: RegisterOrganizationAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RegisterOrganizationAdminAccountCommandOutput) => void), cb?: (err: any, data?: RegisterOrganizationAdminAccountCommandOutput) => void ): Promise<RegisterOrganizationAdminAccountCommandOutput> | void { const command = new RegisterOrganizationAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Tags the specified resource in Audit Manager. * </p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Removes a tag from a resource in Audit Manager. * </p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Edits an Audit Manager assessment. * </p> */ public updateAssessment( args: UpdateAssessmentCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateAssessmentCommandOutput>; public updateAssessment( args: UpdateAssessmentCommandInput, cb: (err: any, data?: UpdateAssessmentCommandOutput) => void ): void; public updateAssessment( args: UpdateAssessmentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateAssessmentCommandOutput) => void ): void; public updateAssessment( args: UpdateAssessmentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAssessmentCommandOutput) => void), cb?: (err: any, data?: UpdateAssessmentCommandOutput) => void ): Promise<UpdateAssessmentCommandOutput> | void { const command = new UpdateAssessmentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Updates a control within an assessment in Audit Manager. * </p> */ public updateAssessmentControl( args: UpdateAssessmentControlCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateAssessmentControlCommandOutput>; public updateAssessmentControl( args: UpdateAssessmentControlCommandInput, cb: (err: any, data?: UpdateAssessmentControlCommandOutput) => void ): void; public updateAssessmentControl( args: UpdateAssessmentControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateAssessmentControlCommandOutput) => void ): void; public updateAssessmentControl( args: UpdateAssessmentControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAssessmentControlCommandOutput) => void), cb?: (err: any, data?: UpdateAssessmentControlCommandOutput) => void ): Promise<UpdateAssessmentControlCommandOutput> | void { const command = new UpdateAssessmentControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Updates the status of a control set in an Audit Manager assessment. * </p> */ public updateAssessmentControlSetStatus( args: UpdateAssessmentControlSetStatusCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateAssessmentControlSetStatusCommandOutput>; public updateAssessmentControlSetStatus( args: UpdateAssessmentControlSetStatusCommandInput, cb: (err: any, data?: UpdateAssessmentControlSetStatusCommandOutput) => void ): void; public updateAssessmentControlSetStatus( args: UpdateAssessmentControlSetStatusCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateAssessmentControlSetStatusCommandOutput) => void ): void; public updateAssessmentControlSetStatus( args: UpdateAssessmentControlSetStatusCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAssessmentControlSetStatusCommandOutput) => void), cb?: (err: any, data?: UpdateAssessmentControlSetStatusCommandOutput) => void ): Promise<UpdateAssessmentControlSetStatusCommandOutput> | void { const command = new UpdateAssessmentControlSetStatusCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Updates a custom framework in Audit Manager. * </p> */ public updateAssessmentFramework( args: UpdateAssessmentFrameworkCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateAssessmentFrameworkCommandOutput>; public updateAssessmentFramework( args: UpdateAssessmentFrameworkCommandInput, cb: (err: any, data?: UpdateAssessmentFrameworkCommandOutput) => void ): void; public updateAssessmentFramework( args: UpdateAssessmentFrameworkCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateAssessmentFrameworkCommandOutput) => void ): void; public updateAssessmentFramework( args: UpdateAssessmentFrameworkCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAssessmentFrameworkCommandOutput) => void), cb?: (err: any, data?: UpdateAssessmentFrameworkCommandOutput) => void ): Promise<UpdateAssessmentFrameworkCommandOutput> | void { const command = new UpdateAssessmentFrameworkCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Updates the status of an assessment in Audit Manager. * </p> */ public updateAssessmentStatus( args: UpdateAssessmentStatusCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateAssessmentStatusCommandOutput>; public updateAssessmentStatus( args: UpdateAssessmentStatusCommandInput, cb: (err: any, data?: UpdateAssessmentStatusCommandOutput) => void ): void; public updateAssessmentStatus( args: UpdateAssessmentStatusCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateAssessmentStatusCommandOutput) => void ): void; public updateAssessmentStatus( args: UpdateAssessmentStatusCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAssessmentStatusCommandOutput) => void), cb?: (err: any, data?: UpdateAssessmentStatusCommandOutput) => void ): Promise<UpdateAssessmentStatusCommandOutput> | void { const command = new UpdateAssessmentStatusCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Updates a custom control in Audit Manager. * </p> */ public updateControl( args: UpdateControlCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateControlCommandOutput>; public updateControl( args: UpdateControlCommandInput, cb: (err: any, data?: UpdateControlCommandOutput) => void ): void; public updateControl( args: UpdateControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateControlCommandOutput) => void ): void; public updateControl( args: UpdateControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateControlCommandOutput) => void), cb?: (err: any, data?: UpdateControlCommandOutput) => void ): Promise<UpdateControlCommandOutput> | void { const command = new UpdateControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Updates Audit Manager settings for the current user account. * </p> */ public updateSettings( args: UpdateSettingsCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateSettingsCommandOutput>; public updateSettings( args: UpdateSettingsCommandInput, cb: (err: any, data?: UpdateSettingsCommandOutput) => void ): void; public updateSettings( args: UpdateSettingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateSettingsCommandOutput) => void ): void; public updateSettings( args: UpdateSettingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateSettingsCommandOutput) => void), cb?: (err: any, data?: UpdateSettingsCommandOutput) => void ): Promise<UpdateSettingsCommandOutput> | void { const command = new UpdateSettingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Validates the integrity of an assessment report in Audit Manager. * </p> */ public validateAssessmentReportIntegrity( args: ValidateAssessmentReportIntegrityCommandInput, options?: __HttpHandlerOptions ): Promise<ValidateAssessmentReportIntegrityCommandOutput>; public validateAssessmentReportIntegrity( args: ValidateAssessmentReportIntegrityCommandInput, cb: (err: any, data?: ValidateAssessmentReportIntegrityCommandOutput) => void ): void; public validateAssessmentReportIntegrity( args: ValidateAssessmentReportIntegrityCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ValidateAssessmentReportIntegrityCommandOutput) => void ): void; public validateAssessmentReportIntegrity( args: ValidateAssessmentReportIntegrityCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ValidateAssessmentReportIntegrityCommandOutput) => void), cb?: (err: any, data?: ValidateAssessmentReportIntegrityCommandOutput) => void ): Promise<ValidateAssessmentReportIntegrityCommandOutput> | void { const command = new ValidateAssessmentReportIntegrityCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import {Random} from "./simjs"; export class Project { constructor(public startYear: int, public totalAmount: number) {} } export class SubBucket { min = Number.MAX_SAFE_INTEGER; max = Number.MIN_SAFE_INTEGER; empty = true; } export class Bucket { min = Number.MAX_SAFE_INTEGER; max = Number.MIN_SAFE_INTEGER; /** * The sub buckets. The index of the sub bucket is the group to which it belongs * The index is a group index */ subBuckets = [ new SubBucket(), new SubBucket(), new SubBucket(), new SubBucket() ]; } export enum GroupIndex { GREEN = 0, YELLOW = 1, GRAY = 2, RED = 3 } export class Group { /** * The index of the group. Can be used to locate sub buckets */ groupIndex: GroupIndex; /** * Should a separator line been drawn for this group? */ separator: boolean; /** * Whats the percentage of values in this group to the total number of simulated values */ percentage = 0.0; /** * Whats the minimum value that is still part of this group */ from?: number; /** * Whats the maximum value (exclusive) that defines the upper end of this group */ to?: number; /** * Number of values in this group */ count = 0; constructor(index: GroupIndex, from?: number, to?: number, separator = true) { this.groupIndex = index; this.from = from; this.to = to; this.separator = separator; } } export class MinMax { constructor(public min: number, public max: number) {} } export class ProjectResult { /** * The minimal simulated value for this project */ min: number; /** * The maximal simulated value */ max: number; /** The median of the values found for this project */ median: number; /** * Defines where the 2/3 of the simulated values start / end. */ twoThird: MinMax; buckets: Bucket[]; groups: Group[]; constructor(public project: Project) {} } class Simulation { investmentAmount: number; liquidity: number; noInterestReferenceLine: number[] = []; numRuns: int; projectsByStartYear: { [year: number]: Project[] }; simulatedValues: number[][]; } class SimulationOptions { investmentAmount = 1000000; liquidity = 10000; numRuns = 10000; numYears = 10; performance = 0; projects: Project[] = []; seed: int | undefined = undefined; volatility = 0.01; } function toAbsoluteIndices(indices: number[], cashFlows: number[], investmentAmount: number) { const absolute = new Array<number>(indices.length); let currentPortfolioValue = investmentAmount; let previousYearIndex = 100.0; for (let relativeYear = 0; relativeYear < indices.length; ++relativeYear) { const currentYearIndex = indices[relativeYear]; const cashFlowStartOfYear = relativeYear === 0 ? 0 : cashFlows[relativeYear - 1]; // scale current value with performance gain according to index const performance = currentYearIndex / previousYearIndex; currentPortfolioValue = (currentPortfolioValue + cashFlowStartOfYear) * performance; absolute[relativeYear] = Math.round(currentPortfolioValue); previousYearIndex = currentYearIndex; } return absolute; } function simulateSingleAbsoluteOutcome(numYears: number, cashFlows: number[], options: SimulationOptions, random: Random) { const indices = new Array<number>(numYears + 1); indices[0] = 100; for (let i = 0; i < numYears; ++i) { const randomPerformance = 1 + random.normal(options.performance, options.volatility); indices[i + 1] = indices[i] * randomPerformance; } // convert the relative values from above to absolute values. return toAbsoluteIndices(indices, cashFlows, options.investmentAmount); } /** * Performs the monte carlo simulation for all years and num runs. * @param cashFlows the cash flows * @param numYears the number of years to simulate * @returns {number[][]} the simulated outcomes grouped by year */ function simulateOutcomes(cashFlows: number[], numYears: int, options: SimulationOptions): number[][] { const random = new Random(10); const result: number[][] = new Array(numYears); for (let year = 0; year <= numYears; ++year) { result[year] = new Array(options.numRuns); } for (let run = 0; run < options.numRuns; ++run) { const indices = simulateSingleAbsoluteOutcome(numYears, cashFlows, options, random); for (let year = 0; year < indices.length; ++year) { result[year][run] = indices[year]; } } return result; } function projectsToCashFlows(numYears: number, projectsByStartYear: Project[][]) { const cashFlows: number[] = []; for (let year = 0; year <= numYears; ++year) { const projectsByThisYear = projectsByStartYear[year] || []; const cashFlow = -projectsByThisYear.reduce((memo, project) => memo + project.totalAmount, 0.0); cashFlows.push(cashFlow); } return cashFlows; } function calculateNoInterestReferenceLine(cashFlows: number[], numYears: number, investmentAmount: number) { const noInterestReferenceLine: number[] = []; let investmentAmountLeft = investmentAmount; for (let year = 0; year <= numYears; ++year) { investmentAmountLeft = investmentAmountLeft + cashFlows[year]; noInterestReferenceLine.push(investmentAmountLeft); } return noInterestReferenceLine; } function performSimulation(options: SimulationOptions): Simulation { const projectsToSimulate: Project[] = options.projects; const projects = options.projects.sort((a, b) => a.startYear - b.startYear); // Group projects by startYear, use lodash groupBy instead const projectsByStartYear: Project[][] = []; for (const project of projects) { const arr = projectsByStartYear[project.startYear] = projectsByStartYear[project.startYear] || []; arr.push(project); } const numYears = projectsToSimulate.reduce((memo, project) => Math.max(memo, project.startYear), 0); const cashFlows = projectsToCashFlows(numYears, projectsByStartYear); const noInterestReferenceLine = calculateNoInterestReferenceLine(cashFlows, numYears, options.investmentAmount); const simulation = new Simulation(); simulation.investmentAmount = options.investmentAmount; simulation.liquidity = options.liquidity; simulation.noInterestReferenceLine = noInterestReferenceLine; simulation.numRuns = options.numRuns; simulation.projectsByStartYear = projectsByStartYear; simulation.simulatedValues = simulateOutcomes(cashFlows, numYears, options); return simulation; } function groupForValuePredicate(value) { "use speedyjs"; return group => (group.from === undefined || group.from <= value) && (group.to === undefined || group.to > value); } function createGroups(requiredAmount: number, noInterestReference: number, liquidity: number): Group[] { return [ new Group(GroupIndex.GREEN, requiredAmount, undefined, true), new Group(GroupIndex.YELLOW, requiredAmount - liquidity, requiredAmount), new Group(GroupIndex.GRAY, noInterestReference, requiredAmount - liquidity, false), new Group(GroupIndex.RED, undefined, noInterestReference, false) ]; } function calculateRequiredAmount(project: Project, simulation: Simulation) { let amount = project.totalAmount; const projectsSameYear = simulation.projectsByStartYear[project.startYear]; for (const otherProject of projectsSameYear) { if (otherProject === project) { break; } amount += otherProject.totalAmount; } return amount; } function median(values: number[]) { const half = Math.floor(values.length / 2); if (values.length % 2) { return values[half]; } return (values[half - 1] + values[half]) / 2.0; } function computeBucket(bucketStart: number, bucketSize: number, simulatedValuesThisYear: number[], groups: Group[]) { const bucket = new Bucket(); const bucketEnd = bucketStart + bucketSize; for (let j = bucketStart; j < bucketEnd; ++j) { const value = simulatedValuesThisYear[j]; bucket.min = Math.min(bucket.min, value); bucket.max = Math.max(bucket.max, value); const group = groups.find(groupForValuePredicate(simulatedValuesThisYear[j])); ++group.count; const subBucket = bucket.subBuckets[group.groupIndex]; subBucket.min = Math.min(subBucket.min, value); subBucket.max = Math.max(subBucket.max, value); subBucket.empty = false; } return bucket; } function computeBuckets(groups: Group[], simulatedValuesThisYear: number[]) { const NUMBER_OF_BUCKETS = 10; const bucketSize = Math.round(simulatedValuesThisYear.length / NUMBER_OF_BUCKETS) | 0; const buckets: Bucket[] = []; for (let i = 0; i < simulatedValuesThisYear.length; i += bucketSize) { const bucket = computeBucket(i, bucketSize, simulatedValuesThisYear, groups); buckets.push(bucket); } return buckets; } function compareNumbersInverse(a: number, b: number): number { return a - b; } function calculateProject(project: Project, simulation: Simulation): ProjectResult { const requiredAmount = calculateRequiredAmount(project, simulation); const simulatedValuesThisYear = simulation.simulatedValues[project.startYear]; simulatedValuesThisYear.sort(compareNumbersInverse); const groups = createGroups(requiredAmount, simulation.noInterestReferenceLine[project.startYear], simulation.liquidity); const buckets = computeBuckets(groups, simulatedValuesThisYear); const nonEmptyGroups = groups.filter(group => group.count > 0); nonEmptyGroups.forEach(group => group.percentage = group.count / simulatedValuesThisYear.length); const oneSixth = Math.round(simulatedValuesThisYear.length / 6); const result = new ProjectResult(project); result.buckets = buckets; result.groups = nonEmptyGroups; result.max = simulatedValuesThisYear[simulatedValuesThisYear.length - 1]; result.median = median(simulatedValuesThisYear); result.min = simulatedValuesThisYear[0]; result.twoThird = new MinMax(simulatedValuesThisYear[oneSixth], simulatedValuesThisYear[simulatedValuesThisYear.length - oneSixth]); return result; } export function monteCarlo(options: Partial<SimulationOptions>) { const initializedOptions = new SimulationOptions(); Object.assign(initializedOptions, options); const environment = performSimulation(initializedOptions); const results: ProjectResult[] = []; for (const project of options!.projects!) { results.push(calculateProject(project, environment)); } return results; }
the_stack
import { assert } from "chai"; import { mount, ReactWrapper, shallow } from "enzyme"; import * as React from "react"; import * as sinon from "sinon"; import { Menu } from "@blueprintjs/core"; import { IQueryListProps } from "@blueprintjs/select"; import { IFilm, renderFilm, TOP_100_FILMS } from "../../docs-app/src/common/films"; import { IQueryListRendererProps, IQueryListState, ItemListPredicate, ItemListRenderer, ItemPredicate, QueryList, } from "../src"; // this is an awkward import across the monorepo, but we'd rather not introduce a cyclical dependency or create another package type FilmQueryListWrapper = ReactWrapper<IQueryListProps<IFilm>, IQueryListState<IFilm>>; describe("<QueryList>", () => { const FilmQueryList = QueryList.ofType<IFilm>(); const testProps = { itemRenderer: sinon.spy(renderFilm), items: TOP_100_FILMS.slice(0, 20), onActiveItemChange: sinon.spy(), onItemSelect: sinon.spy(), renderer: sinon.spy((props: IQueryListRendererProps<IFilm>) => <div>{props.itemList}</div>), }; beforeEach(() => { testProps.itemRenderer.resetHistory(); testProps.onActiveItemChange.resetHistory(); testProps.onItemSelect.resetHistory(); testProps.renderer.resetHistory(); }); describe("items", () => { it("handles controlled changes to the whole items list", () => { const wrapper = shallow(<FilmQueryList {...testProps} />); const newItems = TOP_100_FILMS.slice(0, 1); wrapper.setProps({ items: newItems }); assert.deepEqual(wrapper.state("filteredItems"), newItems); }); }); describe("itemListRenderer", () => { const itemListRenderer: ItemListRenderer<IFilm> = props => ( <ul className="foo">{props.items.map(props.renderItem)}</ul> ); it("renderItem calls itemRenderer", () => { const wrapper = shallow(<FilmQueryList {...testProps} itemListRenderer={itemListRenderer} />); assert.lengthOf(wrapper.find("ul.foo"), 1, "should find element"); assert.equal(testProps.itemRenderer.callCount, 20); }); }); describe("filtering", () => { it("itemPredicate filters each item by query", () => { const predicate = sinon.spy((query: string, film: IFilm) => film.year === +query); shallow(<FilmQueryList {...testProps} itemPredicate={predicate} query="1994" />); assert.equal(predicate.callCount, testProps.items.length, "called once per item"); const { filteredItems } = testProps.renderer.args[0][0] as IQueryListRendererProps<IFilm>; assert.lengthOf(filteredItems, 3, "returns only films from 1994"); }); it("itemListPredicate filters entire list by query", () => { const predicate = sinon.spy((query: string, films: IFilm[]) => films.filter(f => f.year === +query)); shallow(<FilmQueryList {...testProps} itemListPredicate={predicate} query="1994" />); assert.equal(predicate.callCount, 1, "called once for entire list"); const { filteredItems } = testProps.renderer.args[0][0] as IQueryListRendererProps<IFilm>; assert.lengthOf(filteredItems, 3, "returns only films from 1994"); }); it("prefers itemListPredicate if both are defined", () => { const predicate = sinon.spy(() => true); const listPredicate: ItemListPredicate<any> = (_q, items) => items; const listPredicateSpy = sinon.spy(listPredicate); shallow( <FilmQueryList {...testProps} itemPredicate={predicate} itemListPredicate={listPredicateSpy} query="1980" />, ); assert.isTrue(listPredicateSpy.called, "listPredicate should be invoked"); assert.isFalse(predicate.called, "item predicate should not be invoked"); }); it("omitting both predicate props is supported", () => { shallow(<FilmQueryList {...testProps} query="1980" />); const { filteredItems } = testProps.renderer.args[0][0] as IQueryListRendererProps<IFilm>; assert.lengthOf(filteredItems, testProps.items.length, "returns all films"); }); it("ensure onActiveItemChange is not called with undefined and empty list", () => { const myItem = { title: "Toy Story 3", year: 2010, rank: 1 }; const filmQueryList = mount(<FilmQueryList {...testProps} items={[myItem]} activeItem={myItem} query="" />); filmQueryList.setState({ query: "query" }); filmQueryList.setState({ activeItem: undefined }); assert.equal(testProps.onActiveItemChange.callCount, 0); }); it("ensure onActiveItemChange is not called updating props and query doesn't change", () => { const myItem = { title: "Toy Story 3", year: 2010, rank: 1 }; const props: IQueryListProps<IFilm> = { ...testProps, activeItem: myItem, items: [myItem], query: "", }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); filmQueryList.setProps(props); assert.equal(testProps.onActiveItemChange.callCount, 0); }); it("ensure activeItem changes on query change", () => { const props: IQueryListProps<IFilm> = { ...testProps, items: [TOP_100_FILMS[0]], query: "abc", }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); assert.deepEqual(filmQueryList.state().activeItem, TOP_100_FILMS[0]); filmQueryList.setProps({ items: [TOP_100_FILMS[1]], query: "123", }); assert.deepEqual(filmQueryList.state().activeItem, TOP_100_FILMS[1]); }); it("ensure activeItem changes on when no longer in new items", () => { const props: IQueryListProps<IFilm> = { ...testProps, items: [TOP_100_FILMS[0]], query: "abc", }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); assert.deepEqual(filmQueryList.state().activeItem, TOP_100_FILMS[0]); filmQueryList.setProps({ items: [TOP_100_FILMS[1]], }); assert.deepEqual(filmQueryList.state().activeItem, TOP_100_FILMS[1]); }); }); describe("activeItem state initialization", () => { it("initializes to first filtered item when uncontrolled", () => { const props: IQueryListProps<IFilm> = { ...testProps, // Filter down to only item at index 11, so item at index 11 should be // chosen as default activeItem itemPredicate: (_query, item) => item === TOP_100_FILMS[11], query: "123", }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); assert(filmQueryList.state().activeItem === TOP_100_FILMS[11]); }); it("initializes to controlled activeItem prop (non-null)", () => { const props: IQueryListProps<IFilm> = { ...testProps, // List is not filtered, and item at index 11 is explicitly chosen as activeItem activeItem: TOP_100_FILMS[11], }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); assert(filmQueryList.state().activeItem === TOP_100_FILMS[11]); }); it("initializes to controlled activeItem prop (null)", () => { const props: IQueryListProps<IFilm> = { ...testProps, activeItem: null, }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); assert(filmQueryList.state().activeItem === null); }); it("createNewItemPosition affects position of create new item", () => { const props: IQueryListProps<IFilm> = { ...testProps, createNewItemFromQuery: sinon.spy(), createNewItemRenderer: () => <article />, items: TOP_100_FILMS.slice(0, 4), query: "the", }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); assert(filmQueryList.find(Menu).children().children().last().is("article")); filmQueryList.setProps({ createNewItemPosition: "first" }); assert(filmQueryList.find(Menu).children().children().first().is("article")); }); }); describe("scrolling", () => { it("brings active item into view"); }); describe("pasting", () => { const onItemsPaste = sinon.spy(); const itemPredicate: ItemPredicate<IFilm> = (query: string, film: IFilm, _i?: number, exactMatch?: boolean) => { return exactMatch === true ? query.toLowerCase() === film.title.toLowerCase() : true; }; function mountForPasteTest(overrideProps: Partial<IQueryListProps<IFilm>> = {}) { // Placeholder. This will be overwritten by the mounted component. let handlePaste: (queries: string[]) => void; const props: IQueryListProps<IFilm> = { ...testProps, itemPredicate, onItemsPaste, renderer: sinon.spy((listItemsProps: IQueryListRendererProps<IFilm>) => { handlePaste = listItemsProps.handlePaste; return testProps.renderer(listItemsProps); }), ...overrideProps, }; const filmQueryList: FilmQueryListWrapper = mount(<FilmQueryList {...props} />); // `handlePaste` will have been set by now, because `props.renderer` // will have been called. return { filmQueryList, handlePaste: handlePaste! }; } afterEach(() => { onItemsPaste.resetHistory(); }); it("converts 1 pasted value into an item", () => { const { filmQueryList, handlePaste } = mountForPasteTest(); const pastedValue = TOP_100_FILMS[0].title; handlePaste([pastedValue]); assert.isTrue(onItemsPaste.calledOnce); assert.deepEqual(onItemsPaste.args[0][0], [TOP_100_FILMS[0]]); assert.deepEqual(filmQueryList.state().activeItem, TOP_100_FILMS[0]); assert.deepEqual(filmQueryList.state().query, ""); }); it("convert multiple pasted values into items", () => { const { filmQueryList, handlePaste } = mountForPasteTest(); // Paste items in unsorted order for fun. const item1 = TOP_100_FILMS[6]; const item2 = TOP_100_FILMS[0]; const item3 = TOP_100_FILMS[3]; const pastedValue1 = item1.title; const pastedValue2 = item2.title; const pastedValue3 = item3.title; handlePaste([pastedValue1, pastedValue2, pastedValue3]); assert.isTrue(onItemsPaste.calledOnce); // Emits all three items. assert.deepEqual(onItemsPaste.args[0][0], [item1, item2, item3]); // Highlight the last item pasted. assert.deepEqual(filmQueryList.state().activeItem, item3); assert.deepEqual(filmQueryList.state().query, ""); }); it("concatenates unrecognized values into the ghost input by default", () => { const { filmQueryList, handlePaste } = mountForPasteTest(); const item2 = TOP_100_FILMS[6]; const item4 = TOP_100_FILMS[3]; const pastedValue1 = "unrecognized1"; const pastedValue2 = item2.title; const pastedValue3 = "unrecognized2"; const pastedValue4 = item4.title; handlePaste([pastedValue1, pastedValue2, pastedValue3, pastedValue4]); assert.isTrue(onItemsPaste.calledOnce); // Emits just the 2 valid items. assert.deepEqual(onItemsPaste.args[0][0], [item2, item4]); // Highlight the last item pasted. assert.deepEqual(filmQueryList.state().activeItem, item4); assert.deepEqual(filmQueryList.state().query, "unrecognized1, unrecognized2"); }); it("creates new items out of unrecognized values if 'Create item' option is enabled", () => { const createdRank = 0; const createdYear = 2019; const { filmQueryList, handlePaste } = mountForPasteTest({ // Must pass these two props to enable the "Create item" option. createNewItemFromQuery: query => ({ rank: createdRank, title: query, year: createdYear, }), createNewItemRenderer: () => <div>Create item</div>, }); const item1 = TOP_100_FILMS[6]; const item2 = TOP_100_FILMS[3]; const pastedValue1 = item1.title; const pastedValue2 = item2.title; // Paste this item last. const pastedValue3 = "unrecognized"; handlePaste([pastedValue1, pastedValue2, pastedValue3]); const createdItem = { title: "unrecognized", rank: createdRank, year: createdYear }; assert.isTrue(onItemsPaste.calledOnce); // Emits 2 existing items and 1 newly created item. assert.deepEqual(onItemsPaste.args[0][0], [item1, item2, createdItem]); // Highlight the last *already existing* item pasted. assert.deepEqual(filmQueryList.state().activeItem, item2); assert.deepEqual(filmQueryList.state().query, ""); }); }); describe("query", () => { it("trims leading and trailing whitespace when creating new items", () => { let triggerInputQueryChange: ((e: any) => void) | undefined; const createNewItemFromQuerySpy = sinon.spy(); const createNewItemRendererSpy = sinon.spy(); // we must supply our own renderer so that we can hook into IQueryListRendererProps#handleQueryChange const renderer = sinon.spy((props: IQueryListRendererProps<IFilm>) => { triggerInputQueryChange = props.handleQueryChange; return <div>{props.itemList}</div>; }); shallow( <FilmQueryList {...testProps} renderer={renderer} createNewItemFromQuery={createNewItemFromQuerySpy} createNewItemRenderer={createNewItemRendererSpy} />, ); const untrimmedQuery = " foo "; const trimmedQuery = untrimmedQuery.trim(); assert.isDefined(triggerInputQueryChange, "query list should render with input change callbacks"); triggerInputQueryChange!({ target: { value: untrimmedQuery } }); assert.isTrue(createNewItemFromQuerySpy.calledWith(trimmedQuery)); assert.isTrue(createNewItemRendererSpy.calledWith(trimmedQuery)); }); it("resets the query after creating new item if resetOnSelect=true", () => { const onQueryChangeSpy = runResetOnSelectTest(true); assert.isTrue(onQueryChangeSpy.calledWith("")); }); it("does not reset the query after creating new item if resetOnSelect=false", () => { const onQueryChangeSpy = runResetOnSelectTest(false); assert.isTrue(onQueryChangeSpy.notCalled); }); function runResetOnSelectTest(resetOnSelect: boolean): sinon.SinonSpy { let triggerItemCreate: ((e: any) => void) | undefined; const onQueryChangeSpy = sinon.spy(); // supply a custom renderer so we can hook into handleClick and invoke it ourselves later const createNewItemRenderer = sinon.spy( (_query: string, _active: boolean, handleClick: React.MouseEventHandler<HTMLElement>) => { triggerItemCreate = handleClick; return <div />; }, ); const queryList = shallow( <FilmQueryList {...testProps} // Must return something in order for item creation to work. // tslint:disable-next-line jsx-no-lambda createNewItemFromQuery={() => ({ title: "irrelevant", rank: 0, year: 0 })} createNewItemRenderer={createNewItemRenderer} onQueryChange={onQueryChangeSpy} resetOnSelect={resetOnSelect} />, ); // Change the query to something non-empty so we can ensure it wasn't cleared. // Ignore this change in the spy. (queryList.instance() as QueryList<IFilm>).setQuery("some query"); onQueryChangeSpy.resetHistory(); assert.isDefined(triggerItemCreate, "query list should pass click handler to createNewItemRenderer"); triggerItemCreate!({}); return onQueryChangeSpy; } }); });
the_stack
* @module Content */ import { assert, Id64String } from "@itwin/core-bentley"; import { ClassInfo, ClassInfoJSON, CompressedClassInfoJSON, RelatedClassInfo, RelatedClassInfoJSON, RelatedClassInfoWithOptionalRelationship, RelatedClassInfoWithOptionalRelationshipJSON, RelationshipPath, RelationshipPathJSON, } from "../EC"; import { CategoryDescription, CategoryDescriptionJSON } from "./Category"; import { Field, FieldDescriptor, FieldJSON, getFieldByName } from "./Fields"; /** * Data structure that describes an ECClass in content [[Descriptor]]. * @public */ export interface SelectClassInfo { /** Information about the ECClass */ selectClassInfo: ClassInfo; /** Is the class handled polymorphically */ isSelectPolymorphic: boolean; /** Relationship path from input class to the select class. */ pathFromInputToSelectClass?: RelatedClassInfoWithOptionalRelationship[]; /** Relationship paths to [related property]($docs/presentation/content/Terminology#related-properties) classes */ relatedPropertyPaths?: RelationshipPath[]; /** Relationship paths to navigation property classes */ navigationPropertyClasses?: RelatedClassInfo[]; /** Relationship paths to [related instance]($docs/presentation/content/Terminology#related-instance) classes. */ relatedInstancePaths?: RelationshipPath[]; } /** * Serialized [[SelectClassInfo]] JSON representation * @public */ export interface SelectClassInfoJSON<TClassInfoJSON = ClassInfoJSON> { selectClassInfo: TClassInfoJSON; isSelectPolymorphic: boolean; pathFromInputToSelectClass?: RelatedClassInfoWithOptionalRelationshipJSON<TClassInfoJSON>[]; relatedPropertyPaths?: RelationshipPathJSON<TClassInfoJSON>[]; navigationPropertyClasses?: RelatedClassInfoJSON<TClassInfoJSON>[]; relatedInstancePaths?: RelationshipPathJSON<TClassInfoJSON>[]; } /** @public */ export namespace SelectClassInfo { /** Deserialize [[SelectClassInfo]] from compressed JSON */ export function fromCompressedJSON(json: SelectClassInfoJSON<string>, classesMap: { [id: string]: CompressedClassInfoJSON }): SelectClassInfo { assert(classesMap.hasOwnProperty(json.selectClassInfo)); return { selectClassInfo: { id: json.selectClassInfo, ...classesMap[json.selectClassInfo] }, isSelectPolymorphic: json.isSelectPolymorphic, ...(json.navigationPropertyClasses ? { navigationPropertyClasses: json.navigationPropertyClasses.map((item) => RelatedClassInfo.fromCompressedJSON(item, classesMap)) } : undefined), ...(json.relatedInstancePaths ? { relatedInstancePaths: json.relatedInstancePaths.map((rip) => rip.map((item) => RelatedClassInfo.fromCompressedJSON(item, classesMap))) } : undefined), ...(json.pathFromInputToSelectClass ? { pathFromInputToSelectClass: json.pathFromInputToSelectClass.map((item) => RelatedClassInfoWithOptionalRelationship.fromCompressedJSON(item, classesMap)) } : undefined), ...(json.relatedPropertyPaths ? { relatedPropertyPaths: json.relatedPropertyPaths.map((path) => path.map((item) => RelatedClassInfo.fromCompressedJSON(item, classesMap))) } : undefined), }; } /** Serialize [[SelectClassInfo]] to compressed JSON */ export function toCompressedJSON(selectClass: SelectClassInfo, classesMap: { [id: string]: CompressedClassInfoJSON }): SelectClassInfoJSON<string> { const { id, ...leftOverClassInfo } = selectClass.selectClassInfo; classesMap[id] = leftOverClassInfo; return { selectClassInfo: id, isSelectPolymorphic: selectClass.isSelectPolymorphic, ...(selectClass.relatedInstancePaths ? { relatedInstancePaths: selectClass.relatedInstancePaths.map((rip) => rip.map((item) => RelatedClassInfo.toCompressedJSON(item, classesMap))) } : undefined), ...(selectClass.navigationPropertyClasses ? { navigationPropertyClasses: selectClass.navigationPropertyClasses.map((propertyClass) => RelatedClassInfo.toCompressedJSON(propertyClass, classesMap)) } : undefined), ...(selectClass.pathFromInputToSelectClass ? { pathFromInputToSelectClass: selectClass.pathFromInputToSelectClass.map((item) => RelatedClassInfoWithOptionalRelationship.toCompressedJSON(item, classesMap)) } : undefined), ...(selectClass.relatedPropertyPaths ? { relatedPropertyPaths: selectClass.relatedPropertyPaths.map((path) => path.map((relatedClass) => RelatedClassInfo.toCompressedJSON(relatedClass, classesMap))) } : undefined), }; } /** * Deserialize [[SelectClassInfo]] list from JSON * @param json JSON or JSON serialized to string to deserialize from * @returns Deserialized [[SelectClassInfo]] objects list * * @internal */ export function listFromCompressedJSON(json: SelectClassInfoJSON<Id64String>[], classesMap: { [id: string]: CompressedClassInfoJSON }): SelectClassInfo[] { return json.map((sci) => fromCompressedJSON(sci, classesMap)); } } /** * Flags that control content format. * @public */ export enum ContentFlags { /** Each content record only has [[InstanceKey]] and no data */ KeysOnly = 1 << 0, /** * Each content record additionally has an image id * @deprecated Use [[ExtendedDataRule]] instead. See [extended data usage page]($docs/presentation/customization/ExtendedDataUsage.md) for more details. */ ShowImages = 1 << 1, /** Each content record additionally has a display label */ ShowLabels = 1 << 2, /** All content records are merged into a single record (see [Merging values]($docs/presentation/content/terminology#value-merging)) */ MergeResults = 1 << 3, /** Content has only distinct values */ DistinctValues = 1 << 4, /** Doesn't create property or calculated fields. Can be used in conjunction with [[ShowLabels]]. */ NoFields = 1 << 5, /** * Set related input keys on [[Item]] objects when creating content. This helps identify which [[Item]] is associated to which * given input key at the cost of performance creating those items. * * @beta */ IncludeInputKeys = 1 << 8, } /** * Data sorting direction * @public */ export enum SortDirection { Ascending, Descending, } /** * Data structure that contains selection information. Used * for cases when requesting content after a selection change. * * @public */ export interface SelectionInfo { /** Name of selection provider which cause the selection change */ providerName: string; /** Level of selection that changed */ level?: number; } /** * Serialized [[Descriptor]] JSON representation. * @public */ export interface DescriptorJSON { classesMap: { [id: string]: CompressedClassInfoJSON }; connectionId: string; inputKeysHash: string; contentOptions: any; selectionInfo?: SelectionInfo; displayType: string; selectClasses: SelectClassInfoJSON<Id64String>[]; categories: CategoryDescriptionJSON[]; fields: FieldJSON<Id64String>[]; sortingFieldName?: string; sortDirection?: SortDirection; contentFlags: number; filterExpression?: string; } /** * Descriptor overrides that can be used to customize content * @public */ export interface DescriptorOverrides { /** * Content display type. Can be accessed in presentation rules and used * to modify content in various ways. Defaults to empty string. */ displayType?: string; /** Content flags used for content customization. See [[ContentFlags]] */ contentFlags?: number; /** Fields selector that allows excluding or including only specified fields. */ fieldsSelector?: { /** Should the specified fields be included or excluded */ type: "include" | "exclude"; /** A list of field descriptors that identify fields to include / exclude */ fields: FieldDescriptor[]; }; /** Specification for sorting data. */ sorting?: { /** Identifier of the field to use for sorting */ field: FieldDescriptor; /** Sort direction */ direction: SortDirection; }; /** [ECExpression]($docs/presentation/advanced/ECExpressions.md) for filtering content */ filterExpression?: string; } /** * Descriptor properties * @public */ export interface DescriptorSource { /** Id of the connection used to create the descriptor */ readonly connectionId?: string; /** Hash of the input keys used to create the descriptor */ readonly inputKeysHash?: string; /** Selection info used to create the descriptor */ readonly selectionInfo?: SelectionInfo; /** Display type used to create the descriptor */ readonly displayType: string; /** A list of classes that will be selected from when creating content with this descriptor */ readonly selectClasses: SelectClassInfo[]; /** A list of content field categories used in this descriptor */ readonly categories: CategoryDescription[]; /** A list of fields contained in the descriptor */ readonly fields: Field[]; /** [[ContentFlags]] used to create the descriptor */ readonly contentFlags: number; /** Field used to sort the content */ readonly sortingField?: Field; /** Sorting direction */ readonly sortDirection?: SortDirection; /** Content filtering [ECExpression]($docs/presentation/advanced/ECExpressions) */ readonly filterExpression?: string; } /** * Data structure that describes content: fields, sorting, filtering, format, etc. * Descriptor may be changed to control how content is created. * * @public */ export class Descriptor implements DescriptorSource { /** Id of the connection used to create the descriptor */ public readonly connectionId?: string; /** Hash of the input keys used to create the descriptor */ public readonly inputKeysHash?: string; /** Extended options used to create the descriptor */ public readonly contentOptions: any; /** Selection info used to create the descriptor */ public readonly selectionInfo?: SelectionInfo; /** Display type used to create the descriptor */ public readonly displayType: string; /** A list of classes that will be selected when creating content with this descriptor */ public readonly selectClasses: SelectClassInfo[]; /** A list of content field categories used in this descriptor */ public readonly categories: CategoryDescription[]; /** A list of fields contained in the descriptor */ public readonly fields: Field[]; /** [[ContentFlags]] used to create the descriptor */ public readonly contentFlags: number; /** Field used to sort the content */ public sortingField?: Field; /** Sorting direction */ public sortDirection?: SortDirection; /** Content filtering [ECExpression]($docs/presentation/advanced/ECExpressions) */ public filterExpression?: string; /** Construct a new Descriptor using a [[DescriptorSource]] */ public constructor(source: DescriptorSource) { this.connectionId = source.connectionId; this.inputKeysHash = source.inputKeysHash; this.selectionInfo = source.selectionInfo; this.displayType = source.displayType; this.contentFlags = source.contentFlags; this.selectClasses = [...source.selectClasses]; this.categories = [...source.categories]; this.fields = [...source.fields]; this.sortingField = source.sortingField; this.sortDirection = source.sortDirection; this.filterExpression = source.filterExpression; } /** Serialize [[Descriptor]] to JSON */ public toJSON(): DescriptorJSON { const classesMap: { [id: string]: CompressedClassInfoJSON } = {}; const selectClasses: SelectClassInfoJSON<string>[] = this.selectClasses.map((selectClass) => SelectClassInfo.toCompressedJSON(selectClass, classesMap)); const fields: FieldJSON<string>[] = this.fields.map((field) => field.toCompressedJSON(classesMap)); return Object.assign( { connectionId: this.connectionId, inputKeysHash: this.inputKeysHash, contentOptions: this.contentOptions, displayType: this.displayType, contentFlags: this.contentFlags, categories: this.categories.map(CategoryDescription.toJSON), fields, selectClasses, classesMap, }, this.sortingField !== undefined && { sortingFieldName: this.sortingField.name }, this.sortDirection !== undefined && { sortDirection: this.sortDirection }, this.filterExpression !== undefined && { filterExpression: this.filterExpression }, this.selectionInfo !== undefined && { selectionInfo: this.selectionInfo }, ); } /** Deserialize [[Descriptor]] from JSON */ public static fromJSON(json: DescriptorJSON | undefined): Descriptor | undefined { if (!json) return undefined; const { classesMap, ...leftOverJson } = json; const categories = CategoryDescription.listFromJSON(json.categories); const selectClasses = SelectClassInfo.listFromCompressedJSON(json.selectClasses, classesMap); const fields = this.getFieldsFromJSON(json.fields, (fieldJson) => Field.fromCompressedJSON(fieldJson, classesMap, categories)); return new Descriptor({ ...leftOverJson, selectClasses, categories, fields, sortingField: getFieldByName(fields, json.sortingFieldName, true), }); } private static getFieldsFromJSON(json: FieldJSON[], factory: (json: FieldJSON) => Field | undefined): Field[] { return json.map((fieldJson: FieldJSON) => { const field = factory(fieldJson); if (field) field.rebuildParentship(); return field; }).filter((field): field is Field => !!field); } /** * Get field by its name * @param name Name of the field to find * @param recurse Recurse into nested fields */ public getFieldByName(name: string, recurse?: boolean): Field | undefined { return getFieldByName(this.fields, name, recurse); } /** * Create descriptor overrides object from this descriptor. * @public */ public createDescriptorOverrides(): DescriptorOverrides { const overrides: DescriptorOverrides = {}; if (this.displayType) overrides.displayType = this.displayType; if (this.contentFlags !== 0) overrides.contentFlags = this.contentFlags; if (this.filterExpression) overrides.filterExpression = this.filterExpression; if (this.sortingField) overrides.sorting = { field: this.sortingField.getFieldDescriptor(), direction: this.sortDirection ?? SortDirection.Ascending }; return overrides; } }
the_stack
import { assert, log, logIf, LogLevel } from './auxiliaries'; import { byteSizeOfFormat } from './formatbytesizes'; import { AllocationRegister } from './allocationregister'; import { ContextMasquerade } from './contextmasquerade'; import { WEBGL1_EXTENSIONS, WEBGL2_DEFAULT_EXTENSIONS, WEBGL2_EXTENSIONS } from './extensions'; import { ExtensionsHash } from './extensionshash'; import { GL2Facade } from './gl2facade'; /* spellchecker: enable */ /** * A controller for either a WebGLRenderingContext or WebGL2RenderingContext. It requests a context, tracks context * attributes, extensions as well as multi frame specific rendering information and a (gpu)allocation registry. * * An instance of `Context` can be created only implicitly by requesting a context given a canvas element and its * dataset: * ``` * const element: HTMLCanvasElement = <HTMLCanvasElement>document.getElementById(canvasID); * this.context = Context.request(element); // element.dataset is used for attributes * ``` * The context supports the following data-attributes: * ``` * data-backend: 'auto' | 'webgl' | 'webgl2' * data-accumulation-format: 'auto' | 'float' | 'half' | 'byte' * ``` * * At run-time, cached context features can be queried without a performance impact, e.g., frequent extension-based * branching: * ``` * if(this.context.supportsVertexArrayObject) { * this.context.vertexArrayObject.bindVertexArrayOES(...); * ... * } * ``` * * For convenience, protected extension names such as `EXT_frag_depth` are not prefixed by an underscore. */ export class Context { /** * Context creation attribute defaults. The defaults are taken directly from the spec. */ protected static readonly DEFAULT_ATTRIBUTES = { alpha: true, antialias: false, /* Not defaulted to true, since it might interfere with manual blitting. */ depth: true, failIfMajorPerformanceCaveat: false, premultipliedAlpha: true, preserveDrawingBuffer: false, stencil: false, }; /** @see {@link backend} */ protected _backend: Context.BackendType | undefined; /** * Created context. The actual type depends on the created context. * @see {@link gl} */ protected _context: WebGLRenderingContext | WebGL2RenderingContext | undefined; /** @see {@link mask} */ protected _mask: ContextMasquerade | undefined; /** @see {@link gl2facade} */ protected _gl2: GL2Facade; /** * Creates a masquerade object that can be used for debugging. This is intended to be called when requesting a * context, i.e., before actually requesting it. For creation of a masquerade object, the following masquerade * specifiers are evaluated in the following order: * 1. msqrd_h GET parameter, * 2. msqrd_p GET parameter, * 3. data-msqrd-h attribute of the canvas element, and, finally, * 4. data-msqrd-p attribute of the canvas element. * If no specifier can be found, no object is created and undefined is returned. * @param dataset - Dataset of the canvas element that might provide a data-msqrd-{h,p} attribute. * @returns - Masquerade object when a specifier was found. If none was found undefined is returned. */ protected static createMasqueradeFromGETorDataAttribute(dataset: DOMStringMap): ContextMasquerade | undefined { const mask = ContextMasquerade.fromGET(); if (mask) { return mask; } if (dataset.msqrdH) { return ContextMasquerade.fromHash(dataset.msqrdH as string); } if (dataset.msqrdP) { return ContextMasquerade.fromPreset(dataset.msqrdP as string); } return undefined; } // WEBGL 1 & 2 CONTEXT /** * Create a WebGL context. Note: this should only be called once in constructor, because the second and subsequent * calls to getContext of an element will return null. * @param element - Canvas element to request context from. * @param attributes - Overrides the internal default attributes @see{Context.DEFAULT_ATTRIBUTES}. * @returns - Context providing either a WebGLRenderingContext, WebGL2RenderingContext. */ static request(element: HTMLCanvasElement, attributes: WebGLContextAttributes = Context.DEFAULT_ATTRIBUTES): Context { const dataset: DOMStringMap = element.dataset; const mask = Context.createMasqueradeFromGETorDataAttribute(dataset); /** Favor backend specification by masquerade over specification by data attribute. */ let request = mask ? (mask.backend as string) : dataset.backend ? (dataset.backend as string).toLowerCase() : 'auto'; if (!(request in Context.BackendRequestType)) { log(LogLevel.Warning, `unknown backend '${dataset.backend}' changed to '${Context.BackendRequestType.auto}'`); request = 'auto'; } switch (request) { case Context.BackendRequestType.webgl: break; case Context.BackendRequestType.experimental: case Context.BackendRequestType.webgl1: case Context.BackendRequestType.experimental1: request = Context.BackendRequestType.webgl; break; case Context.BackendRequestType.webgl2: case Context.BackendRequestType.experimental2: request = Context.BackendRequestType.webgl2; break; default: request = Context.BackendRequestType.auto; } let context; if (request !== Context.BackendRequestType.webgl) { context = this.requestWebGL2(element, attributes); } if (!context) { context = this.requestWebGL1(element, attributes); logIf(context !== undefined && request === Context.BackendRequestType.webgl2, LogLevel.Info, `backend changed to '${Context.BackendRequestType.webgl}', given '${request}'`); } assert(!!context, `creating a context failed`); return new Context(context, mask); } /** * Helper that tries to create a WebGL 1 context (requests to 'webgl' and 'experimental-webgl' are made). * @param element - Canvas element to request context from. * @param attributes - Overrides the internal default attributes @see{Context.CONTEXT_ATTRIBUTES}. * @returns {WebGLRenderingContext} - WebGL context object or null. */ protected static requestWebGL1(element: HTMLCanvasElement, attributes: WebGLContextAttributes = Context.DEFAULT_ATTRIBUTES): WebGLRenderingContext | undefined { let context = element.getContext(Context.BackendRequestType.webgl, attributes); if (context) { return context; } context = element.getContext(Context.BackendRequestType.experimental, attributes) as WebGLRenderingContext; return context === null ? undefined : context; } /** * Helper that tries to create a WebGL 2 context (requests to 'webgl2' and 'experimental-webgl2' are made). * @param element - Canvas element to request context from. * @param attributes - Overrides the internal default attributes @see{Context.CONTEXT_ATTRIBUTES}. * @returns {WebGL2RenderingContext} - WebGL2 context object or undefined. */ protected static requestWebGL2(element: HTMLCanvasElement, attributes: WebGLContextAttributes = Context.DEFAULT_ATTRIBUTES) : WebGL2RenderingContext | undefined { let context = element.getContext(Context.BackendRequestType.webgl2, attributes); if (context) { return context; } context = element.getContext(Context.BackendRequestType.experimental2, attributes) as WebGL2RenderingContext; return context === null ? undefined : context; } // CONTEXT ATTRIBUTES /** * Cached attributes of the context. */ protected _attributes: WebGLContextAttributes | undefined = undefined; protected queryAttributes(): void { const attributes = this._context!.getContextAttributes(); // Some browsers, e.g., Brave, might disable querying the attributes. if (attributes === null) { log(LogLevel.Error, `querying context attributes failed (probably blocked)`); return; } this._attributes = attributes; } /** * @link https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 * If the value is true, the drawing buffer has an alpha channel for the purposes of performing OpenGL destination * alpha operations and compositing with the page. If the value is false, no alpha buffer is available. */ get alpha(): boolean { return this._attributes ? this._attributes!.alpha as boolean : false; } /** * @link https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 * If the value is true and the implementation supports antialiasing the drawing buffer will perform antialiasing * using its choice of technique (multisample/supersample) and quality. If the value is false or the implementation * does not support antialiasing, no antialiasing is performed. */ get antialias(): boolean { return this._attributes ? this._attributes!.antialias as boolean : false; } /** * @link https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 * If the value is true, the drawing buffer has a depth buffer of at least 16 bits. If the value is false, no depth * buffer is available. */ get depth(): boolean { return this._attributes ? this._attributes!.depth as boolean : false; } /** * @link https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 * If the value is true, context creation will fail if the implementation determines that the performance of the * created WebGL context would be dramatically lower than that of a native application making equivalent OpenGL * calls... */ get failIfMajorPerformanceCaveat(): boolean { return this._attributes ? this._attributes!.failIfMajorPerformanceCaveat as boolean : false; } /** * @link https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 * If the value is true the page compositor will assume the drawing buffer contains colors with premultiplied alpha. * If the value is false the page compositor will assume that colors in the drawing buffer are not premultiplied. * This flag is ignored if the alpha flag is false. See Premultiplied Alpha for more information on the effects of * the premultipliedAlpha flag. */ get premultipliedAlpha(): boolean { return this._attributes ? this._attributes!.premultipliedAlpha as boolean : false; } /** * @link https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 * If false, once the drawing buffer is presented as described in theDrawing Buffer section, the contents of the * drawing buffer are cleared to their default values. All elements of the drawing buffer (color, depth and stencil) * are cleared. If the value is true the buffers will not be cleared and will preserve their values until cleared * or overwritten by the author. */ get preserveDrawingBuffer(): boolean { return this._attributes ? this._attributes!.preserveDrawingBuffer as boolean : false; } /** * @link https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 * If the value is true, the drawing buffer has a stencil buffer of at least 8 bits. If the value is false, no * stencil buffer is available. */ get stencil(): boolean { return this._attributes ? this._attributes!.stencil as boolean : false; } // EXTENSIONS /** * Cached extension supported by the context. */ protected _extensions: Array<string> = new Array<string>(); /** * Checks if the given extension is supported. Please note that a 'supports' call asserts whether or not the * extension is related to the WebGL version. For example, the following code would lead to an Error: * ``` * this.supports('ANGLE_instanced_arrays'); // asserts in WebGL2 since the extension is incorporated by default * ``` * If the context is masked by a ContextMasquerade the support of an extension might be concealed. * @param extension - Extension identifier to query support for. * @returns - True if the extension is supported, false otherwise. */ supports(extension: string): boolean { if (this._mask && this._mask.extensionsConceal.indexOf(extension) > -1) { return false; } switch (this._backend) { case Context.BackendType.WebGL1: assert(WEBGL1_EXTENSIONS.indexOf(extension) > -1, `extension ${extension} not available to WebGL1`); break; case Context.BackendType.WebGL2: assert(WEBGL2_DEFAULT_EXTENSIONS.indexOf(extension) === -1, `extension ${extension} supported by default in WebGL2`); assert(WEBGL2_EXTENSIONS.indexOf(extension) > -1, `extension ${extension} not available to WebGL2`); break; default: break; } return this._extensions.indexOf(extension) > -1; } /** * Enable provided extensions. Each extension is only enabled if it is supported. Alternatively the extension can * be queried for support and accessed (thereby enabled) directly. Thus, this function only acts as convenience * interface for something like a mandatory extension configuration etc. Also, some extensions only effect GLSL * capabilities and must be enabled explicitly without accessing the extension object. * @param extensions - Array of extensions identifier that are to be enabled. */ enable(extensions: Array<string>): void { for (const extension of extensions) { if (this.isWebGL1 && WEBGL1_EXTENSIONS.indexOf(extension) === -1) { continue; } if (this.isWebGL2 && WEBGL2_EXTENSIONS.indexOf(extension) === -1) { continue; } if (this.supports(extension) === false) { continue; } this.extension(undefined, extension); } } /** * Queries all extensions for the current context and stores the result (supported or not supported). This is * relevant to avoid continuous searches or regexp matching or substring queries in the complete extension string. * Instead, the support is queried once and can be explicitly request in the public interface using properties. * * This function should get called only once per Context instance. */ protected queryExtensionSupport(): void { const extensions = this._context!.getSupportedExtensions(); // Some browsers, e.g., Brave, might disable querying the supported extensions. if (extensions === null) { log(LogLevel.Error, `querying supported extensions failed (probably blocked)`); return; } // Only handle masquerade here and not within each supports-query? for (const extension of extensions) { if (this._mask && this._mask.extensionsConceal.indexOf(extension) > -1) { continue; } this._extensions.push(extension); } if (this._backend === Context.BackendType.WebGL1) { this.ANGLE_instanced_arrays_supported = this.supports('ANGLE_instanced_arrays'); this.EXT_blend_minmax_supported = this.supports('EXT_blend_minmax'); this.EXT_color_buffer_half_float_supported = this.supports('EXT_color_buffer_half_float'); this.EXT_disjoint_timer_query_supported = this.supports('EXT_disjoint_timer_query'); this.EXT_frag_depth_supported = this.supports('EXT_frag_depth'); this.EXT_sRGB_supported = this.supports('EXT_sRGB'); this.EXT_shader_texture_lod_supported = this.supports('EXT_shader_texture_lod'); this.OES_element_index_uint_supported = this.supports('OES_element_index_uint'); this.OES_standard_derivatives_supported = this.supports('OES_standard_derivatives'); this.OES_texture_float_supported = this.supports('OES_texture_float'); this.OES_texture_half_float_supported = this.supports('OES_texture_half_float'); this.OES_vertex_array_object_supported = this.supports('OES_vertex_array_object'); this.WEBGL_color_buffer_float_supported = this.supports('WEBGL_color_buffer_float'); this.WEBGL_depth_texture_supported = this.supports('WEBGL_depth_texture'); this.WEBGL_draw_buffers_supported = this.supports('WEBGL_draw_buffers'); } if (this._backend === Context.BackendType.WebGL2) { this.EXT_color_buffer_float_supported = this.supports('EXT_color_buffer_float'); this.EXT_disjoint_timer_query_webgl2_supported = this.supports('EXT_disjoint_timer_query_webgl2'); } this.EXT_texture_filter_anisotropic_supported = this.supports('EXT_texture_filter_anisotropic'); this.OES_texture_float_linear_supported = this.supports('OES_texture_float_linear'); this.OES_texture_half_float_linear_supported = this.supports('OES_texture_half_float_linear'); this.WEBGL_compressed_texture_astc_supported = this.supports('WEBGL_compressed_texture_astc'); this.WEBGL_compressed_texture_atc_supported = this.supports('WEBGL_compressed_texture_atc'); this.WEBGL_compressed_texture_etc_supported = this.supports('WEBGL_compressed_texture_etc'); this.WEBGL_compressed_texture_etc1_supported = this.supports('WEBGL_compressed_texture_etc1'); this.WEBGL_compressed_texture_pvrtc_supported = this.supports('WEBGL_compressed_texture_pvrtc'); this.WEBGL_compressed_texture_s3tc_supported = this.supports('WEBGL_compressed_texture_s3tc'); this.WEBGL_compressed_texture_s3tc_srgb_supported = this.supports('WEBGL_compressed_texture_s3tc_srgb'); this.WEBGL_debug_renderer_info_supported = this.supports('WEBGL_debug_renderer_info'); this.WEBGL_debug_shaders_supported = this.supports('WEBGL_debug_shaders'); this.WEBGL_lose_context_supported = this.supports('WEBGL_lose_context'); } /** * Returns the cached extensions object for the given extension identifier. If no extensions is cached, it is * queried. Asserts if the extension is provided by default in the current backend, not supported in general, or * unknown to the specification. * Please not that the availability of an extension might be concealed by the context's mask. * @param out - Member the extension object is cached into. * @param extension - Extension identifier to query. * @returns - Extension object. */ protected extension(out: any, extension: string): any { if (out === undefined) { assert(this.supports(extension), `extension ${extension} expected to be supported`); out = this._context!.getExtension(extension); } return out; } /** * Context this is of type 'any' for now, since WebGL2RenderingContext not available but supported. This * constructor is protected to enforce context creation using `request`. It queries extension support and * configures context specifics for convenience, e.g., HALF_FLOAT format. */ protected constructor(context: any, mask: ContextMasquerade | undefined) { this._context = context; this._mask = mask; const contextString = context.toString(); { // WebGL chrome debugger renames Context to CaptureContext const webgl1 = /WebGLRenderingContext/.test(contextString) || /CaptureContext/.test(contextString); const webgl2 = /WebGL2RenderingContext/.test(contextString); this._backend = webgl1 ? Context.BackendType.WebGL1 : webgl2 ? Context.BackendType.WebGL2 : undefined; } assert(this._backend !== undefined && this._backend.valueOf() !== Context.BackendType.Invalid.valueOf(), `context is neither webgl nor webgl2, given ${contextString}`); this.queryAttributes(); this.queryExtensionSupport(); // undefine all masked functions if (this._mask && this._mask.functionsUndefine) { for (const func in this._mask.functionsUndefine) { (this._context as any)[func] = undefined; } } // create an instance for a gl2 facade (unifies mandatory interfaces of the webgl and webgl2 api) this._gl2 = new GL2Facade(this); } /** @see {@link allocationRegister} */ protected _allocationRegister = new AllocationRegister(); /** * The context's GPU allocation register for use of tracking memory allocations. */ get allocationRegister(): AllocationRegister { return this._allocationRegister; } /** * The created rendering backend (webgl context type), either 'webgl' or 'webgl2' based on which one was * created successfully. If no context could be created undefined is returned. * @returns - Backend that was created on construction. */ get backend(): Context.BackendType | undefined { return this._backend; } /** * Provides a human-readable string of the backend. */ get backendString(): string | undefined { switch (this._backend) { case Context.BackendType.WebGL1: return 'WebGL'; case Context.BackendType.WebGL2: return 'WebGL2'; default: return undefined; } } /** * Provides an array of all extensions supported by the used WebGL1/2 context. */ get extensions(): Array<string> { return this._extensions; } /** * Masquerade object applied to a context instance. */ get mask(): ContextMasquerade | undefined { return this._mask; } /** * Access to either the WebGLRenderingContext or WebGL2RenderingContext. */ get gl(): any { // WebGLRenderingContext | WebGL2RenderingContext return this._context; } /** * WebGL2 facade for WebGL2 API like access to features mandatory to this engine. */ get gl2facade(): GL2Facade { return this._gl2; } /** * True if the context is a WebGL1 context, otherwise false. */ get isWebGL1(): boolean { return this._backend === Context.BackendType.WebGL1; } /** * True if the context is a WebGL2 context, otherwise false. */ get isWebGL2(): boolean { return this._backend === Context.BackendType.WebGL2; } // EXTENSION QUERIES // WebGL1, WebGL2-default protected ANGLE_instanced_arrays: any; protected ANGLE_instanced_arrays_supported: boolean; get supportsInstancedArrays(): boolean { return this.ANGLE_instanced_arrays_supported; } get instancedArrays(): any { return this.extension(this.ANGLE_instanced_arrays, 'ANGLE_instanced_arrays'); } // WebGL1, WebGL2-default protected EXT_blend_minmax: any; protected EXT_blend_minmax_supported: boolean; get supportsBlendMinmax(): boolean { return this.EXT_blend_minmax_supported; } get blendMinmax(): any { return this.extension(this.EXT_blend_minmax, 'EXT_blend_minmax'); } // WebGL1 protected EXT_color_buffer_half_float: any; protected EXT_color_buffer_half_float_supported: boolean; get supportsColorBufferHalfFloat(): boolean { return this.EXT_color_buffer_half_float_supported; } get colorBufferHalfFloat(): any { return this.extension(this.EXT_color_buffer_half_float, 'EXT_color_buffer_half_float'); } // WebGL1 protected EXT_disjoint_timer_query: any; protected EXT_disjoint_timer_query_supported: boolean; get supportsDisjointTimerQuery(): boolean { return this.EXT_disjoint_timer_query_supported; } get disjointTimerQuery(): any { return this.extension(this.EXT_disjoint_timer_query, 'EXT_disjoint_timer_query'); } // WebGL2 protected EXT_disjoint_timer_query_webgl2: any; protected EXT_disjoint_timer_query_webgl2_supported: boolean; get supportsDisjointTimerQueryWebGL2(): boolean { return this.EXT_disjoint_timer_query_webgl2_supported; } get disjointTimerQueryWebGL2(): any { return this.extension(this.EXT_disjoint_timer_query_webgl2, 'EXT_disjoint_timer_query_webgl2'); } // WebGL1, WebGL2-default protected EXT_frag_depth: any; protected EXT_frag_depth_supported: boolean; get supportsFragDepth(): boolean { return this.EXT_frag_depth_supported; } get fragDepth(): any { return this.extension(this.EXT_frag_depth, 'EXT_frag_depth'); } // WebGL1, WebGL2-default protected EXT_sRGB: any; protected EXT_sRGB_supported: boolean; get supportsSRGB(): boolean { return this.EXT_sRGB_supported; } get sRGB(): any { return this.extension(this.EXT_sRGB, 'EXT_sRGB'); } // WebGL1, WebGL2-default protected EXT_shader_texture_lod: any; protected EXT_shader_texture_lod_supported: boolean; get supportsShaderTextureLOD(): boolean { return this.EXT_shader_texture_lod_supported; } get shaderTextureLOD(): any { return this.extension(this.EXT_shader_texture_lod, 'EXT_shader_texture_lod'); } // WebGL1, WebGL2 protected EXT_texture_filter_anisotropic: any; protected EXT_texture_filter_anisotropic_supported: boolean; get supportsTextureFilterAnisotropic(): boolean { return this.EXT_texture_filter_anisotropic_supported; } get textureFilterAnisotropic(): any { return this.extension(this.EXT_texture_filter_anisotropic, 'EXT_texture_filter_anisotropic'); } // WebGL1, WebGL2-default protected OES_element_index_uint: any; protected OES_element_index_uint_supported: boolean; get supportsElementIndexUint(): boolean { return this.OES_element_index_uint_supported; } get elementIndexUint(): any { return this.extension(this.OES_element_index_uint, 'OES_element_index_uint'); } // WebGL1, WebGL2-default protected OES_standard_derivatives: any; protected OES_standard_derivatives_supported: boolean; get supportsStandardDerivatives(): boolean { return this.OES_standard_derivatives_supported; } get standardDerivatives(): any { return this.extension(this.OES_standard_derivatives, 'OES_standard_derivatives'); } // WebGL1, WebGL2-default protected OES_texture_float: any; protected OES_texture_float_supported: boolean; get supportsTextureFloat(): boolean { return this.OES_texture_float_supported; } get textureFloat(): any { return this.extension(this.OES_texture_float, 'OES_texture_float'); } // WebGL1, WebGL2 protected OES_texture_float_linear: any; protected OES_texture_float_linear_supported: boolean; get supportsTextureFloatLinear(): boolean { return this.OES_texture_float_linear_supported; } get textureFloatLinear(): any { return this.extension(this.OES_texture_float_linear, 'OES_texture_float_linear'); } // WebGL1, WebGL2-default protected OES_texture_half_float: any; protected OES_texture_half_float_supported: boolean; get supportsTextureHalfFloat(): boolean { return this.OES_texture_half_float_supported; } get textureHalfFloat(): any { return this.extension(this.OES_texture_half_float, 'OES_texture_half_float'); } // WebGL1, WebGL2 protected OES_texture_half_float_linear: any; protected OES_texture_half_float_linear_supported: boolean; get supportsTextureHalfFloatLinear(): boolean { return this.OES_texture_half_float_linear_supported; } get textureHalfFloatLinear(): any { return this.extension(this.OES_texture_half_float_linear, 'OES_texture_half_float_linear'); } // WebGL1, WebGL2-default protected OES_vertex_array_object: any; protected OES_vertex_array_object_supported: boolean; get supportsVertexArrayObject(): boolean { return this.OES_vertex_array_object_supported; } get vertexArrayObject(): any { return this.extension(this.OES_vertex_array_object, 'OES_vertex_array_object'); } // WebGL1 protected WEBGL_color_buffer_float: any; protected WEBGL_color_buffer_float_supported: boolean; // WebGL2 protected EXT_color_buffer_float: any; protected EXT_color_buffer_float_supported: boolean; get supportsColorBufferFloat(): boolean | undefined { switch (this._backend) { case Context.BackendType.WebGL1: return this.WEBGL_color_buffer_float_supported; case Context.BackendType.WebGL2: return this.EXT_color_buffer_float_supported; default: return undefined; } } get colorBufferFloat(): any | undefined { switch (this._backend) { case Context.BackendType.WebGL1: return this.extension(this.WEBGL_color_buffer_float, 'WEBGL_color_buffer_float'); case Context.BackendType.WebGL2: return this.extension(this.EXT_color_buffer_float, 'EXT_color_buffer_float'); default: return undefined; } } // WebGL1, WebGL2 protected WEBGL_compressed_texture_astc: any; protected WEBGL_compressed_texture_astc_supported: boolean; get supportsCompressedTextureASTC(): boolean { return this.WEBGL_compressed_texture_astc_supported; } get compressedTextureASTC(): any { return this.extension(this.WEBGL_compressed_texture_astc, 'WEBGL_compressed_texture_astc'); } // WebGL1, WebGL2 protected WEBGL_compressed_texture_atc: any; protected WEBGL_compressed_texture_atc_supported: boolean; get supportsCompressedTextureATC(): boolean { return this.WEBGL_compressed_texture_atc_supported; } get compressedTextureATC(): any { return this.extension(this.WEBGL_compressed_texture_atc, 'WEBGL_compressed_texture_atc'); } // WebGL1, WebGL2 protected WEBGL_compressed_texture_etc: any; protected WEBGL_compressed_texture_etc_supported: boolean; get supportsCompressedTextureETC(): boolean { return this.WEBGL_compressed_texture_etc_supported; } get compressedTextureETC(): any { return this.extension(this.WEBGL_compressed_texture_etc, 'WEBGL_compressed_texture_etc'); } // WebGL1, WebGL2 protected WEBGL_compressed_texture_etc1: any; protected WEBGL_compressed_texture_etc1_supported: boolean; get supportsCompressedTextureETC1(): boolean { return this.WEBGL_compressed_texture_etc1_supported; } get compressedTextureETC1(): any { return this.extension(this.WEBGL_compressed_texture_etc1, 'WEBGL_compressed_texture_etc1'); } // WebGL1, WebGL2 protected WEBGL_compressed_texture_pvrtc: any; protected WEBGL_compressed_texture_pvrtc_supported: boolean; get supportsCompressedTexturePVRTC(): boolean { return this.WEBGL_compressed_texture_pvrtc_supported; } get compressedTexturePVRTC(): any { return this.extension(this.WEBGL_compressed_texture_pvrtc, 'WEBGL_compressed_texture_pvrtc'); } // WebGL1, WebGL2 protected WEBGL_compressed_texture_s3tc: any; protected WEBGL_compressed_texture_s3tc_supported: boolean; get supportsCompressedTextureS3TC(): boolean { return this.WEBGL_compressed_texture_s3tc_supported; } get compressedTextureS3TC(): any { return this.extension(this.WEBGL_compressed_texture_s3tc, 'WEBGL_compressed_texture_s3tc'); } // WebGL1, WebGL2 protected WEBGL_compressed_texture_s3tc_srgb: any; protected WEBGL_compressed_texture_s3tc_srgb_supported: boolean; get supportsCompressedTextureS3TCSRGB(): boolean { return this.WEBGL_compressed_texture_s3tc_srgb_supported; } get compressedTextureS3TCSRGB(): any { return this.extension(this.WEBGL_compressed_texture_s3tc_srgb, 'WEBGL_compressed_texture_s3tc_srgb'); } // WebGL1, WebGL2 protected WEBGL_debug_renderer_info: any; protected WEBGL_debug_renderer_info_supported: boolean; get supportsDebugRendererInfo(): boolean { return this.WEBGL_debug_renderer_info_supported; } get debugRendererInfo(): any { return this.extension(this.WEBGL_debug_renderer_info, 'WEBGL_debug_renderer_info'); } // WebGL1, WebGL2 protected WEBGL_debug_shaders: any; protected WEBGL_debug_shaders_supported: boolean; get supportsDebugShaders(): boolean { return this.WEBGL_debug_shaders_supported; } get debugShaders(): any { return this.extension(this.WEBGL_debug_shaders, 'WEBGL_debug_shaders'); } // WebGL1, WebGL2-default protected WEBGL_depth_texture: any; protected WEBGL_depth_texture_supported: boolean; get supportsDepthTexture(): boolean { return this.WEBGL_depth_texture_supported; } get depthTexture(): any { return this.extension(this.WEBGL_depth_texture, 'WEBGL_depth_texture'); } // WebGL1, WebGL2-default protected WEBGL_draw_buffers: any; protected WEBGL_draw_buffers_supported: boolean; get supportsDrawBuffers(): boolean { return this.WEBGL_draw_buffers_supported; } get drawBuffers(): any { return this.extension(this.WEBGL_draw_buffers, 'WEBGL_draw_buffers'); } // WebGL1, WebGL2 protected WEBGL_lose_context: any; protected WEBGL_lose_context_supported: boolean; get supportsLoseContext(): boolean { return this.WEBGL_lose_context_supported; } get loseContext(): any { return this.extension(this.WEBGL_lose_context, 'WEBGL_lose_context'); } // FUNCTION QUERIES /** * True if WebGL2 blitFramebuffer is supported, false otherwise. This is experimental technology. */ get supportsBlitFramebuffer(): boolean { return (this._context as any).blitFramebuffer !== undefined; } /** * True if WebGL2 readBuffer is supported, false otherwise. This is experimental technology. */ get supportsReadBuffer(): boolean { return (this._context as any).readBuffer !== undefined; } /** * True if WebGL2 texImage3D draft is supported, false otherwise. This is experimental technology. */ get supportsTexImage3D(): boolean { return (this._context as any).texImage3D !== undefined; } // PARAMETER QUERIES param(pname: GLenum): any { assert(!!this._context, `expected context to be valid`); return this._context!.getParameter(pname); } /** * Provides the context's extension hash. The hash can be used for context masquerade. */ hash(): string { return ExtensionsHash.encode(this._backend as Context.BackendType, this._extensions); } /** * Queries various parameters (depending on the type of context and support of extensions) and returns them as * formatted string. * @returns - Array of 2-tuple containing (1) the queried enum as string and (2) the resulting parameter value. */ about(): Array<[string, number | string]> { const available = 'ok'; const unavailable = 'na'; if (this._backend === Context.BackendType.Invalid) { return new Array<[string, number | string]>(); } assert(!!this._context, `expected context to be valid`); const context = this._context!; const pNamesAndValues = new Array<[string, number | string]>(); pNamesAndValues.push(['BACKEND (GLOPERATE)', this.backend as Context.BackendType]); pNamesAndValues.push(['CONTEXT_HASH (GLOPERATE)', this.hash()]); pNamesAndValues.push(['RENDERER', this.param(context.RENDERER)]); pNamesAndValues.push(['VENDOR', this.param(context.VENDOR)]); pNamesAndValues.push(['VERSION', this.param(context.VERSION)]); pNamesAndValues.push(['SHADING_LANGUAGE_VERSION', this.param(context.SHADING_LANGUAGE_VERSION)]); /* Debug Render Info Extension - Unmasked Vendor and Renderer. */ pNamesAndValues.push(['UNMASKED_VENDOR_WEBGL', !this.supportsDebugRendererInfo ? unavailable : this.param(this.debugRendererInfo.UNMASKED_VENDOR_WEBGL)]); pNamesAndValues.push(['UNMASKED_RENDERER_WEBGL', !this.supportsDebugRendererInfo ? unavailable : this.param(this.debugRendererInfo.UNMASKED_RENDERER_WEBGL)]); /* Actual Context Attributes. */ pNamesAndValues.push(['ALPHA (ATTRIBUTE)', String(this.alpha)]); pNamesAndValues.push(['ANTIALIAS (ATTRIBUTE)', String(this.antialias)]); pNamesAndValues.push(['DEPTH (ATTRIBUTE)', String(this.depth)]); pNamesAndValues.push(['FAIL_IF_MAJOR_PERFORMANCE_CAVEAT (ATTRIBUTE)', String(this.failIfMajorPerformanceCaveat)]); pNamesAndValues.push(['PREMULTIPLIED_ALPHA (ATTRIBUTE)', String(this.premultipliedAlpha)]); pNamesAndValues.push(['PRESERVE_DRAWING_BUFFER (ATTRIBUTE)', String(this.preserveDrawingBuffer)]); pNamesAndValues.push(['STENCIL (ATTRIBUTE)', String(this.stencil)]); /* Window Info. */ pNamesAndValues.push(['DEVICE_PIXEL_RATIO (WINDOW)', window.devicePixelRatio]); /* Navigator Info. */ pNamesAndValues.push(['APP_CODE_NAME (NAVIGATOR)', window.navigator.appCodeName]); pNamesAndValues.push(['APP_NAME (NAVIGATOR)', window.navigator.appName]); pNamesAndValues.push(['APP_VERSION (NAVIGATOR)', window.navigator.appVersion]); pNamesAndValues.push(['PLATFORM (NAVIGATOR)', window.navigator.platform]); pNamesAndValues.push(['HARDWARE_CONCURRENCY (NAVIGATOR)', window.navigator.appCodeName]); pNamesAndValues.push(['VENDOR (NAVIGATOR)', window.navigator.vendor]); pNamesAndValues.push(['VENDOR_SUB (NAVIGATOR)', window.navigator.vendorSub]); /* Max and min queries - context limitations. */ pNamesAndValues.push(['MAX_COMBINED_TEXTURE_IMAGE_UNITS', this.param(context.MAX_COMBINED_TEXTURE_IMAGE_UNITS)]); pNamesAndValues.push(['MAX_CUBE_MAP_TEXTURE_SIZE', this.param(context.MAX_CUBE_MAP_TEXTURE_SIZE)]); pNamesAndValues.push(['MAX_FRAGMENT_UNIFORM_VECTORS', this.param(context.MAX_FRAGMENT_UNIFORM_VECTORS)]); pNamesAndValues.push(['MAX_RENDERBUFFER_SIZE', this.param(context.MAX_RENDERBUFFER_SIZE)]); pNamesAndValues.push(['MAX_TEXTURE_IMAGE_UNITS', this.param(context.MAX_TEXTURE_IMAGE_UNITS)]); pNamesAndValues.push(['MAX_TEXTURE_SIZE', this.param(context.MAX_TEXTURE_SIZE)]); pNamesAndValues.push(['MAX_VARYING_VECTORS', this.param(context.MAX_VARYING_VECTORS)]); pNamesAndValues.push(['MAX_VERTEX_ATTRIBS', this.param(context.MAX_VERTEX_ATTRIBS)]); pNamesAndValues.push(['MAX_VERTEX_TEXTURE_IMAGE_UNITS', this.param(context.MAX_VERTEX_TEXTURE_IMAGE_UNITS)]); pNamesAndValues.push(['MAX_VERTEX_UNIFORM_VECTORS', this.param(context.MAX_VERTEX_UNIFORM_VECTORS)]); const MAX_VIEWPORT_DIMS = this.param(context.MAX_VIEWPORT_DIMS); pNamesAndValues.push(['MAX_VIEWPORT_DIMS (WIDTH)', MAX_VIEWPORT_DIMS ? MAX_VIEWPORT_DIMS[0] : null]); pNamesAndValues.push(['MAX_VIEWPORT_DIMS (HEIGHT)', MAX_VIEWPORT_DIMS ? MAX_VIEWPORT_DIMS[1] : null]); if (this.isWebGL2) { const context = this._context as WebGL2RenderingContext; pNamesAndValues.push(['MAX_3D_TEXTURE_SIZE', this.param(context.MAX_3D_TEXTURE_SIZE)]); pNamesAndValues.push(['MAX_ARRAY_TEXTURE_LAYERS', this.param(context.MAX_ARRAY_TEXTURE_LAYERS)]); pNamesAndValues.push(['MAX_CLIENT_WAIT_TIMEOUT_WEBGL', this.param(context.MAX_CLIENT_WAIT_TIMEOUT_WEBGL)]); pNamesAndValues.push(['MAX_COLOR_ATTACHMENTS', this.param(context.MAX_COLOR_ATTACHMENTS)]); pNamesAndValues.push(['MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS', this.param(context.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS)]); pNamesAndValues.push(['MAX_COMBINED_UNIFORM_BLOCKS', this.param(context.MAX_COMBINED_UNIFORM_BLOCKS)]); pNamesAndValues.push(['MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS', this.param(context.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS)]); pNamesAndValues.push(['MAX_DRAW_BUFFERS', this.param(context.MAX_DRAW_BUFFERS)]); pNamesAndValues.push(['MAX_ELEMENT_INDEX', this.param(context.MAX_ELEMENT_INDEX)]); pNamesAndValues.push(['MAX_ELEMENTS_INDICES', this.param(context.MAX_ELEMENTS_INDICES)]); pNamesAndValues.push(['MAX_ELEMENTS_VERTICES', this.param(context.MAX_ELEMENTS_VERTICES)]); pNamesAndValues.push(['MAX_FRAGMENT_INPUT_COMPONENTS', this.param(context.MAX_FRAGMENT_INPUT_COMPONENTS)]); pNamesAndValues.push(['MAX_FRAGMENT_UNIFORM_BLOCKS', this.param(context.MAX_FRAGMENT_UNIFORM_BLOCKS)]); pNamesAndValues.push(['MAX_FRAGMENT_UNIFORM_COMPONENTS', this.param(context.MAX_FRAGMENT_UNIFORM_COMPONENTS)]); pNamesAndValues.push(['MAX_PROGRAM_TEXEL_OFFSET', this.param(context.MAX_PROGRAM_TEXEL_OFFSET)]); pNamesAndValues.push(['MAX_SAMPLES', this.param(context.MAX_SAMPLES)]); pNamesAndValues.push(['MAX_SERVER_WAIT_TIMEOUT', this.param(context.MAX_SERVER_WAIT_TIMEOUT)]); pNamesAndValues.push(['MAX_TEXTURE_LOD_BIAS', this.param(context.MAX_TEXTURE_LOD_BIAS)]); pNamesAndValues.push(['MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS', this.param(context.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS)]); pNamesAndValues.push(['MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS', this.param(context.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS)]); pNamesAndValues.push(['MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS', this.param(context.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS)]); pNamesAndValues.push(['MAX_UNIFORM_BLOCK_SIZE', this.param(context.MAX_UNIFORM_BLOCK_SIZE)]); pNamesAndValues.push(['MAX_UNIFORM_BUFFER_BINDINGS', this.param(context.MAX_UNIFORM_BUFFER_BINDINGS)]); pNamesAndValues.push(['MAX_VARYING_COMPONENTS', this.param(context.MAX_VARYING_COMPONENTS)]); pNamesAndValues.push(['MAX_VERTEX_OUTPUT_COMPONENTS', this.param(context.MAX_VERTEX_OUTPUT_COMPONENTS)]); pNamesAndValues.push(['MAX_VERTEX_UNIFORM_BLOCKS', this.param(context.MAX_VERTEX_UNIFORM_BLOCKS)]); pNamesAndValues.push(['MAX_VERTEX_UNIFORM_COMPONENTS', this.param(context.MAX_VERTEX_UNIFORM_COMPONENTS)]); pNamesAndValues.push(['MIN_PROGRAM_TEXEL_OFFSET', this.param(context.MIN_PROGRAM_TEXEL_OFFSET)]); } if (this.isWebGL1) { for (const extension of WEBGL1_EXTENSIONS) { pNamesAndValues.push([extension, this.supports(extension) ? available : unavailable]); } } else if (this.isWebGL2) { for (const extension of WEBGL2_DEFAULT_EXTENSIONS) { pNamesAndValues.push([`${extension} (default)`, available]); } for (const extension of WEBGL2_EXTENSIONS) { pNamesAndValues.push([extension, this.supports(extension) ? available : unavailable]); } } return pNamesAndValues; } /** * Creates a well formated about string, e.g., for logging. */ aboutString(): string { const about = this.about(); let maxPNameLength = 0; for (const tuple of about) { maxPNameLength = Math.max(tuple[0].length, maxPNameLength); } let index = 0; let message = ``; const extensionSeparator = this.isWebGL2 ? 63 + WEBGL2_DEFAULT_EXTENSIONS.length : -1; for (const tuple of about) { /* Provide some semantic grouping: Core, Limits, Extensions, ... */ switch (index) { case 2: // End of Backend and Context Hash case 6: // End of Core Context Info case 8: // End of unmasked vendor and renderer case 15: // End of context attributes case 16: // End of window attributes case 23: // End of navigator attributes case 35: // End of WebGL 1 specific Limits case 63: // End of WebGL 2 specific Limit, start of extensions case extensionSeparator: // End of default Extensions (in case of WebGL2) or -1 message += `\n`; break; default: break; } message += ` ${tuple[0]} ${'-'.repeat(maxPNameLength - tuple[0].length)}-- ${tuple[1]}\n`; ++index; } message += `\n`; return message; } /** * Logs a well formated list of all queried about params (names and associated values). * @param verbosity - Log verbosity that is to be used for logging. */ logAbout(verbosity: LogLevel = LogLevel.Info): void { log(verbosity, `context.about\n\n` + this.aboutString()); } /** * Invokes `logAbout` @see{@link logAbout}) iff the given statement has resolved to true. * @param statement - Result of an expression expected to be true in order to invoke logPerformanceStop. * @param verbosity - Log verbosity that is to be used for logging. */ logAboutIf(statement: boolean, verbosity: LogLevel = LogLevel.Info): void { logIf(statement, verbosity, `context.about\n\n` + this.aboutString()); } // CONTEXT-RELATED AUXILIARIES /** * Provides the size in bytes of certain WebGL format enumerator. Please note that some byte sizes might vary based * on context attributes or the bound render, thus, DEPTH_COMPONENT and DEPTH_STENCIL are not covered by this * function. @see {@link byteSizeOfFormat} */ byteSizeOfFormat(format: GLenum): number { return byteSizeOfFormat(this, format); } } export namespace Context { /** * Supported OpenGL backend types. */ export enum BackendType { Invalid = 'invalid', WebGL1 = 'webgl1', WebGL2 = 'webgl2', } /** * The list of valid backend identifiers that can be requested and matched to backend types. * List adopted from https://developer.mozilla.org/de/docs/Web/API/HTMLCanvasElement/getContext. */ export enum BackendRequestType { auto = 'auto', webgl = 'webgl', experimental = 'experimental-webgl', webgl1 = 'webgl1', experimental1 = 'experimental-webgl1', webgl2 = 'webgl2', experimental2 = 'experimental-webgl2', } }
the_stack
import * as firestore from '@google-cloud/firestore'; import {CallOptions} from 'google-gax'; import {Duplex, PassThrough, Transform} from 'stream'; import {URL} from 'url'; import {google} from '../protos/firestore_v1_proto_api'; import {ExponentialBackoff, ExponentialBackoffSetting} from './backoff'; import {BulkWriter} from './bulk-writer'; import {BundleBuilder} from './bundle'; import {fieldsFromJson, timestampFromJson} from './convert'; import {DocumentReader} from './document-reader'; import { DocumentSnapshot, DocumentSnapshotBuilder, QueryDocumentSnapshot, } from './document'; import {logger, setLibVersion} from './logger'; import { DEFAULT_DATABASE_ID, QualifiedResourcePath, ResourcePath, validateResourcePath, } from './path'; import {ClientPool} from './pool'; import {CollectionReference, DocumentReference} from './reference'; import {Serializer} from './serializer'; import {Timestamp} from './timestamp'; import {parseGetAllArguments, Transaction} from './transaction'; import { ApiMapValue, FirestoreStreamingMethod, FirestoreUnaryMethod, GapicClient, UnaryMethod, } from './types'; import { autoId, Deferred, getRetryParams, isPermanentRpcError, requestTag, wrapError, } from './util'; import { validateBoolean, validateFunction, validateHost, validateInteger, validateMinNumberOfArguments, validateObject, validateString, validateTimestamp, } from './validate'; import {WriteBatch} from './write-batch'; import {interfaces} from './v1/firestore_client_config.json'; const serviceConfig = interfaces['google.firestore.v1.Firestore']; import api = google.firestore.v1; import {CollectionGroup} from './collection-group'; import { RECURSIVE_DELETE_MAX_PENDING_OPS, RECURSIVE_DELETE_MIN_PENDING_OPS, RecursiveDelete, } from './recursive-delete'; export { CollectionReference, DocumentReference, QuerySnapshot, Query, } from './reference'; export {BulkWriter} from './bulk-writer'; export {DocumentSnapshot, QueryDocumentSnapshot} from './document'; export {FieldValue} from './field-value'; export {WriteBatch, WriteResult} from './write-batch'; export {Transaction} from './transaction'; export {Timestamp} from './timestamp'; export {DocumentChange} from './document-change'; export {FieldPath} from './path'; export {GeoPoint} from './geo-point'; export {CollectionGroup}; export {QueryPartition} from './query-partition'; export {setLogFunction} from './logger'; const libVersion = require('../../package.json').version; setLibVersion(libVersion); /*! * DO NOT REMOVE THE FOLLOWING NAMESPACE DEFINITIONS */ /** * @namespace google.protobuf */ /** * @namespace google.rpc */ /** * @namespace google.longrunning */ /** * @namespace google.firestore.v1 */ /** * @namespace google.firestore.v1beta1 */ /** * @namespace google.firestore.admin.v1 */ /*! * HTTP header for the resource prefix to improve routing and project isolation * by the backend. */ const CLOUD_RESOURCE_HEADER = 'google-cloud-resource-prefix'; /*! * The maximum number of times to retry idempotent requests. */ export const MAX_REQUEST_RETRIES = 5; /*! * The maximum number of times to attempt a transaction before failing. */ export const DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; /*! * The default number of idle GRPC channel to keep. */ const DEFAULT_MAX_IDLE_CHANNELS = 1; /*! * The maximum number of concurrent requests supported by a single GRPC channel, * as enforced by Google's Frontend. If the SDK issues more than 100 concurrent * operations, we need to use more than one GAPIC client since these clients * multiplex all requests over a single channel. */ const MAX_CONCURRENT_REQUESTS_PER_CLIENT = 100; /** * Document data (e.g. for use with * [set()]{@link DocumentReference#set}) consisting of fields mapped * to values. * * @typedef {Object.<string, *>} DocumentData */ /** * Converter used by [withConverter()]{@link Query#withConverter} to transform * user objects of type T into Firestore data. * * Using the converter allows you to specify generic type arguments when storing * and retrieving objects from Firestore. * * @example * ``` * class Post { * constructor(readonly title: string, readonly author: string) {} * * toString(): string { * return this.title + ', by ' + this.author; * } * } * * const postConverter = { * toFirestore(post: Post): FirebaseFirestore.DocumentData { * return {title: post.title, author: post.author}; * }, * fromFirestore( * snapshot: FirebaseFirestore.QueryDocumentSnapshot * ): Post { * const data = snapshot.data(); * return new Post(data.title, data.author); * } * }; * * const postSnap = await Firestore() * .collection('posts') * .withConverter(postConverter) * .doc().get(); * const post = postSnap.data(); * if (post !== undefined) { * post.title; // string * post.toString(); // Should be defined * post.someNonExistentProperty; // TS error * } * * ``` * @property {Function} toFirestore Called by the Firestore SDK to convert a * custom model object of type T into a plain Javascript object (suitable for * writing directly to the Firestore database). * @property {Function} fromFirestore Called by the Firestore SDK to convert * Firestore data into an object of type T. * @typedef {Object} FirestoreDataConverter */ /** * Update data (for use with [update]{@link DocumentReference#update}) * that contains paths mapped to values. Fields that contain dots * reference nested fields within the document. * * You can update a top-level field in your document by using the field name * as a key (e.g. `foo`). The provided value completely replaces the contents * for this field. * * You can also update a nested field directly by using its field path as a key * (e.g. `foo.bar`). This nested field update replaces the contents at `bar` * but does not modify other data under `foo`. * * @example * ``` * const documentRef = firestore.doc('coll/doc'); * documentRef.set({a1: {a2: 'val'}, b1: {b2: 'val'}, c1: {c2: 'val'}}); * documentRef.update({ * b1: {b3: 'val'}, * 'c1.c3': 'val', * }); * // Value is {a1: {a2: 'val'}, b1: {b3: 'val'}, c1: {c2: 'val', c3: 'val'}} * * ``` * @typedef {Object.<string, *>} UpdateData */ /** * An options object that configures conditional behavior of * [update()]{@link DocumentReference#update} and * [delete()]{@link DocumentReference#delete} calls in * [DocumentReference]{@link DocumentReference}, * [WriteBatch]{@link WriteBatch}, [BulkWriter]{@link BulkWriter}, and * [Transaction]{@link Transaction}. Using Preconditions, these calls * can be restricted to only apply to documents that match the specified * conditions. * * @example * ``` * const documentRef = firestore.doc('coll/doc'); * * documentRef.get().then(snapshot => { * const updateTime = snapshot.updateTime; * * console.log(`Deleting document at update time: ${updateTime.toDate()}`); * return documentRef.delete({ lastUpdateTime: updateTime }); * }); * * ``` * @property {Timestamp} lastUpdateTime The update time to enforce. If set, * enforces that the document was last updated at lastUpdateTime. Fails the * operation if the document was last updated at a different time. * @property {boolean} exists If set, enforces that the target document must * or must not exist. * @typedef {Object} Precondition */ /** * An options object that configures the behavior of * [set()]{@link DocumentReference#set} calls in * [DocumentReference]{@link DocumentReference}, * [WriteBatch]{@link WriteBatch}, and * [Transaction]{@link Transaction}. These calls can be * configured to perform granular merges instead of overwriting the target * documents in their entirety by providing a SetOptions object with * { merge : true }. * * @property {boolean} merge Changes the behavior of a set() call to only * replace the values specified in its data argument. Fields omitted from the * set() call remain untouched. * @property {Array<(string|FieldPath)>} mergeFields Changes the behavior of * set() calls to only replace the specified field paths. Any field path that is * not specified is ignored and remains untouched. * It is an error to pass a SetOptions object to a set() call that is missing a * value for any of the fields specified here. * @typedef {Object} SetOptions */ /** * An options object that can be used to configure the behavior of * [getAll()]{@link Firestore#getAll} calls. By providing a `fieldMask`, these * calls can be configured to only return a subset of fields. * * @property {Array<(string|FieldPath)>} fieldMask Specifies the set of fields * to return and reduces the amount of data transmitted by the backend. * Adding a field mask does not filter results. Documents do not need to * contain values for all the fields in the mask to be part of the result set. * @typedef {Object} ReadOptions */ /** * An options object to configure throttling on BulkWriter. * * Whether to disable or configure throttling. By default, throttling is * enabled. `throttling` can be set to either a boolean or a config object. * Setting it to `true` will use default values. You can override the defaults * by setting it to `false` to disable throttling, or by setting the config * values to enable throttling with the provided values. * * @property {boolean|Object} throttling Whether to disable or enable * throttling. Throttling is enabled by default, if the field is set to `true` * or if any custom throttling options are provided. `{ initialOpsPerSecond: * number }` sets the initial maximum number of operations per second allowed by * the throttler. If `initialOpsPerSecond` is not set, the default is 500 * operations per second. `{ maxOpsPerSecond: number }` sets the maximum number * of operations per second allowed by the throttler. If `maxOpsPerSecond` is * not set, no maximum is enforced. * @typedef {Object} BulkWriterOptions */ /** * An error thrown when a BulkWriter operation fails. * * The error used by {@link BulkWriter~shouldRetryCallback} set in * {@link BulkWriter#onWriteError}. * * @property {GrpcStatus} code The status code of the error. * @property {string} message The error message of the error. * @property {DocumentReference} documentRef The document reference the operation was * performed on. * @property {'create' | 'set' | 'update' | 'delete'} operationType The type * of operation performed. * @property {number} failedAttempts How many times this operation has been * attempted unsuccessfully. * @typedef {Error} BulkWriterError */ /** * Status codes returned by GRPC operations. * * @see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md * * @enum {number} * @typedef {Object} GrpcStatus */ /** * The Firestore client represents a Firestore Database and is the entry point * for all Firestore operations. * * @see [Firestore Documentation]{@link https://firebase.google.com/docs/firestore/} * * @class * * @example Install the client library with <a href="https://www.npmjs.com/">npm</a>: * ``` * npm install --save @google-cloud/firestore * * ``` * @example Import the client library * ``` * var Firestore = require('@google-cloud/firestore'); * * ``` * @example Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>: * ``` * var firestore = new Firestore(); * * ``` * @example Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>: * ``` * var firestore = new Firestore({ projectId: * 'your-project-id', keyFilename: '/path/to/keyfile.json' * }); * * ``` * @example <caption>include:samples/quickstart.js</caption> * region_tag:firestore_quickstart * Full quickstart example: */ export class Firestore implements firestore.Firestore { /** * A client pool to distribute requests over multiple GAPIC clients in order * to work around a connection limit of 100 concurrent requests per client. * @private * @internal */ private _clientPool: ClientPool<GapicClient>; /** * The configuration options for the GAPIC client. * @private * @internal */ _settings: firestore.Settings = {}; /** * Settings for the exponential backoff used by the streaming endpoints. * @private * @internal */ private _backoffSettings: ExponentialBackoffSetting; /** * Whether the initialization settings can still be changed by invoking * `settings()`. * @private * @internal */ private _settingsFrozen = false; /** * The serializer to use for the Protobuf transformation. * @private * @internal */ _serializer: Serializer | null = null; /** * The project ID for this client. * * The project ID is auto-detected during the first request unless a project * ID is passed to the constructor (or provided via `.settings()`). * @private * @internal */ private _projectId: string | undefined = undefined; /** * Count of listeners that have been registered on the client. * * The client can only be terminated when there are no pending writes or * registered listeners. * @private * @internal */ private registeredListenersCount = 0; /** * A lazy-loaded BulkWriter instance to be used with recursiveDelete() if no * BulkWriter instance is provided. * * @private * @internal */ private _bulkWriter: BulkWriter | undefined; /** * Lazy-load the Firestore's default BulkWriter. * * @private * @internal */ private getBulkWriter(): BulkWriter { if (!this._bulkWriter) { this._bulkWriter = this.bulkWriter(); } return this._bulkWriter; } /** * Number of pending operations on the client. * * The client can only be terminated when there are no pending writes or * registered listeners. * @private * @internal */ private bulkWritersCount = 0; /** * @param {Object=} settings [Configuration object](#/docs). * @param {string=} settings.projectId The project ID from the Google * Developer's Console, e.g. 'grape-spaceship-123'. We will also check the * environment variable GCLOUD_PROJECT for your project ID. Can be omitted in * environments that support * {@link https://cloud.google.com/docs/authentication Application Default * Credentials} * @param {string=} settings.keyFilename Local file containing the Service * Account credentials as downloaded from the Google Developers Console. Can * be omitted in environments that support * {@link https://cloud.google.com/docs/authentication Application Default * Credentials}. To configure Firestore with custom credentials, use * `settings.credentials` and provide the `client_email` and `private_key` of * your service account. * @param {{client_email:string=, private_key:string=}=} settings.credentials * The `client_email` and `private_key` properties of the service account * to use with your Firestore project. Can be omitted in environments that * support {@link https://cloud.google.com/docs/authentication Application * Default Credentials}. If your credentials are stored in a JSON file, you * can specify a `keyFilename` instead. * @param {string=} settings.host The host to connect to. * @param {boolean=} settings.ssl Whether to use SSL when connecting. * @param {number=} settings.maxIdleChannels The maximum number of idle GRPC * channels to keep. A smaller number of idle channels reduces memory usage * but increases request latency for clients with fluctuating request rates. * If set to 0, shuts down all GRPC channels when the client becomes idle. * Defaults to 1. * @param {boolean=} settings.ignoreUndefinedProperties Whether to skip nested * properties that are set to `undefined` during object serialization. If set * to `true`, these properties are skipped and not written to Firestore. If * set `false` or omitted, the SDK throws an exception when it encounters * properties of type `undefined`. */ constructor(settings?: firestore.Settings) { const libraryHeader = { libName: 'gccl', libVersion, }; if (settings && settings.firebaseVersion) { libraryHeader.libVersion += ' fire/' + settings.firebaseVersion; } this.validateAndApplySettings({...settings, ...libraryHeader}); const retryConfig = serviceConfig.retry_params.default; this._backoffSettings = { initialDelayMs: retryConfig.initial_retry_delay_millis, maxDelayMs: retryConfig.max_retry_delay_millis, backoffFactor: retryConfig.retry_delay_multiplier, }; const maxIdleChannels = this._settings.maxIdleChannels === undefined ? DEFAULT_MAX_IDLE_CHANNELS : this._settings.maxIdleChannels; this._clientPool = new ClientPool<GapicClient>( MAX_CONCURRENT_REQUESTS_PER_CLIENT, maxIdleChannels, /* clientFactory= */ () => { let client: GapicClient; if (this._settings.ssl === false) { const grpcModule = this._settings.grpc ?? require('google-gax').grpc; const sslCreds = grpcModule.credentials.createInsecure(); client = new module.exports.v1({ sslCreds, ...this._settings, }); } else { client = new module.exports.v1(this._settings); } logger('Firestore', null, 'Initialized Firestore GAPIC Client'); return client; }, /* clientDestructor= */ client => client.close() ); logger('Firestore', null, 'Initialized Firestore'); } /** * Specifies custom settings to be used to configure the `Firestore` * instance. Can only be invoked once and before any other Firestore method. * * If settings are provided via both `settings()` and the `Firestore` * constructor, both settings objects are merged and any settings provided via * `settings()` take precedence. * * @param {object} settings The settings to use for all Firestore operations. */ settings(settings: firestore.Settings): void { validateObject('settings', settings); validateString('settings.projectId', settings.projectId, {optional: true}); if (this._settingsFrozen) { throw new Error( 'Firestore has already been initialized. You can only call ' + 'settings() once, and only before calling any other methods on a ' + 'Firestore object.' ); } const mergedSettings = {...this._settings, ...settings}; this.validateAndApplySettings(mergedSettings); this._settingsFrozen = true; } private validateAndApplySettings(settings: firestore.Settings): void { if (settings.projectId !== undefined) { validateString('settings.projectId', settings.projectId); this._projectId = settings.projectId; } let url: URL | null = null; // If the environment variable is set, it should always take precedence // over any user passed in settings. if (process.env.FIRESTORE_EMULATOR_HOST) { validateHost( 'FIRESTORE_EMULATOR_HOST', process.env.FIRESTORE_EMULATOR_HOST ); settings = { ...settings, host: process.env.FIRESTORE_EMULATOR_HOST, ssl: false, }; url = new URL(`http://${settings.host}`); } else if (settings.host !== undefined) { validateHost('settings.host', settings.host); url = new URL(`http://${settings.host}`); } // Only store the host if a valid value was provided in `host`. if (url !== null) { if ( (settings.servicePath !== undefined && settings.servicePath !== url.hostname) || (settings.apiEndpoint !== undefined && settings.apiEndpoint !== url.hostname) ) { // eslint-disable-next-line no-console console.warn( `The provided host (${url.hostname}) in "settings" does not ` + `match the existing host (${ settings.servicePath ?? settings.apiEndpoint }). Using the provided host.` ); } settings.servicePath = url.hostname; if (url.port !== '' && settings.port === undefined) { settings.port = Number(url.port); } // We need to remove the `host` and `apiEndpoint` setting, in case a user // calls `settings()`, which will compare the the provided `host` to the // existing hostname stored on `servicePath`. delete settings.host; delete settings.apiEndpoint; } if (settings.ssl !== undefined) { validateBoolean('settings.ssl', settings.ssl); } if (settings.maxIdleChannels !== undefined) { validateInteger('settings.maxIdleChannels', settings.maxIdleChannels, { minValue: 0, }); } this._settings = settings; this._serializer = new Serializer(this); } /** * Returns the Project ID for this Firestore instance. Validates that * `initializeIfNeeded()` was called before. * * @private * @internal */ get projectId(): string { if (this._projectId === undefined) { throw new Error( 'INTERNAL ERROR: Client is not yet ready to issue requests.' ); } return this._projectId; } /** * Returns the root path of the database. Validates that * `initializeIfNeeded()` was called before. * * @private * @internal */ get formattedName(): string { return `projects/${this.projectId}/databases/${DEFAULT_DATABASE_ID}`; } /** * Gets a [DocumentReference]{@link DocumentReference} instance that * refers to the document at the specified path. * * @param {string} documentPath A slash-separated path to a document. * @returns {DocumentReference} The * [DocumentReference]{@link DocumentReference} instance. * * @example * ``` * let documentRef = firestore.doc('collection/document'); * console.log(`Path of document is ${documentRef.path}`); * ``` */ doc(documentPath: string): DocumentReference { validateResourcePath('documentPath', documentPath); const path = ResourcePath.EMPTY.append(documentPath); if (!path.isDocument) { throw new Error( `Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.` ); } return new DocumentReference(this, path); } /** * Gets a [CollectionReference]{@link CollectionReference} instance * that refers to the collection at the specified path. * * @param {string} collectionPath A slash-separated path to a collection. * @returns {CollectionReference} The * [CollectionReference]{@link CollectionReference} instance. * * @example * ``` * let collectionRef = firestore.collection('collection'); * * // Add a document with an auto-generated ID. * collectionRef.add({foo: 'bar'}).then((documentRef) => { * console.log(`Added document at ${documentRef.path})`); * }); * ``` */ collection(collectionPath: string): CollectionReference { validateResourcePath('collectionPath', collectionPath); const path = ResourcePath.EMPTY.append(collectionPath); if (!path.isCollection) { throw new Error( `Value for argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.` ); } return new CollectionReference(this, path); } /** * Creates and returns a new Query that includes all documents in the * database that are contained in a collection or subcollection with the * given collectionId. * * @param {string} collectionId Identifies the collections to query over. * Every collection or subcollection with this ID as the last segment of its * path will be included. Cannot contain a slash. * @returns {CollectionGroup} The created CollectionGroup. * * @example * ``` * let docA = firestore.doc('mygroup/docA').set({foo: 'bar'}); * let docB = firestore.doc('abc/def/mygroup/docB').set({foo: 'bar'}); * * Promise.all([docA, docB]).then(() => { * let query = firestore.collectionGroup('mygroup'); * query = query.where('foo', '==', 'bar'); * return query.get().then(snapshot => { * console.log(`Found ${snapshot.size} documents.`); * }); * }); * ``` */ collectionGroup(collectionId: string): CollectionGroup { if (collectionId.indexOf('/') !== -1) { throw new Error( `Invalid collectionId '${collectionId}'. Collection IDs must not contain '/'.` ); } return new CollectionGroup(this, collectionId, /* converter= */ undefined); } /** * Creates a [WriteBatch]{@link WriteBatch}, used for performing * multiple writes as a single atomic operation. * * @returns {WriteBatch} A WriteBatch that operates on this Firestore * client. * * @example * ``` * let writeBatch = firestore.batch(); * * // Add two documents in an atomic batch. * let data = { foo: 'bar' }; * writeBatch.set(firestore.doc('col/doc1'), data); * writeBatch.set(firestore.doc('col/doc2'), data); * * writeBatch.commit().then(res => { * console.log('Successfully executed batch.'); * }); * ``` */ batch(): WriteBatch { return new WriteBatch(this); } /** * Creates a [BulkWriter]{@link BulkWriter}, used for performing * multiple writes in parallel. Gradually ramps up writes as specified * by the 500/50/5 rule. * * If you pass [BulkWriterOptions]{@link BulkWriterOptions}, you can * configure the throttling rates for the created BulkWriter. * * @see [500/50/5 Documentation]{@link https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic} * * @param {BulkWriterOptions=} options BulkWriter options. * @returns {BulkWriter} A BulkWriter that operates on this Firestore * client. * * @example * ``` * let bulkWriter = firestore.bulkWriter(); * * bulkWriter.create(firestore.doc('col/doc1'), {foo: 'bar'}) * .then(res => { * console.log(`Added document at ${res.writeTime}`); * }); * bulkWriter.update(firestore.doc('col/doc2'), {foo: 'bar'}) * .then(res => { * console.log(`Updated document at ${res.writeTime}`); * }); * bulkWriter.delete(firestore.doc('col/doc3')) * .then(res => { * console.log(`Deleted document at ${res.writeTime}`); * }); * await bulkWriter.close().then(() => { * console.log('Executed all writes'); * }); * ``` */ bulkWriter(options?: firestore.BulkWriterOptions): BulkWriter { return new BulkWriter(this, options); } /** * Creates a [DocumentSnapshot]{@link DocumentSnapshot} or a * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} from a * `firestore.v1.Document` proto (or from a resource name for missing * documents). * * This API is used by Google Cloud Functions and can be called with both * 'Proto3 JSON' and 'Protobuf JS' encoded data. * * @private * @internal * @param documentOrName The Firestore 'Document' proto or the resource name * of a missing document. * @param readTime A 'Timestamp' proto indicating the time this document was * read. * @param encoding One of 'json' or 'protobufJS'. Applies to both the * 'document' Proto and 'readTime'. Defaults to 'protobufJS'. * @returns A QueryDocumentSnapshot for existing documents, otherwise a * DocumentSnapshot. */ snapshot_( documentName: string, readTime?: google.protobuf.ITimestamp, encoding?: 'protobufJS' ): DocumentSnapshot; snapshot_( documentName: string, readTime: string, encoding: 'json' ): DocumentSnapshot; snapshot_( document: api.IDocument, readTime: google.protobuf.ITimestamp, encoding?: 'protobufJS' ): QueryDocumentSnapshot; snapshot_( document: {[k: string]: unknown}, readTime: string, encoding: 'json' ): QueryDocumentSnapshot; snapshot_( documentOrName: api.IDocument | {[k: string]: unknown} | string, readTime?: google.protobuf.ITimestamp | string, encoding?: 'json' | 'protobufJS' ): DocumentSnapshot { // TODO: Assert that Firestore Project ID is valid. let convertTimestamp: ( timestampValue?: string | google.protobuf.ITimestamp, argumentName?: string ) => google.protobuf.ITimestamp | undefined; let convertFields: (data: ApiMapValue) => ApiMapValue; if (encoding === undefined || encoding === 'protobufJS') { convertTimestamp = data => data as google.protobuf.ITimestamp; convertFields = data => data; } else if (encoding === 'json') { // Google Cloud Functions calls us with Proto3 JSON format data, which we // must convert to Protobuf JS. convertTimestamp = timestampFromJson; convertFields = fieldsFromJson; } else { throw new Error( 'Unsupported encoding format. Expected "json" or "protobufJS", ' + `but was "${encoding}".` ); } let ref: DocumentReference; let document: DocumentSnapshotBuilder; if (typeof documentOrName === 'string') { ref = new DocumentReference( this, QualifiedResourcePath.fromSlashSeparatedString(documentOrName) ); document = new DocumentSnapshotBuilder(ref); } else { ref = new DocumentReference( this, QualifiedResourcePath.fromSlashSeparatedString( documentOrName.name as string ) ); document = new DocumentSnapshotBuilder(ref); document.fieldsProto = documentOrName.fields ? convertFields(documentOrName.fields as ApiMapValue) : {}; document.createTime = Timestamp.fromProto( convertTimestamp( documentOrName.createTime as string | google.protobuf.ITimestamp, 'documentOrName.createTime' )! ); document.updateTime = Timestamp.fromProto( convertTimestamp( documentOrName.updateTime as string | google.protobuf.ITimestamp, 'documentOrName.updateTime' )! ); } if (readTime) { document.readTime = Timestamp.fromProto( convertTimestamp(readTime, 'readTime')! ); } return document.build(); } /** * Creates a new `BundleBuilder` instance to package selected Firestore data into * a bundle. * * @param bundleId. The id of the bundle. When loaded on clients, client SDKs use this id * and the timestamp associated with the built bundle to tell if it has been loaded already. * If not specified, a random identifier will be used. */ bundle(name?: string): BundleBuilder { return new BundleBuilder(name || autoId()); } /** * Function executed by {@link Firestore#runTransaction} within the transaction * context. * * @callback Firestore~updateFunction * @template T * @param {Transaction} transaction The transaction object for this * transaction. * @returns {Promise<T>} The promise returned at the end of the transaction. * This promise will be returned by {@link Firestore#runTransaction} if the * transaction completed successfully. */ /** * Options object for {@link Firestore#runTransaction} to configure a * read-only transaction. * * @callback Firestore~ReadOnlyTransactionOptions * @template T * @param {true} readOnly Set to true to indicate a read-only transaction. * @param {Timestamp=} readTime If specified, documents are read at the given * time. This may not be more than 60 seconds in the past from when the * request is processed by the server. */ /** * Options object for {@link Firestore#runTransaction} to configure a * read-write transaction. * * @callback Firestore~ReadWriteTransactionOptions * @template T * @param {false=} readOnly Set to false or omit to indicate a read-write * transaction. * @param {number=} maxAttempts The maximum number of attempts for this * transaction. Defaults to five. */ /** * Executes the given updateFunction and commits the changes applied within * the transaction. * * You can use the transaction object passed to 'updateFunction' to read and * modify Firestore documents under lock. You have to perform all reads before * before you perform any write. * * Transactions can be performed as read-only or read-write transactions. By * default, transactions are executed in read-write mode. * * A read-write transaction obtains a pessimistic lock on all documents that * are read during the transaction. These locks block other transactions, * batched writes, and other non-transactional writes from changing that * document. Any writes in a read-write transactions are committed once * 'updateFunction' resolves, which also releases all locks. * * If a read-write transaction fails with contention, the transaction is * retried up to five times. The `updateFunction` is invoked once for each * attempt. * * Read-only transactions do not lock documents. They can be used to read * documents at a consistent snapshot in time, which may be up to 60 seconds * in the past. Read-only transactions are not retried. * * Transactions time out after 60 seconds if no documents are read. * Transactions that are not committed within than 270 seconds are also * aborted. Any remaining locks are released when a transaction times out. * * @template T * @param {Firestore~updateFunction} updateFunction The user function to * execute within the transaction context. * @param { * Firestore~ReadWriteTransactionOptions|Firestore~ReadOnlyTransactionOptions= * } transactionOptions Transaction options. * @returns {Promise<T>} If the transaction completed successfully or was * explicitly aborted (by the updateFunction returning a failed Promise), the * Promise returned by the updateFunction will be returned here. Else if the * transaction failed, a rejected Promise with the corresponding failure * error will be returned. * * @example * ``` * let counterTransaction = firestore.runTransaction(transaction => { * let documentRef = firestore.doc('col/doc'); * return transaction.get(documentRef).then(doc => { * if (doc.exists) { * let count = doc.get('count') || 0; * if (count > 10) { * return Promise.reject('Reached maximum count'); * } * transaction.update(documentRef, { count: ++count }); * return Promise.resolve(count); * } * * transaction.create(documentRef, { count: 1 }); * return Promise.resolve(1); * }); * }); * * counterTransaction.then(res => { * console.log(`Count updated to ${res}`); * }); * ``` */ runTransaction<T>( updateFunction: (transaction: Transaction) => Promise<T>, transactionOptions?: | firestore.ReadWriteTransactionOptions | firestore.ReadOnlyTransactionOptions ): Promise<T> { validateFunction('updateFunction', updateFunction); const tag = requestTag(); let maxAttempts = DEFAULT_MAX_TRANSACTION_ATTEMPTS; let readOnly = false; let readTime: Timestamp | undefined; if (transactionOptions) { validateObject('transactionOptions', transactionOptions); validateBoolean( 'transactionOptions.readOnly', transactionOptions.readOnly, {optional: true} ); if (transactionOptions.readOnly) { validateTimestamp( 'transactionOptions.readTime', transactionOptions.readTime, {optional: true} ); readOnly = true; readTime = transactionOptions.readTime as Timestamp | undefined; maxAttempts = 1; } else { validateInteger( 'transactionOptions.maxAttempts', transactionOptions.maxAttempts, {optional: true, minValue: 1} ); maxAttempts = transactionOptions.maxAttempts || DEFAULT_MAX_TRANSACTION_ATTEMPTS; } } const transaction = new Transaction(this, tag); return this.initializeIfNeeded(tag).then(() => transaction.runTransaction(updateFunction, { maxAttempts, readOnly, readTime, }) ); } /** * Fetches the root collections that are associated with this Firestore * database. * * @returns {Promise.<Array.<CollectionReference>>} A Promise that resolves * with an array of CollectionReferences. * * @example * ``` * firestore.listCollections().then(collections => { * for (let collection of collections) { * console.log(`Found collection with id: ${collection.id}`); * } * }); * ``` */ listCollections(): Promise<CollectionReference[]> { const rootDocument = new DocumentReference(this, ResourcePath.EMPTY); return rootDocument.listCollections(); } /** * Retrieves multiple documents from Firestore. * * The first argument is required and must be of type `DocumentReference` * followed by any additional `DocumentReference` documents. If used, the * optional `ReadOptions` must be the last argument. * * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The * `DocumentReferences` to receive, followed by an optional field mask. * @returns {Promise<Array.<DocumentSnapshot>>} A Promise that * contains an array with the resulting document snapshots. * * @example * ``` * let docRef1 = firestore.doc('col/doc1'); * let docRef2 = firestore.doc('col/doc2'); * * firestore.getAll(docRef1, docRef2, { fieldMask: ['user'] }).then(docs => { * console.log(`First document: ${JSON.stringify(docs[0])}`); * console.log(`Second document: ${JSON.stringify(docs[1])}`); * }); * ``` */ getAll<T>( ...documentRefsOrReadOptions: Array< firestore.DocumentReference<T> | firestore.ReadOptions > ): Promise<Array<DocumentSnapshot<T>>> { validateMinNumberOfArguments( 'Firestore.getAll', documentRefsOrReadOptions, 1 ); const {documents, fieldMask} = parseGetAllArguments( documentRefsOrReadOptions ); const tag = requestTag(); // Capture the error stack to preserve stack tracing across async calls. const stack = Error().stack!; return this.initializeIfNeeded(tag) .then(() => { const reader = new DocumentReader(this, documents); reader.fieldMask = fieldMask || undefined; return reader.get(tag); }) .catch(err => { throw wrapError(err, stack); }); } /** * Registers a listener on this client, incrementing the listener count. This * is used to verify that all listeners are unsubscribed when terminate() is * called. * * @private * @internal */ registerListener(): void { this.registeredListenersCount += 1; } /** * Unregisters a listener on this client, decrementing the listener count. * This is used to verify that all listeners are unsubscribed when terminate() * is called. * * @private * @internal */ unregisterListener(): void { this.registeredListenersCount -= 1; } /** * Increments the number of open BulkWriter instances. This is used to verify * that all pending operations are complete when terminate() is called. * * @private * @internal */ _incrementBulkWritersCount(): void { this.bulkWritersCount += 1; } /** * Decrements the number of open BulkWriter instances. This is used to verify * that all pending operations are complete when terminate() is called. * * @private * @internal */ _decrementBulkWritersCount(): void { this.bulkWritersCount -= 1; } /** * Recursively deletes all documents and subcollections at and under the * specified level. * * If any delete fails, the promise is rejected with an error message * containing the number of failed deletes and the stack trace of the last * failed delete. The provided reference is deleted regardless of whether * all deletes succeeded. * * `recursiveDelete()` uses a BulkWriter instance with default settings to * perform the deletes. To customize throttling rates or add success/error * callbacks, pass in a custom BulkWriter instance. * * @param ref The reference of a document or collection to delete. * @param bulkWriter A custom BulkWriter instance used to perform the * deletes. * @return A promise that resolves when all deletes have been performed. * The promise is rejected if any of the deletes fail. * * @example * ``` * // Recursively delete a reference and log the references of failures. * const bulkWriter = firestore.bulkWriter(); * bulkWriter * .onWriteError((error) => { * if ( * error.failedAttempts < MAX_RETRY_ATTEMPTS * ) { * return true; * } else { * console.log('Failed write at document: ', error.documentRef.path); * return false; * } * }); * await firestore.recursiveDelete(docRef, bulkWriter); * ``` */ recursiveDelete( ref: | firestore.CollectionReference<unknown> | firestore.DocumentReference<unknown>, bulkWriter?: BulkWriter ): Promise<void> { return this._recursiveDelete( ref, RECURSIVE_DELETE_MAX_PENDING_OPS, RECURSIVE_DELETE_MIN_PENDING_OPS, bulkWriter ); } /** * This overload is not private in order to test the query resumption with * startAfter() once the RecursiveDelete instance has MAX_PENDING_OPS pending. * * @private * @internal */ // Visible for testing _recursiveDelete( ref: | firestore.CollectionReference<unknown> | firestore.DocumentReference<unknown>, maxPendingOps: number, minPendingOps: number, bulkWriter?: BulkWriter ): Promise<void> { const writer = bulkWriter ?? this.getBulkWriter(); const deleter = new RecursiveDelete( this, writer, ref, maxPendingOps, minPendingOps ); return deleter.run(); } /** * Terminates the Firestore client and closes all open streams. * * @return A Promise that resolves when the client is terminated. */ terminate(): Promise<void> { if (this.registeredListenersCount > 0 || this.bulkWritersCount > 0) { return Promise.reject( 'All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' + 'instances must be closed before terminating the client. ' + `There are ${this.registeredListenersCount} active listeners and ` + `${this.bulkWritersCount} open BulkWriter instances.` ); } return this._clientPool.terminate(); } /** * Returns the Project ID to serve as the JSON representation of this * Firestore instance. * * @return An object that contains the project ID (or `undefined` if not yet * available). */ toJSON(): object { return {projectId: this._projectId}; } /** * Initializes the client if it is not already initialized. All methods in the * SDK can be used after this method completes. * * @private * @internal * @param requestTag A unique client-assigned identifier that caused this * initialization. * @return A Promise that resolves when the client is initialized. */ async initializeIfNeeded(requestTag: string): Promise<void> { this._settingsFrozen = true; if (this._settings.ssl === false) { // If SSL is false, we assume that we are talking to the emulator. We // provide an Authorization header by default so that the connection is // recognized as admin in Firestore Emulator. (If for some reason we're // not connecting to the emulator, then this will result in denials with // invalid token, rather than behave like clients not logged in. The user // can then provide their own Authorization header, which will take // precedence). this._settings.customHeaders = { Authorization: 'Bearer owner', ...this._settings.customHeaders, }; } if (this._projectId === undefined) { try { this._projectId = await this._clientPool.run(requestTag, gapicClient => gapicClient.getProjectId() ); logger( 'Firestore.initializeIfNeeded', null, 'Detected project ID: %s', this._projectId ); } catch (err) { logger( 'Firestore.initializeIfNeeded', null, 'Failed to detect project ID: %s', err ); return Promise.reject(err); } } } /** * Returns GAX call options that set the cloud resource header. * @private * @internal */ private createCallOptions( methodName: string, retryCodes?: number[] ): CallOptions { const callOptions: CallOptions = { otherArgs: { headers: { [CLOUD_RESOURCE_HEADER]: this.formattedName, ...this._settings.customHeaders, ...this._settings[methodName]?.customHeaders, }, }, }; if (retryCodes) { const retryParams = getRetryParams(methodName); callOptions.retry = new (require('google-gax').RetryOptions)( retryCodes, retryParams ); } return callOptions; } /** * A function returning a Promise that can be retried. * * @private * @internal * @callback retryFunction * @returns {Promise} A Promise indicating the function's success. */ /** * Helper method that retries failed Promises. * * If 'delayMs' is specified, waits 'delayMs' between invocations. Otherwise, * schedules the first attempt immediately, and then waits 100 milliseconds * for further attempts. * * @private * @internal * @param methodName Name of the Veneer API endpoint that takes a request * and GAX options. * @param requestTag A unique client-assigned identifier for this request. * @param func Method returning a Promise than can be retried. * @returns A Promise with the function's result if successful within * `attemptsRemaining`. Otherwise, returns the last rejected Promise. */ private async _retry<T>( methodName: string, requestTag: string, func: () => Promise<T> ): Promise<T> { const backoff = new ExponentialBackoff(); let lastError: Error | undefined = undefined; for (let attempt = 0; attempt < MAX_REQUEST_RETRIES; ++attempt) { if (lastError) { logger( 'Firestore._retry', requestTag, 'Retrying request that failed with error:', lastError ); } try { await backoff.backoffAndWait(); return await func(); } catch (err) { lastError = err; if (isPermanentRpcError(err, methodName)) { break; } } } logger( 'Firestore._retry', requestTag, 'Request failed with error:', lastError ); return Promise.reject(lastError); } /** * Waits for the provided stream to become active and returns a paused but * healthy stream. If an error occurs before the first byte is read, the * method rejects the returned Promise. * * @private * @internal * @param backendStream The Node stream to monitor. * @param lifetime A Promise that resolves when the stream receives an 'end', * 'close' or 'finish' message. * @param requestTag A unique client-assigned identifier for this request. * @param request If specified, the request that should be written to the * stream after opening. * @returns A guaranteed healthy stream that should be used instead of * `backendStream`. */ private _initializeStream( backendStream: Duplex, lifetime: Deferred<void>, requestTag: string, request?: {} ): Promise<Duplex> { const resultStream = new PassThrough({objectMode: true}); resultStream.pause(); /** * Whether we have resolved the Promise and returned the stream to the * caller. */ let streamInitialized = false; return new Promise<Duplex>((resolve, reject) => { function streamReady(): void { if (!streamInitialized) { streamInitialized = true; logger('Firestore._initializeStream', requestTag, 'Releasing stream'); resolve(resultStream); } } function streamEnded(): void { logger( 'Firestore._initializeStream', requestTag, 'Received stream end' ); resultStream.unpipe(backendStream); resolve(resultStream); lifetime.resolve(); } function streamFailed(err: Error): void { if (!streamInitialized) { // If we receive an error before we were able to receive any data, // reject this stream. logger( 'Firestore._initializeStream', requestTag, 'Received initial error:', err ); reject(err); } else { logger( 'Firestore._initializeStream', requestTag, 'Received stream error:', err ); // We execute the forwarding of the 'error' event via setImmediate() as // V8 guarantees that the Promise chain returned from this method // is resolved before any code executed via setImmediate(). This // allows the caller to attach an error handler. setImmediate(() => { resultStream.emit('error', err); }); } } backendStream.on('data', () => streamReady()); backendStream.on('error', err => streamFailed(err)); backendStream.on('end', () => streamEnded()); backendStream.on('close', () => streamEnded()); backendStream.on('finish', () => streamEnded()); backendStream.pipe(resultStream); if (request) { logger( 'Firestore._initializeStream', requestTag, 'Sending request: %j', request ); backendStream.write(request, 'utf-8', err => { if (err) { streamFailed(err); } else { logger( 'Firestore._initializeStream', requestTag, 'Marking stream as healthy' ); streamReady(); } }); } }); } /** * A funnel for all non-streaming API requests, assigning a project ID where * necessary within the request options. * * @private * @internal * @param methodName Name of the Veneer API endpoint that takes a request * and GAX options. * @param request The Protobuf request to send. * @param requestTag A unique client-assigned identifier for this request. * @param retryCodes If provided, a custom list of retry codes. If not * provided, retry is based on the behavior as defined in the ServiceConfig. * @returns A Promise with the request result. */ request<Req, Resp>( methodName: FirestoreUnaryMethod, request: Req, requestTag: string, retryCodes?: number[] ): Promise<Resp> { const callOptions = this.createCallOptions(methodName, retryCodes); return this._clientPool.run(requestTag, async gapicClient => { try { logger('Firestore.request', requestTag, 'Sending request: %j', request); const [result] = await ( gapicClient[methodName] as UnaryMethod<Req, Resp> )(request, callOptions); logger( 'Firestore.request', requestTag, 'Received response: %j', result ); return result; } catch (err) { logger('Firestore.request', requestTag, 'Received error:', err); return Promise.reject(err); } }); } /** * A funnel for streaming API requests, assigning a project ID where necessary * within the request options. * * The stream is returned in paused state and needs to be resumed once all * listeners are attached. * * @private * @internal * @param methodName Name of the streaming Veneer API endpoint that * takes a request and GAX options. * @param request The Protobuf request to send. * @param requestTag A unique client-assigned identifier for this request. * @returns A Promise with the resulting read-only stream. */ requestStream( methodName: FirestoreStreamingMethod, request: {}, requestTag: string ): Promise<Duplex> { const callOptions = this.createCallOptions(methodName); const bidirectional = methodName === 'listen'; return this._retry(methodName, requestTag, () => { const result = new Deferred<Duplex>(); this._clientPool.run(requestTag, async gapicClient => { logger( 'Firestore.requestStream', requestTag, 'Sending request: %j', request ); try { const stream = bidirectional ? gapicClient[methodName](callOptions) : gapicClient[methodName](request, callOptions); const logStream = new Transform({ objectMode: true, transform: (chunk, encoding, callback) => { logger( 'Firestore.requestStream', requestTag, 'Received response: %j', chunk ); callback(); }, }); stream.pipe(logStream); const lifetime = new Deferred<void>(); const resultStream = await this._initializeStream( stream, lifetime, requestTag, bidirectional ? request : undefined ); resultStream.on('end', () => stream.end()); result.resolve(resultStream); // While we return the stream to the callee early, we don't want to // release the GAPIC client until the callee has finished processing the // stream. return lifetime.promise; } catch (e) { result.reject(e); } }); return result.promise; }); } } /** * A logging function that takes a single string. * * @callback Firestore~logFunction * @param {string} Log message */ // tslint:disable-next-line:no-default-export /** * The default export of the `@google-cloud/firestore` package is the * {@link Firestore} class. * * See {@link Firestore} and {@link ClientConfig} for client methods and * configuration options. * * @module {Firestore} @google-cloud/firestore * @alias nodejs-firestore * * @example Install the client library with <a href="https://www.npmjs.com/">npm</a>: * ``` * npm install --save @google-cloud/firestore * * ``` * @example Import the client library * ``` * var Firestore = require('@google-cloud/firestore'); * * ``` * @example Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>: * ``` * var firestore = new Firestore(); * * ``` * @example Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>: * ``` * var firestore = new Firestore({ projectId: * 'your-project-id', keyFilename: '/path/to/keyfile.json' * }); * * ``` * @example <caption>include:samples/quickstart.js</caption> * region_tag:firestore_quickstart * Full quickstart example: */ // tslint:disable-next-line:no-default-export export default Firestore; // Horrible hack to ensure backwards compatibility with <= 17.0, which allows // users to call the default constructor via // `const Fs = require(`@google-cloud/firestore`); new Fs()`; const existingExports = module.exports; module.exports = Firestore; module.exports = Object.assign(module.exports, existingExports); /** * {@link v1beta1} factory function. * * @private * @internal * @name Firestore.v1beta1 * @type {function} */ Object.defineProperty(module.exports, 'v1beta1', { // The v1beta1 module is very large. To avoid pulling it in from static // scope, we lazy-load the module. get: () => require('./v1beta1'), }); /** * {@link v1} factory function. * * @private * @internal * @name Firestore.v1 * @type {function} */ Object.defineProperty(module.exports, 'v1', { // The v1 module is very large. To avoid pulling it in from static // scope, we lazy-load the module. get: () => require('./v1'), }); /** * {@link Status} factory function. * * @private * @internal * @name Firestore.GrpcStatus * @type {function} */ Object.defineProperty(module.exports, 'GrpcStatus', { // The gax module is very large. To avoid pulling it in from static // scope, we lazy-load the module. get: () => require('google-gax').Status, });
the_stack
import {CollectionViewer, DataSource} from '@angular/cdk/collections'; import {CdkTableModule} from '@angular/cdk/table'; import { createFakeEvent, createMouseEvent, dispatchMouseEvent, wrappedErrorMessage } from '@angular/cdk/testing'; import {Component, ElementRef, ViewChild} from '@angular/core'; import {async, ComponentFixture, fakeAsync, inject, TestBed, tick} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Observable} from 'rxjs'; import {map} from 'rxjs/operators'; import {MatTableModule} from '../table/index'; import { MatSort, MatSortHeader, MatSortHeaderIntl, MatSortModule, Sort, SortDirection } from './index'; import { getSortDuplicateSortableIdError, getSortHeaderMissingIdError, getSortHeaderNotContainedWithinSortError, getSortInvalidDirectionError, } from './sort-errors'; describe('MatSort', () => { let fixture: ComponentFixture<SimpleMatSortApp>; let component: SimpleMatSortApp; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MatSortModule, MatTableModule, CdkTableModule, NoopAnimationsModule], declarations: [ SimpleMatSortApp, CdkTableMatSortApp, MatTableMatSortApp, MatSortHeaderMissingMatSortApp, MatSortDuplicateMatSortableIdsApp, MatSortableMissingIdApp, MatSortableInvalidDirection ], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SimpleMatSortApp); component = fixture.componentInstance; fixture.detectChanges(); }); it('should have the sort headers register and deregister themselves', () => { const sortables = component.matSort.sortables; expect(sortables.size).toBe(4); expect(sortables.get('defaultA')).toBe(component.defaultA); expect(sortables.get('defaultB')).toBe(component.defaultB); fixture.destroy(); expect(sortables.size).toBe(0); }); it('should mark itself as initialized', fakeAsync(() => { let isMarkedInitialized = false; component.matSort.initialized.subscribe(() => isMarkedInitialized = true); tick(); expect(isMarkedInitialized).toBeTruthy(); })); it('should use the column definition if used within a cdk table', () => { let cdkTableMatSortAppFixture = TestBed.createComponent(CdkTableMatSortApp); let cdkTableMatSortAppComponent = cdkTableMatSortAppFixture.componentInstance; cdkTableMatSortAppFixture.detectChanges(); cdkTableMatSortAppFixture.detectChanges(); const sortables = cdkTableMatSortAppComponent.matSort.sortables; expect(sortables.size).toBe(3); expect(sortables.has('column_a')).toBe(true); expect(sortables.has('column_b')).toBe(true); expect(sortables.has('column_c')).toBe(true); }); it('should use the column definition if used within an mat table', () => { let matTableMatSortAppFixture = TestBed.createComponent(MatTableMatSortApp); let matTableMatSortAppComponent = matTableMatSortAppFixture.componentInstance; matTableMatSortAppFixture.detectChanges(); matTableMatSortAppFixture.detectChanges(); const sortables = matTableMatSortAppComponent.matSort.sortables; expect(sortables.size).toBe(3); expect(sortables.has('column_a')).toBe(true); expect(sortables.has('column_b')).toBe(true); expect(sortables.has('column_c')).toBe(true); }); describe('checking correct arrow direction and view state for its various states', () => { let expectedStates: Map<string, {viewState: string, arrowDirection: string}>; beforeEach(() => { // Starting state for the view and directions - note that overrideStart is reversed to be desc expectedStates = new Map<string, {viewState: string, arrowDirection: string}>([ ['defaultA', {viewState: 'asc', arrowDirection: 'asc'}], ['defaultB', {viewState: 'asc', arrowDirection: 'asc'}], ['overrideStart', {viewState: 'desc', arrowDirection: 'desc'}], ['overrideDisableClear', {viewState: 'asc', arrowDirection: 'asc'}], ]); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when mousing over headers and leaving on mouseleave', () => { // Mousing over the first sort should set the view state to hint (asc) component.dispatchMouseEvent('defaultA', 'mouseenter'); expectedStates.set('defaultA', {viewState: 'asc-to-hint', arrowDirection: 'asc'}); component.expectViewAndDirectionStates(expectedStates); // Mousing away from the first sort should hide the arrow component.dispatchMouseEvent('defaultA', 'mouseleave'); expectedStates.set('defaultA', {viewState: 'hint-to-asc', arrowDirection: 'asc'}); component.expectViewAndDirectionStates(expectedStates); // Mousing over another sort should set the view state to hint (desc) component.dispatchMouseEvent('overrideStart', 'mouseenter'); expectedStates.set('overrideStart', {viewState: 'desc-to-hint', arrowDirection: 'desc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when mousing over header and then sorting', () => { // Mousing over the first sort should set the view state to hint component.dispatchMouseEvent('defaultA', 'mouseenter'); expectedStates.set('defaultA', {viewState: 'asc-to-hint', arrowDirection: 'asc'}); component.expectViewAndDirectionStates(expectedStates); // Clicking sort on the header should set it to be active immediately // (since it was already hinted) component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when cycling through a default sort header', () => { // Sort the header to set it to the active start state component.sort('defaultA'); expectedStates.set('defaultA', {viewState: 'asc-to-active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); // Sorting again will reverse its direction component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-desc'}); component.expectViewAndDirectionStates(expectedStates); // Sorting again will remove the sort and animate away the view component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active-to-desc', arrowDirection: 'desc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should not enter sort with animations if an animations is disabled', () => { // Sort the header to set it to the active start state component.defaultA._disableViewStateAnimation = true; component.sort('defaultA'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); // Sorting again will reverse its direction component.defaultA._disableViewStateAnimation = true; component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-desc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when sort has changed while a header is active', () => { // Sort the first header to set up component.sort('defaultA'); expectedStates.set('defaultA', {viewState: 'asc-to-active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); // Sort the second header and verify that the first header animated away component.dispatchMouseEvent('defaultB', 'click'); expectedStates.set('defaultA', {viewState: 'active-to-asc', arrowDirection: 'asc'}); expectedStates.set('defaultB', {viewState: 'asc-to-active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when sort has been disabled', () => { // Mousing over the first sort should set the view state to hint component.disabledColumnSort = true; fixture.detectChanges(); component.dispatchMouseEvent('defaultA', 'mouseenter'); component.expectViewAndDirectionStates(expectedStates); }); }); it('should be able to cycle from asc -> desc from either start point', () => { component.disableClear = true; component.start = 'asc'; testSingleColumnSortDirectionSequence(fixture, ['asc', 'desc']); // Reverse directions component.start = 'desc'; testSingleColumnSortDirectionSequence(fixture, ['desc', 'asc']); }); it('should be able to cycle asc -> desc -> [none]', () => { component.start = 'asc'; testSingleColumnSortDirectionSequence(fixture, ['asc', 'desc', '']); }); it('should be able to cycle desc -> asc -> [none]', () => { component.start = 'desc'; testSingleColumnSortDirectionSequence(fixture, ['desc', 'asc', '']); }); it('should allow for the cycling the sort direction to be disabled per column', () => { const button = fixture.nativeElement.querySelector('#defaultA button'); component.sort('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(button.getAttribute('disabled')).toBeFalsy(); component.disabledColumnSort = true; fixture.detectChanges(); component.sort('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(button.getAttribute('disabled')).toBe('true'); }); it('should allow for the cycling the sort direction to be disabled for all columns', () => { const button = fixture.nativeElement.querySelector('#defaultA button'); component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(button.getAttribute('disabled')).toBeFalsy(); component.disableAllSort = true; fixture.detectChanges(); component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(button.getAttribute('disabled')).toBe('true'); component.sort('defaultB'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(button.getAttribute('disabled')).toBe('true'); }); it('should reset sort direction when a different column is sorted', () => { component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('desc'); component.sort('defaultB'); expect(component.matSort.active).toBe('defaultB'); expect(component.matSort.direction).toBe('asc'); }); it('should throw an error if an MatSortable is not contained within an MatSort directive', () => { expect(() => TestBed.createComponent(MatSortHeaderMissingMatSortApp).detectChanges()) .toThrowError(wrappedErrorMessage(getSortHeaderNotContainedWithinSortError())); }); it('should throw an error if two MatSortables have the same id', () => { expect(() => TestBed.createComponent(MatSortDuplicateMatSortableIdsApp).detectChanges()) .toThrowError(wrappedErrorMessage(getSortDuplicateSortableIdError('duplicateId'))); }); it('should throw an error if an MatSortable is missing an id', () => { expect(() => TestBed.createComponent(MatSortableMissingIdApp).detectChanges()) .toThrowError(wrappedErrorMessage(getSortHeaderMissingIdError())); }); it('should throw an error if the provided direction is invalid', () => { expect(() => TestBed.createComponent(MatSortableInvalidDirection).detectChanges()) .toThrowError(wrappedErrorMessage(getSortInvalidDirectionError('ascending'))); }); it('should allow let MatSortable override the default sort parameters', () => { testSingleColumnSortDirectionSequence( fixture, ['asc', 'desc', '']); testSingleColumnSortDirectionSequence( fixture, ['desc', 'asc', ''], 'overrideStart'); testSingleColumnSortDirectionSequence( fixture, ['asc', 'desc'], 'overrideDisableClear'); }); it('should apply the aria-labels to the button', () => { const button = fixture.nativeElement.querySelector('#defaultA button'); expect(button.getAttribute('aria-label')).toBe('Change sorting for defaultA'); }); it('should toggle indicator hint on button focus/blur and hide on click', () => { const header = fixture.componentInstance.defaultA; const button = fixture.nativeElement.querySelector('#defaultA button'); const focusEvent = createFakeEvent('focus'); const blurEvent = createFakeEvent('blur'); // Should start without a displayed hint expect(header._showIndicatorHint).toBeFalsy(); // Focusing the button should show the hint, blurring should hide it button.dispatchEvent(focusEvent); expect(header._showIndicatorHint).toBeTruthy(); button.dispatchEvent(blurEvent); expect(header._showIndicatorHint).toBeFalsy(); // Show the indicator hint. On click the hint should be hidden button.dispatchEvent(focusEvent); expect(header._showIndicatorHint).toBeTruthy(); header._handleClick(); expect(header._showIndicatorHint).toBeFalsy(); }); it('should toggle indicator hint on mouseenter/mouseleave and hide on click', () => { const header = fixture.componentInstance.defaultA; const headerElement = fixture.nativeElement.querySelector('#defaultA'); const mouseenterEvent = createMouseEvent('mouseenter'); const mouseleaveEvent = createMouseEvent('mouseleave'); // Should start without a displayed hint expect(header._showIndicatorHint).toBeFalsy(); // Mouse enter should show the hint, blurring should hide it headerElement.dispatchEvent(mouseenterEvent); expect(header._showIndicatorHint).toBeTruthy(); headerElement.dispatchEvent(mouseleaveEvent); expect(header._showIndicatorHint).toBeFalsy(); // Show the indicator hint. On click the hint should be hidden headerElement.dispatchEvent(mouseenterEvent); expect(header._showIndicatorHint).toBeTruthy(); header._handleClick(); expect(header._showIndicatorHint).toBeFalsy(); }); it('should apply the aria-sort label to the header when sorted', () => { const sortHeaderElement = fixture.nativeElement.querySelector('#defaultA'); expect(sortHeaderElement.getAttribute('aria-sort')).toBe(null); component.sort('defaultA'); fixture.detectChanges(); expect(sortHeaderElement.getAttribute('aria-sort')).toBe('ascending'); component.sort('defaultA'); fixture.detectChanges(); expect(sortHeaderElement.getAttribute('aria-sort')).toBe('descending'); component.sort('defaultA'); fixture.detectChanges(); expect(sortHeaderElement.getAttribute('aria-sort')).toBe(null); }); it('should re-render when the i18n labels have changed', inject([MatSortHeaderIntl], (intl: MatSortHeaderIntl) => { const header = fixture.debugElement.query(By.directive(MatSortHeader)).nativeElement; const button = header.querySelector('.mat-sort-header-button'); intl.sortButtonLabel = () => 'Sort all of the things'; intl.changes.next(); fixture.detectChanges(); expect(button.getAttribute('aria-label')).toBe('Sort all of the things'); }) ); }); /** * Performs a sequence of sorting on a single column to see if the sort directions are * consistent with expectations. Detects any changes in the fixture to reflect any changes in * the inputs and resets the MatSort to remove any side effects from previous tests. */ function testSingleColumnSortDirectionSequence(fixture: ComponentFixture<SimpleMatSortApp>, expectedSequence: SortDirection[], id: SimpleMatSortAppColumnIds = 'defaultA') { // Detect any changes that were made in preparation for this sort sequence fixture.detectChanges(); // Reset the sort to make sure there are no side affects from previous tests const component = fixture.componentInstance; component.matSort.active = ''; component.matSort.direction = ''; // Run through the sequence to confirm the order let actualSequence = expectedSequence.map(() => { component.sort(id); // Check that the sort event's active sort is consistent with the MatSort expect(component.matSort.active).toBe(id); expect(component.latestSortEvent.active).toBe(id); // Check that the sort event's direction is consistent with the MatSort expect(component.matSort.direction).toBe(component.latestSortEvent.direction); return component.matSort.direction; }); expect(actualSequence).toEqual(expectedSequence); // Expect that performing one more sort will loop it back to the beginning. component.sort(id); expect(component.matSort.direction).toBe(expectedSequence[0]); } /** Column IDs of the SimpleMatSortApp for typing of function params in the component (e.g. sort) */ type SimpleMatSortAppColumnIds = 'defaultA' | 'defaultB' | 'overrideStart' | 'overrideDisableClear'; @Component({ template: ` <div matSort [matSortActive]="active" [matSortDisabled]="disableAllSort" [matSortStart]="start" [matSortDirection]="direction" [matSortDisableClear]="disableClear" (matSortChange)="latestSortEvent = $event"> <div id="defaultA" #defaultA mat-sort-header="defaultA" [disabled]="disabledColumnSort"> A </div> <div id="defaultB" #defaultB mat-sort-header="defaultB"> B </div> <div id="overrideStart" #overrideStart mat-sort-header="overrideStart" start="desc"> D </div> <div id="overrideDisableClear" #overrideDisableClear mat-sort-header="overrideDisableClear" disableClear> E </div> </div> ` }) class SimpleMatSortApp { latestSortEvent: Sort; active: string; start: SortDirection = 'asc'; direction: SortDirection = ''; disableClear: boolean; disabledColumnSort = false; disableAllSort = false; @ViewChild(MatSort) matSort: MatSort; @ViewChild('defaultA') defaultA: MatSortHeader; @ViewChild('defaultB') defaultB: MatSortHeader; @ViewChild('overrideStart') overrideStart: MatSortHeader; @ViewChild('overrideDisableClear') overrideDisableClear: MatSortHeader; constructor (public elementRef: ElementRef<HTMLElement>) { } sort(id: SimpleMatSortAppColumnIds) { this.dispatchMouseEvent(id, 'click'); } dispatchMouseEvent(id: SimpleMatSortAppColumnIds, event: string) { const sortElement = this.elementRef.nativeElement.querySelector(`#${id}`)!; dispatchMouseEvent(sortElement, event); } /** * Checks expectations for each sort header's view state and arrow direction states. Receives a * map that is keyed by each sort header's ID and contains the expectation for that header's * states. */ expectViewAndDirectionStates( viewStates: Map<string, {viewState: string, arrowDirection: string}>) { const sortHeaders = new Map([ ['defaultA', this.defaultA], ['defaultB', this.defaultB], ['overrideStart', this.overrideStart], ['overrideDisableClear', this.overrideDisableClear] ]); viewStates.forEach((viewState, id) => { expect(sortHeaders.get(id)!._getArrowViewState()).toEqual(viewState.viewState); expect(sortHeaders.get(id)!._getArrowDirectionState()).toEqual(viewState.arrowDirection); }); } } class FakeDataSource extends DataSource<any> { connect(collectionViewer: CollectionViewer): Observable<any[]> { return collectionViewer.viewChange.pipe(map(() => [])); } disconnect() {} } @Component({ template: ` <cdk-table [dataSource]="dataSource" matSort> <ng-container cdkColumnDef="column_a"> <cdk-header-cell *cdkHeaderCellDef #sortHeaderA mat-sort-header> Column A </cdk-header-cell> <cdk-cell *cdkCellDef="let row"> {{row.a}} </cdk-cell> </ng-container> <ng-container cdkColumnDef="column_b"> <cdk-header-cell *cdkHeaderCellDef #sortHeaderB mat-sort-header> Column B </cdk-header-cell> <cdk-cell *cdkCellDef="let row"> {{row.b}} </cdk-cell> </ng-container> <ng-container cdkColumnDef="column_c"> <cdk-header-cell *cdkHeaderCellDef #sortHeaderC mat-sort-header> Column C </cdk-header-cell> <cdk-cell *cdkCellDef="let row"> {{row.c}} </cdk-cell> </ng-container> <cdk-header-row *cdkHeaderRowDef="columnsToRender"></cdk-header-row> <cdk-row *cdkRowDef="let row; columns: columnsToRender"></cdk-row> </cdk-table> ` }) class CdkTableMatSortApp { @ViewChild(MatSort) matSort: MatSort; dataSource = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; } @Component({ template: ` <mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="column_a"> <mat-header-cell *matHeaderCellDef #sortHeaderA mat-sort-header> Column A </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.a}} </mat-cell> </ng-container> <ng-container matColumnDef="column_b"> <mat-header-cell *matHeaderCellDef #sortHeaderB mat-sort-header> Column B </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.b}} </mat-cell> </ng-container> <ng-container matColumnDef="column_c"> <mat-header-cell *matHeaderCellDef #sortHeaderC mat-sort-header> Column C </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.c}} </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="columnsToRender"></mat-header-row> <mat-row *matRowDef="let row; columns: columnsToRender"></mat-row> </mat-table> ` }) class MatTableMatSortApp { @ViewChild(MatSort) matSort: MatSort; dataSource = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; } @Component({ template: `<div mat-sort-header="a"> A </div>` }) class MatSortHeaderMissingMatSortApp { } @Component({ template: ` <div matSort> <div mat-sort-header="duplicateId"> A </div> <div mat-sort-header="duplicateId"> A </div> </div> ` }) class MatSortDuplicateMatSortableIdsApp { } @Component({ template: ` <div matSort> <div mat-sort-header> A </div> </div> ` }) class MatSortableMissingIdApp { } @Component({ template: ` <div matSort matSortDirection="ascending"> <div mat-sort-header="a"> A </div> </div> ` }) class MatSortableInvalidDirection { }
the_stack
import { AbortSignal } from "abort-controller"; import timeoutSignal from "timeout-signal"; import * as debug_ from "debug"; import { promises as fsp } from "fs"; import * as http from "http"; import * as https from "https"; import { AbortError, Headers, RequestInit, Response } from "node-fetch"; import { IHttpGetResult, THttpGetCallback, THttpOptions, THttpResponse, } from "readium-desktop/common/utils/http"; import { decryptPersist, encryptPersist } from "readium-desktop/main/fs/persistCrypto"; import { IS_DEV } from "readium-desktop/preprocessor-directives"; import { tryCatch, tryCatchSync } from "readium-desktop/utils/tryCatch"; import { diMainGet, opdsAuthFilePath } from "../di"; import { fetchWithCookie } from "./fetch"; // Logger const filename_ = "readium-desktop:main/http"; const debug = debug_(filename_); const DEFAULT_HTTP_TIMEOUT = 30000; let authenticationToken: Record<string, IOpdsAuthenticationToken> = {}; // Redirect now handled internally, see https://github.com/valeriangalliat/fetch-cookie/blob/master/CHANGELOG.md#200---2022-02-17 // // // https://github.com/node-fetch/node-fetch/blob/master/src/utils/is-redirect.js // const redirectStatus = new Set([301, 302, 303, 307, 308]); // /** // * Redirect code matching // * // * @param {number} code - Status code // * @return {boolean} // */ // const isRedirect = (code: number) => { // return redirectStatus.has(code); // }; // 20 is fetch-cookie's default // https://github.com/valeriangalliat/fetch-cookie#max-redirects const MAX_FOLLOW_REDIRECT = 20; export const httpSetHeaderAuthorization = (type: string, credentials: string) => `${type} ${credentials}`; export const CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN = "CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN"; // tslint:disable-next-line: variable-name const CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN_fn = (host: string) => `${CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN}.${Buffer.from(host).toString("base64")}`; export interface IOpdsAuthenticationToken { id?: string; opdsAuthenticationUrl?: string; // application/opds-authentication+json refreshUrl?: string; authenticateUrl?: string; accessToken?: string; refreshToken?: string; tokenType?: string; } let authenticationTokenInitialized = false; const authenticationTokenInit = async () => { if (authenticationTokenInitialized) { return; } const data = await tryCatch(() => fsp.readFile(opdsAuthFilePath), ""); let docsFS: string | undefined; if (data) { try { docsFS = decryptPersist(data, CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN, opdsAuthFilePath); } catch (_err) { docsFS = undefined; } } let docs: Record<string, IOpdsAuthenticationToken>; const isValid = typeof docsFS === "string" && ( docs = JSON.parse(docsFS), typeof docs === "object" && Object.entries(docs) .reduce((pv, [k, v]) => pv && k.startsWith(CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN) && typeof v === "object", true)); if (!docs || !isValid) { docs = {}; } authenticationToken = docs; authenticationTokenInitialized = true; }; export const httpSetAuthenticationToken = async (data: IOpdsAuthenticationToken) => { if (!data.opdsAuthenticationUrl) { throw new Error("no opdsAutenticationUrl !!"); } await authenticationTokenInit(); const url = new URL(data.opdsAuthenticationUrl); const { host } = url; // do not risk showing plaintext access/refresh tokens in console / command line shell debug("SET opds authentication credentials for", host); // data const id = CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN_fn(host); const res = authenticationToken[id] = data; await persistJson(); return res; }; const persistJson = () => tryCatch(() => { if (!authenticationToken) return Promise.resolve(); const encrypted = encryptPersist(JSON.stringify(authenticationToken), CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN, opdsAuthFilePath); return fsp.writeFile(opdsAuthFilePath, encrypted); }, ""); export const absorbDBToJson = async () => { await authenticationTokenInit(); await persistJson(); }; export const getAuthenticationToken = async (host: string) => { await authenticationTokenInit(); const id = CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN_fn(host); return authenticationToken[id]; }; export const deleteAuthenticationToken = async (host: string) => { await authenticationTokenInit(); const id = CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN_fn(host); delete authenticationToken[id]; const encrypted = encryptPersist(JSON.stringify(authenticationToken), CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN, opdsAuthFilePath); return fsp.writeFile(opdsAuthFilePath, encrypted); }; export const wipeAuthenticationTokenStorage = async () => { // authenticationTokenInitialized = false; authenticationToken = {}; const encrypted = encryptPersist(JSON.stringify(authenticationToken), CONFIGREPOSITORY_OPDS_AUTHENTICATION_TOKEN, opdsAuthFilePath); return fsp.writeFile(opdsAuthFilePath, encrypted); }; export async function httpFetchRawResponse( url: string | URL, options: THttpOptions = {}, // redirectCounter = 0, locale = tryCatchSync(() => diMainGet("store")?.getState()?.i18n?.locale, filename_) || "en-US", ): Promise<THttpResponse> { url = new URL(url); if (url.host.startsWith("apiapploans.org.edrlab.thoriumreader")) { const [, idGln, host] = url.host.split(".break."); debug("http fetch dilicom api app server ", idGln, url.toString()); url.host = host; } options.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers || {}); (options.headers as Headers).set("user-agent", "readium-desktop"); (options.headers as Headers).set("accept-language", `${locale},en-US;q=0.7,en;q=0.5`); // Redirect now handled internally, see https://github.com/valeriangalliat/fetch-cookie/blob/master/CHANGELOG.md#200---2022-02-17 // // options.redirect = "manual"; // handle cookies // https://github.com/node-fetch/node-fetch#custom-agent // httpAgent doesn't works // err: Protocol "http:" not supported. Expected "https: // https://github.com/edrlab/thorium-reader/issues/1323#issuecomment-911772951 const httpsAgent = new https.Agent({ timeout: options.timeout || DEFAULT_HTTP_TIMEOUT, rejectUnauthorized: IS_DEV ? false : true, }); const httpAgent = new http.Agent({ timeout: options.timeout || DEFAULT_HTTP_TIMEOUT, }); options.agent = (parsedURL: URL) => { if (parsedURL.protocol === "http:") { return httpAgent; } else { return httpsAgent; } }; // if (!options.agent && url.toString().startsWith("https:")) { // const httpsAgent = new https.Agent({ // timeout: options.timeout || DEFAULT_HTTP_TIMEOUT, // rejectUnauthorized: IS_DEV ? false : true, // }); // options.agent = httpsAgent; // } options.timeout = options.timeout || DEFAULT_HTTP_TIMEOUT; options.maxRedirect = MAX_FOLLOW_REDIRECT; let timeSignal: AbortSignal | undefined; let timeout: NodeJS.Timeout | undefined; if (!options.signal) { timeSignal = timeoutSignal(options.timeout); options.signal = timeSignal; (options.signal as any).__abortReasonTimeout = true; } else if (options.abortController) { timeout = setTimeout(() => { timeout = undefined; if (options.abortController?.signal) { (options.abortController.signal as any).__abortReasonTimeout = true; } // normally implied: options.signal === options.abortController.signal (see downloader.ts) // ... but just in case another signal is configured: if (options.signal) { (options.signal as any).__abortReasonTimeout = true; } if (options.abortController && !options.abortController.signal?.aborted) { try { options.abortController.abort(); } catch {} } }, options.timeout); } else { // TODO: handle signal without our own downloader.ts AbortController? // (probably not needed as we control the full fetch lifecycle, there are no such occurences in our codebase) // const controller = new AbortController(); // timeout = setTimeout(() => { // timeout = undefined; // if (controller?.signal) { // (controller.signal as any).__abortReasonTimeout = true; // } // // propagate the timeout state to any other existing signal, // // so we can test in the fetch catch() / promise rejection // if (options.signal) { // (options.signal as any).__abortReasonTimeout = true; // } // if (controller) { // try { // controller.abort(); // not bound to fetch, so does nothing! // } catch {} // } // }, options.timeout); } let response: Response; try { response = await fetchWithCookie(url.toString(), options); } finally { // module-level weakmap of timeouts, // see https://github.com/node-fetch/timeout-signal/blob/main/index.js if (timeSignal) { try { timeoutSignal.clear(timeSignal); } catch {} } // our local, closure-level timeout if (timeout) { clearTimeout(timeout); timeout = undefined; } } debug("fetch URL:", `${url}`); debug("Method", options.method); debug("Request headers :"); debug(options.headers); debug("###"); debug("OK: ", response.ok); debug("status code :", response.status); debug("status text :", response.statusText); // Redirect now handled internally, see https://github.com/valeriangalliat/fetch-cookie/blob/master/CHANGELOG.md#200---2022-02-17 // // // manual Redirect to handle cookies // // https://github.com/node-fetch/node-fetch/blob/0d35ddbf7377a483332892d2b625ec8231fa6181/src/index.js#L129 // if (isRedirect(response.status)) { // const location = response.headers.get("Location"); // debug("Redirect", response.status, "to: ", location); // if (location) { // const locationUrl = resolve(response.url, location); // if (redirectCounter > FOLLOW_REDIRECT_COUNTER) { // throw new Error(`maximum redirect reached at: ${url}`); // } // if ( // response.status === 303 || // ((response.status === 301 || response.status === 302) && options.method === "POST") // ) { // options.method = "GET"; // options.body = undefined; // if (options.headers) { // if (!(options.headers instanceof Headers)) { // options.headers = new Headers(options.headers); // } // (options.headers as Headers).delete("content-length"); // } // } // return await httpFetchRawResponse(locationUrl, options, redirectCounter + 1, locale); // } else { // debug("No location URL to redirect"); // } // } // ALTERNATIVELY, Promise.race() // // See: https://github.com/simonplend/how-to-cancel-an-http-request-in-node-js/blob/main/example-node-fetch.mjs // // import { setTimeout } from "node:timers/promises"; // const cancelRequest = new AbortController(); // const cancelTimeout = new AbortController(); // const fetchWithCookieResponsePromise = async () => { // try { // // response // } finally { // cancelTimeout.abort(); // } // } // const timeoutPromise = async () => { // try { // await setTimeout(options.timeout, undefined, { signal: cancelTimeout.signal }); // cancelRequest.abort(); // } catch (_err) { // return; // } // throw new Error(`HTTP fetch request timeout ${options.timeout}ms`); // }; // return Promise.race([fetchWithCookieResponsePromise, timeoutPromise()]); return response; } const handleCallback = async <T = undefined>(res: IHttpGetResult<T>, callback: THttpGetCallback<T>) => { if (callback) { res = await Promise.resolve(callback(res)); // remove for IPC sync res.body = undefined; res.response = undefined; } return res; }; export async function httpFetchFormattedResponse<TData = undefined>( url: string | URL, options?: THttpOptions, callback?: THttpGetCallback<TData>, locale?: string, ): Promise<IHttpGetResult<TData>> { let result: IHttpGetResult<TData> = { isFailure: true, isSuccess: false, url, }; try { const response = await httpFetchRawResponse(url, options, locale); debug("Response headers :"); debug({ ...response.headers.raw() }); debug("###"); result = { isAbort: false, isNetworkError: false, isTimeout: false, isFailure: !response.ok/*response.status < 200 || response.status >= 300*/, isSuccess: response.ok/*response.status >= 200 && response.status < 300*/, url, responseUrl: response.url, statusCode: response.status, statusMessage: response.statusText, body: response.body, response, data: undefined, contentType: response.headers.get("Content-Type"), // cookies: response.headers.get("Set-Cookie"), }; } catch (err) { const errStr = err.toString(); debug("### HTTP FETCH ERROR ###"); debug(errStr); debug("url: ", url); debug("options: ", options); if (errStr.includes("timeout") || (options?.signal as any)?.__abortReasonTimeout) { // err.name === "FetchError" result = { isAbort: false, isNetworkError: true, isTimeout: true, isFailure: true, isSuccess: false, url, statusMessage: errStr, }; } else if (err.name === "AbortError" || err instanceof AbortError) { result = { isAbort: true, isNetworkError: false, isTimeout: false, isFailure: true, isSuccess: false, url, }; } else { // err.name === "FetchError" result = { isAbort: false, isNetworkError: true, isTimeout: false, isFailure: true, isSuccess: false, url, statusMessage: errStr, }; } debug("HTTP FAIL RESUlT"); debug(result); debug("#################"); } finally { result = await handleCallback(result, callback); } return result; } export const httpGetWithAuth = (enableAuth = true): typeof httpFetchFormattedResponse => async (...arg) => { const [_url, _options, _callback, ..._arg] = arg; const options = _options || {}; options.method = "get"; // const response = await httpFetchFormattedResponse( // _url, // options, // enableAuth ? undefined : _callback, // ..._arg, // ); if (enableAuth) { // response.statusCode === 401 // enableAuth always activate on httpGet request // means that on each request the acessToken is returned and not only for the 401 http response // specific to 'librarySimplified' server implementation const url = _url instanceof URL ? _url : new URL(_url); const { host } = url; const auth = await getAuthenticationToken(host); if ( typeof auth === "object" && auth.accessToken ) { // We have an authentication token for this host. // We should use it by default // Because we won't always get a 401 response that will ask us to use it. return httpGetUnauthorized(auth)(_url, options, _callback, ..._arg); } // return await handleCallback(response, _callback); } // return response; return httpFetchFormattedResponse( _url, options, _callback, ..._arg, ); }; export const httpGet = httpGetWithAuth(true); const httpGetUnauthorized = (auth: IOpdsAuthenticationToken, enableRefresh = true): typeof httpFetchFormattedResponse => async (...arg) => { const [_url, _options, _callback, ..._arg] = arg; const url = _url instanceof URL ? _url : new URL(_url); const options = _options || {}; const { accessToken, tokenType } = auth; options.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers || {}); (options.headers as Headers).set("Authorization", httpSetHeaderAuthorization(tokenType || "Bearer", accessToken)); const response = await httpGetWithAuth(false)( url, options, enableRefresh ? undefined : _callback, ..._arg, ); if (enableRefresh) { if (response.statusCode === 401) { if (auth.refreshUrl && auth.refreshToken) { const responseAfterRefresh = await httpGetUnauthorizedRefresh( auth, )(url, options, _callback, ..._arg); return responseAfterRefresh || response; } else { // Most likely because of a wrong access token. // In some cases the returned content won't launch a new authentication process // It's safer to just delete the access token and start afresh now. await deleteAuthenticationToken(url.host); (options.headers as Headers).delete("Authorization"); const responseWithoutAuth = await httpGetWithAuth( false, )(url, options, _callback, ..._arg); return responseWithoutAuth || response; } } else { return await handleCallback(response, _callback); } } return response; }; const httpGetUnauthorizedRefresh = (auth: IOpdsAuthenticationToken): typeof httpFetchFormattedResponse | undefined => async (...arg) => { const { refreshToken, refreshUrl } = auth; const options: RequestInit = {}; options.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers || {}); (options.headers as Headers).set("Content-Type", "application/json"); options.body = JSON.stringify({ refresh_token: refreshToken, grant_type: "refresh_token", }); const httpPostResponse = await httpPost(refreshUrl, options); if (httpPostResponse.isSuccess) { const jsonDataResponse: any = await httpPostResponse.response.json(); const newRefreshToken = typeof jsonDataResponse?.refresh_token === "string" ? jsonDataResponse.refresh_token : undefined; auth.refreshToken = newRefreshToken || auth.refreshToken; const newAccessToken = typeof jsonDataResponse?.access_token === "string" ? jsonDataResponse.access_token : undefined; auth.accessToken = newAccessToken || auth.accessToken; const httpGetResponse = await httpGetUnauthorized(auth, false)(...arg); if (httpGetResponse.statusCode !== 401) { debug("authenticate with the new access_token"); debug("saved it into db"); await httpSetAuthenticationToken(auth); } return httpGetResponse; } return undefined; }; export const httpPost: typeof httpFetchFormattedResponse = async (...arg) => { let [, options] = arg; options = options || {}; options.method = "post"; arg[1] = options; // do not risk showing plaintext password in console / command line shell // debug("Body:"); // debug(options.body); return httpFetchFormattedResponse(...arg); };
the_stack
import crypto from 'crypto'; import Ejs from 'ejs'; import fs from 'fs'; import { IncomingMessage, ServerResponse } from 'http'; import path from 'path'; import serialize from 'serialize-javascript'; import Vue from 'vue'; import { BundleRenderer, createBundleRenderer, createRenderer, Renderer as VueRenderer } from 'vue-server-renderer'; import * as Genesis from './'; import { SSR } from './ssr'; const md5 = (content: string) => { var md5 = crypto.createHash('md5'); return md5.update(content).digest('hex'); }; const defaultTemplate = `<!DOCTYPE html><html><head><title>Vue SSR for Genesis</title><%-style%></head><body><%-html%><%-scriptState%><%-script%></body></html>`; const modes: Genesis.RenderMode[] = [ 'ssr-html', 'csr-html', 'ssr-json', 'csr-json' ]; export class Renderer { public ssr: Genesis.SSR; public clientManifest: Genesis.ClientManifest; /** * Client side renderer */ private csrRenderer: VueRenderer; /** * Render template functions */ private compile: Ejs.TemplateFunction; /** * Server side renderer */ private ssrRenderer: BundleRenderer; public constructor(ssr: Genesis.SSR, options?: Genesis.RendererOptions) { if ( (!options?.client?.data || !options?.server?.data) && (!fs.existsSync(ssr.outputClientManifestFile) || !fs.existsSync(ssr.outputServerBundleFile)) ) { ssr = new SSR({ build: { outputDir: path.resolve( __dirname, /src$/.test(__dirname) ? '../dist/ssr-genesis' : '../ssr-genesis' ) } }); console.warn( `You have not built the application, please execute 'new Build(ssr).start()' build first, Now use the default` ); } this.ssr = ssr; const template: any = async ( strHtml: string, ctx: Genesis.RenderContext ): Promise<Genesis.RenderData> => { const html = strHtml.replace( /^(<[A-z]([A-z]|[0-9])+)/, `$1 ${this._createRootNodeAttr(ctx)}` ); const vueCtx: any = ctx; const resource = vueCtx.getPreloadFiles().map( (item: any): Genesis.RenderContextResource => { return { file: `${this.ssr.publicPath}${item.file}`, extension: item.extension }; } ); const { data } = ctx; if (html === '<!---->') { data.html += `<div ${this._createRootNodeAttr(ctx)}></div>`; } else { data.html += html; } const baseUrl = encodeURIComponent( ssr.cdnPublicPath + ssr.publicPath ); data.script = `<script>window["__webpack_public_path_${ssr.name}__"] = "${baseUrl}";</script>` + data.script + vueCtx.renderScripts(); data.style += vueCtx.renderStyles(); data.resource = [...data.resource, ...resource]; (ctx as any)._subs.forEach((fn: Function) => fn(ctx)); (ctx as any)._subs = []; return ctx.data; }; const clientManifest: Genesis.ClientManifest = options?.client ?.data || { ...require(this.ssr.outputClientManifestFile) }; const bundle = options?.server?.data || { ...require(this.ssr.outputServerBundleFile) }; clientManifest.publicPath = ssr.cdnPublicPath + clientManifest.publicPath; const renderOptions = { template, inject: false, clientManifest: clientManifest }; const ejsTemplate = fs.existsSync(this.ssr.templateFile) ? fs.readFileSync(this.ssr.outputTemplateFile, 'utf-8') : defaultTemplate; this.ssrRenderer = createBundleRenderer(bundle, { ...renderOptions, runInNewContext: 'once' }); this.csrRenderer = createRenderer(renderOptions); this.clientManifest = clientManifest; this.compile = Ejs.compile(ejsTemplate); const bindArr = [ 'renderJson', 'renderHtml', 'render', 'renderMiddleware' ]; bindArr.forEach((k) => { this[k] = this[k].bind(this); Object.defineProperty(this, k, { enumerable: false }); }); process.env[`__webpack_public_path_${ssr.name}__`] = ssr.cdnPublicPath + ssr.publicPath; } /** * Hot update */ public hotUpdate(options?: Genesis.RendererOptions) { const renderer = new Renderer(this.ssr, options); this.csrRenderer = renderer.csrRenderer; this.compile = renderer.compile; this.ssrRenderer = renderer.ssrRenderer; } /** * Render JSON */ public async renderJson( options: Genesis.RenderOptions<Genesis.RenderModeJson> = { mode: 'ssr-json' } ): Promise<Genesis.RenderResultJson> { options = { ...options }; if ( !options.mode || ['ssr-json', 'csr-json'].indexOf(options.mode) === -1 ) { options.mode = 'ssr-json'; } return this.render(options) as Promise<Genesis.RenderResultJson>; } /** * Render HTML */ public async renderHtml( options: Genesis.RenderOptions<Genesis.RenderModeHtml> = { mode: 'ssr-html' } ): Promise<Genesis.RenderResultHtml> { options = { ...options }; if ( !options.mode || ['ssr-html', 'csr-html'].indexOf(options.mode) === -1 ) { options.mode = 'ssr-html'; } return this.render(options) as Promise<Genesis.RenderResultHtml>; } /** * General basic rendering function */ public async render<T extends Genesis.RenderMode = Genesis.RenderMode>( options: Genesis.RenderOptions<T> = {} ): Promise<Genesis.RenderResult<T>> { const { ssr } = this; const context = this._createContext<T>(options); await ssr.plugin.callHook('renderBefore', context); switch (context.mode) { case 'ssr-html': case 'csr-html': return this._renderHtml(context) as any; case 'ssr-json': case 'csr-json': return this._renderJson(context) as any; } } /** * Rendering Middleware */ public async renderMiddleware( req: IncomingMessage, res: ServerResponse, next: (err: any) => void ): Promise<void> { try { const result = await this.render({ req, res }); res.setHeader('cache-control', 'max-age=0'); switch (result.type) { case 'html': res.setHeader('content-type', 'text/html; charset=utf-8'); res.write(result.data); break; case 'json': res.setHeader( 'content-type', 'application/json; charset=utf-8' ); res.write(JSON.stringify(result.data)); break; } res.end(); } catch (err) { next(err); } } private _createContext<T extends Genesis.RenderMode = Genesis.RenderMode>( options: Genesis.RenderOptions<T> ): Genesis.RenderContext { const context: Genesis.RenderContext = { env: 'server', data: { id: '', name: this.ssr.name, url: '/', html: '', style: '', script: '', scriptState: '', state: {}, resource: [], automount: true }, mode: 'ssr-html', renderHtml: () => this.compile(context.data), ssr: this.ssr, beforeRender: (cb) => { (context as any)._subs.push(cb); } }; Object.defineProperty(context, '_subs', { enumerable: false, value: [], writable: true }); Object.defineProperty(context.data, 'scriptState', { enumerable: false, get() { const data = context.data; const script = { ...data, env: 'client' }; const arr = [ 'style', 'html', 'scriptState', 'script', 'resource' ]; arr.forEach((k) => { Object.defineProperty(script, k, { enumerable: false }); }); const scriptJSON: string = serialize(script, { isJSON: true }); return `<script data-ssr-genesis-name="${data.name}" data-ssr-genesis-id="${data.id}">window["${data.id}"]=${scriptJSON};</script>`; } }); // set context if (options.req instanceof IncomingMessage) { context.req = options.req; if (typeof context.req.url === 'string') { context.data.url = context.req.url; } } if (options.res instanceof ServerResponse) { context.res = options.res; } if (options.mode && modes.indexOf(options.mode) > -1) { context.mode = options.mode; } if ( Object.prototype.toString.call(options.state) === '[object Object]' ) { context.data.state = options.state || {}; } // set context data if (typeof options.url === 'string') { context.data.url = options.url; } if (typeof options.id === 'string') { context.data.id = options.id; } else { context.data.id = md5(`${context.data.name}-${context.data.url}`); } if (typeof options.name === 'string') { context.data.name = options.name; } if (typeof options.automount === 'boolean') { context.data.automount = options.automount; } return context; } private async _renderJson( context: Genesis.RenderContext ): Promise<Genesis.RenderResultJson> { switch (context.mode) { case 'ssr-json': return { type: 'json', data: await this._ssrToJson(context), context }; case 'csr-json': return { type: 'json', data: await this._csrToJson(context), context }; } throw new TypeError(`No type ${context.mode}`); } /** * Render HTML */ private async _renderHtml( context: Genesis.RenderContext ): Promise<Genesis.RenderResultHtml> { switch (context.mode) { case 'ssr-html': return { type: 'html', data: await this._ssrToString(context), context }; case 'csr-html': return { type: 'html', data: await this._csrToString(context), context }; } throw new TypeError(`No type ${context.mode}`); } /** * Static file public path */ public get staticPublicPath() { return this.ssr.publicPath; } /** * Static file directory */ public get staticDir() { return this.ssr.staticDir; } /** * The server renders a JSON */ private async _ssrToJson( context: Genesis.RenderContext ): Promise<Genesis.RenderData> { await new Promise((resolve, reject) => { this.ssrRenderer.renderToString(context, (err, data: any) => { if (err) { return reject(err); } else if (typeof data !== 'object') { reject(new Error('Vue no rendering results')); } resolve(data); }); }); await this.ssr.plugin.callHook('renderCompleted', context); return context.data; } /** * The server renders a HTML */ private async _ssrToString( context: Genesis.RenderContext ): Promise<string> { await this._ssrToJson(context); return context.renderHtml(); } /** * The client renders a JSON */ private async _csrToJson( context: Genesis.RenderContext ): Promise<Genesis.RenderData> { const vm = new Vue({ render(h) { return h('div'); } }); const data: Genesis.RenderData = (await this.csrRenderer.renderToString( vm, context )) as any; data.html = `<div ${this._createRootNodeAttr(context)}></div>`; await this.ssr.plugin.callHook('renderCompleted', context); return context.data; } /** * The client renders a HTML */ private async _csrToString( context: Genesis.RenderContext ): Promise<string> { await this._csrToJson(context); return context.renderHtml(); } private _createRootNodeAttr(context: Genesis.RenderContext) { const { data, ssr } = context; const name = ssr.name; return `data-ssr-genesis-id="${data.id}" data-ssr-genesis-name="${name}"`; } }
the_stack
import * as ecr from '@aws-cdk/aws-ecr'; import * as assets from '@aws-cdk/aws-ecr-assets'; import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; import { Construct } from 'constructs'; import { CfnService } from './apprunner.generated'; /** * The image repository types */ export enum ImageRepositoryType { /** * Amazon ECR Public */ ECR_PUBLIC = 'ECR_PUBLIC', /** * Amazon ECR */ ECR = 'ECR', } /** * The number of CPU units reserved for each instance of your App Runner service. * */ export class Cpu { /** * 1 vCPU */ public static readonly ONE_VCPU = Cpu.of('1 vCPU') /** * 2 vCPU */ public static readonly TWO_VCPU = Cpu.of('2 vCPU') /** * Custom CPU unit * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-instanceconfiguration.html#cfn-apprunner-service-instanceconfiguration-cpu * * @param unit custom CPU unit */ public static of(unit: string) { return new Cpu(unit); } /** * * @param unit The unit of CPU. */ private constructor(public readonly unit: string) {} } /** * The amount of memory reserved for each instance of your App Runner service. */ export class Memory { /** * 2 GB(for 1 vCPU) */ public static readonly TWO_GB = Memory.of('2 GB') /** * 3 GB(for 1 vCPU) */ public static readonly THREE_GB = Memory.of('3 GB') /** * 4 GB(for 1 or 2 vCPU) */ public static readonly FOUR_GB = Memory.of('4 GB') /** * Custom Memory unit * * @param unit custom Memory unit * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-instanceconfiguration.html#cfn-apprunner-service-instanceconfiguration-memory */ public static of(unit: string) { return new Memory(unit); } /** * * @param unit The unit of memory. */ private constructor(public readonly unit: string) { } } /** * The code runtimes */ export class Runtime { /** * NodeJS 12 */ public static readonly NODEJS_12 = Runtime.of('NODEJS_12') /** * Python 3 */ public static readonly PYTHON_3 = Runtime.of('PYTHON_3') /** * Other runtimes * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-codeconfigurationvalues.html#cfn-apprunner-service-codeconfigurationvalues-runtime for all available runtimes. * * @param name runtime name * */ public static of(name: string) { return new Runtime(name); } /** * * @param name The runtime name. */ private constructor(public readonly name: string) { } } /** * The environment variable for the service. */ interface EnvironmentVariable { readonly name: string; readonly value: string; } /** * Result of binding `Source` into a `Service`. */ export interface SourceConfig { /** * The image repository configuration (mutually exclusive with `codeRepository`). * * @default - no image repository. */ readonly imageRepository?: ImageRepository; /** * The ECR repository (required to grant the pull privileges for the iam role). * * @default - no ECR repository. */ readonly ecrRepository?: ecr.IRepository; /** * The code repository configuration (mutually exclusive with `imageRepository`). * * @default - no code repository. */ readonly codeRepository?: CodeRepositoryProps; } /** * Properties of the Github repository for `Source.fromGitHub()` */ export interface GithubRepositoryProps { /** * The code configuration values. Will be ignored if configurationSource is `REPOSITORY`. * @default - no values will be passed. The `apprunner.yaml` from the github reopsitory will be used instead. */ readonly codeConfigurationValues?: CodeConfigurationValues; /** * The source of the App Runner configuration. */ readonly configurationSource: ConfigurationSourceType; /** * The location of the repository that contains the source code. */ readonly repositoryUrl: string; /** * The branch name that represents a specific version for the repository. * * @default main */ readonly branch?: string; /** * ARN of the connection to Github. Only required for Github source. */ readonly connection: GitHubConnection; } /** * Properties of the image repository for `Source.fromEcrPublic()` */ export interface EcrPublicProps { /** * The image configuration for the image from ECR Public. * @default - no image configuration will be passed. The default `port` will be 8080. * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-imageconfiguration.html#cfn-apprunner-service-imageconfiguration-port */ readonly imageConfiguration?: ImageConfiguration; /** * The ECR Public image URI. */ readonly imageIdentifier: string; } /** * Properties of the image repository for `Source.fromEcr()` */ export interface EcrProps { /** * The image configuration for the image from ECR. * @default - no image configuration will be passed. The default `port` will be 8080. * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-imageconfiguration.html#cfn-apprunner-service-imageconfiguration-port */ readonly imageConfiguration?: ImageConfiguration; /** * Represents the ECR repository. */ readonly repository: ecr.IRepository; /** * Image tag. * @default - 'latest' */ readonly tag?: string; } /** * Properties of the image repository for `Source.fromAsset()` */ export interface AssetProps { /** * The image configuration for the image built from the asset. * @default - no image configuration will be passed. The default `port` will be 8080. * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-imageconfiguration.html#cfn-apprunner-service-imageconfiguration-port */ readonly imageConfiguration?: ImageConfiguration; /** * Represents the docker image asset. */ readonly asset: assets.DockerImageAsset; } /** * Represents the App Runner service source. */ export abstract class Source { /** * Source from the GitHub repository. */ public static fromGitHub(props: GithubRepositoryProps): GithubSource { return new GithubSource(props); } /** * Source from the ECR repository. */ public static fromEcr(props: EcrProps): EcrSource { return new EcrSource(props); } /** * Source from the ECR Public repository. */ public static fromEcrPublic(props: EcrPublicProps): EcrPublicSource { return new EcrPublicSource(props); } /** * Source from local assets. */ public static fromAsset(props: AssetProps): AssetSource { return new AssetSource(props); } /** * Called when the Job is initialized to allow this object to bind. */ public abstract bind(scope: Construct): SourceConfig; } /** * Represents the service source from a Github repository. */ export class GithubSource extends Source { private readonly props: GithubRepositoryProps constructor(props: GithubRepositoryProps) { super(); this.props = props; } public bind(_scope: Construct): SourceConfig { return { codeRepository: { codeConfiguration: { configurationSource: this.props.configurationSource, configurationValues: this.props.codeConfigurationValues, }, repositoryUrl: this.props.repositoryUrl, sourceCodeVersion: { type: 'BRANCH', value: this.props.branch ?? 'main', }, connection: this.props.connection, }, }; } } /** * Represents the service source from ECR. */ export class EcrSource extends Source { private readonly props: EcrProps constructor(props: EcrProps) { super(); this.props = props; } public bind(_scope: Construct): SourceConfig { return { imageRepository: { imageConfiguration: this.props.imageConfiguration, imageIdentifier: this.props.repository.repositoryUriForTag(this.props.tag || 'latest'), imageRepositoryType: ImageRepositoryType.ECR, }, ecrRepository: this.props.repository, }; } } /** * Represents the service source from ECR Public. */ export class EcrPublicSource extends Source { private readonly props: EcrPublicProps; constructor(props: EcrPublicProps) { super(); this.props = props; } public bind(_scope: Construct): SourceConfig { return { imageRepository: { imageConfiguration: this.props.imageConfiguration, imageIdentifier: this.props.imageIdentifier, imageRepositoryType: ImageRepositoryType.ECR_PUBLIC, }, }; } } /** * Represents the source from local assets. */ export class AssetSource extends Source { private readonly props: AssetProps constructor(props: AssetProps) { super(); this.props = props; } public bind(_scope: Construct): SourceConfig { return { imageRepository: { imageConfiguration: this.props.imageConfiguration, imageIdentifier: this.props.asset.imageUri, imageRepositoryType: ImageRepositoryType.ECR, }, ecrRepository: this.props.asset.repository, }; } } /** * Describes the configuration that AWS App Runner uses to run an App Runner service * using an image pulled from a source image repository. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-imageconfiguration.html */ export interface ImageConfiguration { /** * The port that your application listens to in the container. * * @default 8080 */ readonly port?: number; /** * Environment variables that are available to your running App Runner service. * * @default - no environment variables */ readonly environment?: { [key: string]: string }; /** * An optional command that App Runner runs to start the application in the source image. * If specified, this command overrides the Docker image’s default start command. * * @default - no start command */ readonly startCommand?: string; } /** * Describes a source image repository. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-imagerepository.html */ export interface ImageRepository { /** * The identifier of the image. For `ECR_PUBLIC` imageRepositoryType, the identifier domain should * always be `public.ecr.aws`. For `ECR`, the pattern should be * `([0-9]{12}.dkr.ecr.[a-z\-]+-[0-9]{1}.amazonaws.com\/.*)`. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-imagerepository.html for more details. */ readonly imageIdentifier: string; /** * The type of the image repository. This reflects the repository provider and whether * the repository is private or public. */ readonly imageRepositoryType: ImageRepositoryType; /** * Configuration for running the identified image. * @default - no image configuration will be passed. The default `port` will be 8080. * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-imageconfiguration.html#cfn-apprunner-service-imageconfiguration-port */ readonly imageConfiguration?: ImageConfiguration; } /** * Identifies a version of code that AWS App Runner refers to within a source code repository. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-sourcecodeversion.html */ export interface SourceCodeVersion { /** * The type of version identifier. */ readonly type: string; /** * A source code version. */ readonly value: string; } /** * Properties of the CodeRepository. */ export interface CodeRepositoryProps { /** * Configuration for building and running the service from a source code repository. */ readonly codeConfiguration: CodeConfiguration; /** * The location of the repository that contains the source code. */ readonly repositoryUrl: string; /** * The version that should be used within the source code repository. */ readonly sourceCodeVersion: SourceCodeVersion; /** * The App Runner connection for GitHub. */ readonly connection: GitHubConnection; } /** * Properties of the AppRunner Service */ export interface ServiceProps { /** * The source of the repository for the service. */ readonly source: Source; /** * The number of CPU units reserved for each instance of your App Runner service. * * @default Cpu.ONE_VCPU */ readonly cpu?: Cpu; /** * The amount of memory reserved for each instance of your App Runner service. * * @default Memory.TWO_GB */ readonly memory?: Memory; /** * The IAM role that grants the App Runner service access to a source repository. * It's required for ECR image repositories (but not for ECR Public repositories). * * The role must be assumable by the 'build.apprunner.amazonaws.com' service principal. * * @see https://docs.aws.amazon.com/apprunner/latest/dg/security_iam_service-with-iam.html#security_iam_service-with-iam-roles-service.access * * @default - generate a new access role. */ readonly accessRole?: iam.IRole; /** * The IAM role that provides permissions to your App Runner service. * These are permissions that your code needs when it calls any AWS APIs. * * The role must be assumable by the 'tasks.apprunner.amazonaws.com' service principal. * * @see https://docs.aws.amazon.com/apprunner/latest/dg/security_iam_service-with-iam.html#security_iam_service-with-iam-roles-service.instance * * @default - no instance role attached. */ readonly instanceRole?: iam.IRole; /** * Name of the service. * * @default - auto-generated if undefined. */ readonly serviceName?: string; } /** * The source of the App Runner configuration. */ export enum ConfigurationSourceType { /** * App Runner reads configuration values from `the apprunner.yaml` file in the source code repository * and ignores `configurationValues`. */ REPOSITORY = 'REPOSITORY', /** * App Runner uses configuration values provided in `configurationValues` and ignores the `apprunner.yaml` * file in the source code repository. */ API = 'API', } /** * Describes the configuration that AWS App Runner uses to build and run an App Runner service * from a source code repository. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apprunner-service-codeconfiguration.html */ export interface CodeConfiguration { /** * The basic configuration for building and running the App Runner service. * Use it to quickly launch an App Runner service without providing a apprunner.yaml file in the * source code repository (or ignoring the file if it exists). * * @default - not specified. Use `apprunner.yaml` instead. */ readonly configurationValues?: CodeConfigurationValues; /** * The source of the App Runner configuration. */ readonly configurationSource: ConfigurationSourceType; } /** * Describes resources needed to authenticate access to some source repositories. * The specific resource depends on the repository provider. */ interface AuthenticationConfiguration { /** * The Amazon Resource Name (ARN) of the IAM role that grants the App Runner service access to a * source repository. It's required for ECR image repositories (but not for ECR Public repositories). * * @defult - no access role. */ readonly accessRoleArn?: string; /** * The Amazon Resource Name (ARN) of the App Runner connection that enables the App Runner service * to connect to a source repository. It's required for GitHub code repositories. * * @default - no connection. */ readonly connectionArn?: string; } /** * Describes the basic configuration needed for building and running an AWS App Runner service. * This type doesn't support the full set of possible configuration options. Fur full configuration capabilities, * use a `apprunner.yaml` file in the source code repository. */ export interface CodeConfigurationValues { /** * The command App Runner runs to build your application. * * @default - no build command. */ readonly buildCommand?: string; /** * The port that your application listens to in the container. * * @default 8080 */ readonly port?: string; /** * A runtime environment type for building and running an App Runner service. It represents * a programming language runtime. */ readonly runtime: Runtime; /** * The environment variables that are available to your running App Runner service. * * @default - no environment variables. */ readonly environment?: { [key: string]: string }; /** * The command App Runner runs to start your application. * * @default - no start command. */ readonly startCommand?: string; } /** * Represents the App Runner connection that enables the App Runner service to connect * to a source repository. It's required for GitHub code repositories. */ export class GitHubConnection { /** * Using existing App Runner connection by specifying the connection ARN. * @param arn connection ARN * @returns Connection */ public static fromConnectionArn(arn: string): GitHubConnection { return new GitHubConnection(arn); } /** * The ARN of the Connection for App Runner service to connect to the repository. */ public readonly connectionArn: string constructor(arn: string) { this.connectionArn = arn; } } /** * Attributes for the App Runner Service */ export interface ServiceAttributes { /** * The name of the service. */ readonly serviceName: string; /** * The ARN of the service. */ readonly serviceArn: string; /** * The URL of the service. */ readonly serviceUrl: string; /** * The status of the service. */ readonly serviceStatus: string; } /** * Represents the App Runner Service. */ export interface IService extends cdk.IResource { /** * The Name of the service. */ readonly serviceName: string; /** * The ARN of the service. */ readonly serviceArn: string; } /** * The App Runner Service. */ export class Service extends cdk.Resource { /** * Import from service name. */ public static fromServiceName(scope: Construct, id: string, serviceName: string): IService { class Import extends cdk.Resource { public serviceName = serviceName; public serviceArn = cdk.Stack.of(this).formatArn({ resource: 'service', service: 'apprunner', resourceName: serviceName, }) } return new Import(scope, id); } /** * Import from service attributes. */ public static fromServiceAttributes(scope: Construct, id: string, attrs: ServiceAttributes): IService { const serviceArn = attrs.serviceArn; const serviceName = attrs.serviceName; const serviceUrl = attrs.serviceUrl; const serviceStatus = attrs.serviceStatus; class Import extends cdk.Resource { public readonly serviceArn = serviceArn public readonly serviceName = serviceName public readonly serviceUrl = serviceUrl public readonly serviceStatus = serviceStatus } return new Import(scope, id); } private readonly props: ServiceProps; private accessRole?: iam.IRole; private source: SourceConfig; /** * Environment variables for this service */ private environment?: { [key: string]: string } = {}; /** * The ARN of the Service. * @attribute */ readonly serviceArn: string; /** * The ID of the Service. * @attribute */ readonly serviceId: string; /** * The URL of the Service. * @attribute */ readonly serviceUrl: string; /** * The status of the Service. * @attribute */ readonly serviceStatus: string; /** * The name of the service. * @attribute */ readonly serviceName: string; public constructor(scope: Construct, id: string, props: ServiceProps) { super(scope, id); const source = props.source.bind(this); this.source = source; this.props = props; // generate an IAM role only when ImageRepositoryType is ECR and props.role is undefined this.accessRole = (this.source.imageRepository?.imageRepositoryType == ImageRepositoryType.ECR) ? this.props.accessRole ? this.props.accessRole : this.generateDefaultRole() : undefined; if (source.codeRepository?.codeConfiguration.configurationSource == ConfigurationSourceType.REPOSITORY && source.codeRepository?.codeConfiguration.configurationValues) { throw new Error('configurationValues cannot be provided if the ConfigurationSource is Repository'); } const resource = new CfnService(this, 'Resource', { instanceConfiguration: { cpu: props.cpu?.unit, memory: props.memory?.unit, instanceRoleArn: props.instanceRole?.roleArn, }, sourceConfiguration: { authenticationConfiguration: this.renderAuthenticationConfiguration(), imageRepository: source.imageRepository ? this.renderImageRepository() : undefined, codeRepository: source.codeRepository ? this.renderCodeConfiguration() : undefined, }, }); // grant required privileges for the role if (source.ecrRepository && this.accessRole) { source.ecrRepository.grantPull(this.accessRole); } this.serviceArn = resource.attrServiceArn; this.serviceId = resource.attrServiceId; this.serviceUrl = resource.attrServiceUrl; this.serviceStatus = resource.attrStatus; this.serviceName = resource.ref; } private renderAuthenticationConfiguration(): AuthenticationConfiguration { return { accessRoleArn: this.accessRole?.roleArn, connectionArn: this.source.codeRepository?.connection?.connectionArn, }; } private renderCodeConfiguration() { return { codeConfiguration: { configurationSource: this.source.codeRepository!.codeConfiguration.configurationSource, // codeConfigurationValues will be ignored if configurationSource is REPOSITORY codeConfigurationValues: this.source.codeRepository!.codeConfiguration.configurationValues ? this.renderCodeConfigurationValues(this.source.codeRepository!.codeConfiguration.configurationValues) : undefined, }, repositoryUrl: this.source.codeRepository!.repositoryUrl, sourceCodeVersion: this.source.codeRepository!.sourceCodeVersion, }; } private renderCodeConfigurationValues(props: CodeConfigurationValues): any { this.environment = props.environment; return { port: props.port, buildCommand: props.buildCommand, runtime: props.runtime.name, runtimeEnvironmentVariables: this.renderEnvironmentVariables(), startCommand: props.startCommand, }; } private renderImageRepository(): any { const repo = this.source.imageRepository!; this.environment = repo.imageConfiguration?.environment; return Object.assign(repo, { imageConfiguration: { port: repo.imageConfiguration?.port?.toString(), startCommand: repo.imageConfiguration?.startCommand, runtimeEnvironmentVariables: this.renderEnvironmentVariables(), }, }); } private renderEnvironmentVariables(): EnvironmentVariable[] | undefined { if (this.environment) { let env: EnvironmentVariable[] = []; for (const [key, value] of Object.entries(this.environment)) { if (key.startsWith('AWSAPPRUNNER')) { throw new Error(`Environment variable key ${key} with a prefix of AWSAPPRUNNER is not allowed`); } env.push({ name: key, value: value }); } return env; } else { return undefined; } } private generateDefaultRole(): iam.Role { const accessRole = new iam.Role(this, 'AccessRole', { assumedBy: new iam.ServicePrincipal('build.apprunner.amazonaws.com'), }); accessRole.addToPrincipalPolicy(new iam.PolicyStatement({ actions: ['ecr:GetAuthorizationToken'], resources: ['*'], })); this.accessRole = accessRole; return accessRole; } }
the_stack
import { Provider, TransactionResponse } from '@ethersproject/abstract-provider' import { EtherscanProvider, getDefaultProvider } from '@ethersproject/providers' import { Address, Balance, BaseXChainClient, FeeOption, FeeType, Fees, Network, Tx, TxHash, TxHistoryParams, TxParams, TxsPage, XChainClient, XChainClientParams, standardFeeRates, } from '@xchainjs/xchain-client' import { Asset, AssetETH, BaseAmount, Chain, assetToString, baseAmount, delay } from '@xchainjs/xchain-util' import { BigNumber, BigNumberish, Wallet, ethers } from 'ethers' import { HDNode, parseUnits, toUtf8Bytes } from 'ethers/lib/utils' import erc20ABI from './data/erc20.json' import * as etherscanAPI from './etherscan-api' import * as ethplorerAPI from './ethplorer-api' import { ApproveParams, CallParams, EstimateApproveParams, EstimateCallParams, EthNetwork, ExplorerUrl, FeesWithGasPricesAndLimits, GasOracleResponse, GasPrices, InfuraCreds, IsApprovedParams, TxOverrides, } from './types' import { BASE_TOKEN_GAS_COST, ETHAddress, ETH_DECIMAL, MAX_APPROVAL, SIMPLE_GAS_COST, getDefaultGasPrices, getFee, getTokenAddress, getTokenBalances, getTxFromEthplorerEthTransaction, getTxFromEthplorerTokenOperation, validateAddress, xchainNetworkToEths, } from './utils' /** * Interface for custom Ethereum client */ export interface EthereumClient { call<T>(params: CallParams): Promise<T> estimateCall(asset: EstimateCallParams): Promise<BigNumber> estimateGasPrices(): Promise<GasPrices> estimateGasLimit(params: TxParams): Promise<BigNumber> estimateFeesWithGasPricesAndLimits(params: TxParams): Promise<FeesWithGasPricesAndLimits> estimateApprove(params: EstimateApproveParams): Promise<BigNumber> isApproved(params: IsApprovedParams): Promise<boolean> approve(params: ApproveParams): Promise<TransactionResponse> // `getFees` of `BaseXChainClient` needs to be overridden getFees(params: TxParams): Promise<Fees> } export type EthereumClientParams = XChainClientParams & { ethplorerUrl?: string ethplorerApiKey?: string explorerUrl?: ExplorerUrl etherscanApiKey?: string infuraCreds?: InfuraCreds } /** * Custom Ethereum client */ export default class Client extends BaseXChainClient implements XChainClient, EthereumClient { private ethNetwork: EthNetwork private hdNode!: HDNode private etherscanApiKey?: string private explorerUrl: ExplorerUrl private infuraCreds: InfuraCreds | undefined private ethplorerUrl: string private ethplorerApiKey: string private providers: Map<Network, Provider> = new Map<Network, Provider>() /** * Constructor * @param {EthereumClientParams} params */ constructor({ network = Network.Testnet, ethplorerUrl = 'https://api.ethplorer.io', ethplorerApiKey = 'freekey', explorerUrl, phrase = '', rootDerivationPaths = { [Network.Mainnet]: `m/44'/60'/0'/0/`, [Network.Testnet]: `m/44'/60'/0'/0/`, // this is INCORRECT but makes the unit tests pass }, etherscanApiKey, infuraCreds, }: EthereumClientParams) { super(Chain.Ethereum, { network, rootDerivationPaths }) this.ethNetwork = xchainNetworkToEths(network) this.rootDerivationPaths = rootDerivationPaths this.infuraCreds = infuraCreds this.etherscanApiKey = etherscanApiKey this.ethplorerUrl = ethplorerUrl this.ethplorerApiKey = ethplorerApiKey this.explorerUrl = explorerUrl || this.getDefaultExplorerURL() this.setupProviders() this.setPhrase(phrase) } /** * Purge client. * * @returns {void} */ purgeClient(): void { super.purgeClient() this.hdNode = HDNode.fromMnemonic('') } /** * Set/Update the explorer url. * * @param {string} url The explorer url. * @returns {void} */ setExplorerURL(url: ExplorerUrl): void { this.explorerUrl = url } /** * Get the current address. * * @param {number} walletIndex (optional) HD wallet index * @returns {Address} The current address. * * @throws {"Phrase must be provided"} * Thrown if phrase has not been set before. A phrase is needed to create a wallet and to derive an address from it. */ getAddress(walletIndex = 0): Address { if (walletIndex < 0) { throw new Error('index must be greater than zero') } return this.hdNode.derivePath(this.getFullDerivationPath(walletIndex)).address.toLowerCase() } /** * Get etherjs wallet interface. * * @param {number} walletIndex (optional) HD wallet index * @returns {Wallet} The current etherjs wallet interface. * * @throws {"Phrase must be provided"} * Thrown if phrase has not been set before. A phrase is needed to create a wallet and to derive an address from it. */ getWallet(walletIndex = 0): ethers.Wallet { return new Wallet(this.hdNode.derivePath(this.getFullDerivationPath(walletIndex))).connect(this.getProvider()) } setupProviders(): void { if (this.infuraCreds) { // Infura provider takes either a string of project id // or an object of id and secret const testnetProvider = this.infuraCreds.projectSecret ? new ethers.providers.InfuraProvider(EthNetwork.Test, this.infuraCreds) : new ethers.providers.InfuraProvider(EthNetwork.Test, this.infuraCreds.projectId) const mainnetProvider = this.infuraCreds.projectSecret ? new ethers.providers.InfuraProvider(EthNetwork.Main, this.infuraCreds) : new ethers.providers.InfuraProvider(EthNetwork.Main, this.infuraCreds.projectId) this.providers.set(Network.Testnet, testnetProvider) this.providers.set(Network.Mainnet, mainnetProvider) } else { this.providers.set(Network.Testnet, getDefaultProvider(EthNetwork.Test)) this.providers.set(Network.Mainnet, getDefaultProvider(EthNetwork.Main)) } } /** * Get etherjs Provider interface. * * @returns {Provider} The current etherjs Provider interface. */ getProvider(): Provider { return this.providers.get(this.network) || getDefaultProvider(this.network) } /** * Get etherjs EtherscanProvider interface. * * @returns {EtherscanProvider} The current etherjs EtherscanProvider interface. */ getEtherscanProvider(): EtherscanProvider { return new EtherscanProvider(this.ethNetwork, this.etherscanApiKey) } /** * Get the explorer url. * * @returns {string} The explorer url for ethereum based on the current network. */ getExplorerUrl(): string { return this.getExplorerUrlByNetwork(this.getNetwork()) } /** * Get the explorer url. * * @returns {ExplorerUrl} The explorer url (both mainnet and testnet) for ethereum. */ private getDefaultExplorerURL(): ExplorerUrl { return { [Network.Testnet]: 'https://ropsten.etherscan.io', [Network.Mainnet]: 'https://etherscan.io', } } /** * Get the explorer url. * * @param {Network} network * @returns {string} The explorer url for ethereum based on the network. */ private getExplorerUrlByNetwork(network: Network): string { return this.explorerUrl[network] } /** * Get the explorer url for the given address. * * @param {Address} address * @returns {string} The explorer url for the given address. */ getExplorerAddressUrl(address: Address): string { return `${this.getExplorerUrl()}/address/${address}` } /** * Get the explorer url for the given transaction id. * * @param {string} txID * @returns {string} The explorer url for the given transaction id. */ getExplorerTxUrl(txID: string): string { return `${this.getExplorerUrl()}/tx/${txID}` } /** * Set/update the current network. * * @param {Network} network * @returns {void} * * @throws {"Network must be provided"} * Thrown if network has not been set before. */ setNetwork(network: Network): void { super.setNetwork(network) this.ethNetwork = xchainNetworkToEths(network) } /** * Set/update a new phrase (Eg. If user wants to change wallet) * * @param {string} phrase A new phrase. * @param {number} walletIndex (optional) HD wallet index * @returns {Address} The address from the given phrase * * @throws {"Invalid phrase"} * Thrown if the given phase is invalid. */ setPhrase(phrase: string, walletIndex = 0): Address { this.hdNode = HDNode.fromMnemonic(phrase) return super.setPhrase(phrase, walletIndex) } /** * Validate the given address. * * @param {Address} address * @returns {boolean} `true` or `false` */ validateAddress(address: Address): boolean { return validateAddress(address) } /** * Get the ETH balance of a given address. * * @param {Address} address By default, it will return the balance of the current wallet. (optional) * @returns {Balance[]} The all balance of the address. * * @throws {"Invalid asset"} throws when the give asset is an invalid one */ async getBalance(address: Address, assets?: Asset[]): Promise<Balance[]> { const ethAddress = address || this.getAddress() // get ETH balance directly from provider const ethBalance: BigNumber = await this.getProvider().getBalance(ethAddress) const ethBalanceAmount = baseAmount(ethBalance.toString(), ETH_DECIMAL) switch (this.getNetwork()) { case Network.Mainnet: { // use ethplorerAPI for mainnet - ignore assets const account = await ethplorerAPI.getAddress(this.ethplorerUrl, address, this.ethplorerApiKey) const balances: Balance[] = [ { asset: AssetETH, amount: ethBalanceAmount, }, ] if (account.tokens) { balances.push(...getTokenBalances(account.tokens)) } return balances } case Network.Testnet: { // use etherscan for testnet const newAssets = assets || [AssetETH] // Follow approach is only for testnet // For mainnet, we will use ethplorer api(one request only) // https://github.com/xchainjs/xchainjs-lib/issues/252 // And to avoid etherscan api call limit, it gets balances in a sequence way, not in parallel const balances = [] for (let i = 0; i < newAssets.length; i++) { const asset = newAssets[i] const etherscan = this.getEtherscanProvider() if (assetToString(asset) !== assetToString(AssetETH)) { // Handle token balances const assetAddress = getTokenAddress(asset) if (!assetAddress) { throw new Error(`Invalid asset ${asset}`) } const balance = await etherscanAPI.getTokenBalance({ baseUrl: etherscan.baseUrl, address, assetAddress, apiKey: etherscan.apiKey, }) const decimals = BigNumber.from( await this.call<BigNumberish>({ contractAddress: assetAddress, abi: erc20ABI, funcName: 'decimals' }), ).toNumber() || ETH_DECIMAL if (!Number.isNaN(decimals)) { balances.push({ asset, amount: baseAmount(balance.toString(), decimals), }) } } else { balances.push({ asset: AssetETH, amount: ethBalanceAmount, }) } // Due to etherscan api call limitation, put some delay before another call // Free Etherscan api key limit: 5 calls per second // So 0.3s delay is reasonable for now await delay(300) } return balances } } } /** * Get transaction history of a given address with pagination options. * By default it will return the transaction history of the current wallet. * * @param {TxHistoryParams} params The options to get transaction history. (optional) * @returns {TxsPage} The transaction history. */ async getTransactions(params?: TxHistoryParams): Promise<TxsPage> { const offset = params?.offset || 0 const limit = params?.limit || 10 const assetAddress = params?.asset const maxCount = 10000 let transations const etherscan = this.getEtherscanProvider() if (assetAddress) { transations = await etherscanAPI.getTokenTransactionHistory({ baseUrl: etherscan.baseUrl, address: params?.address, assetAddress, page: 0, offset: maxCount, apiKey: etherscan.apiKey, }) } else { transations = await etherscanAPI.getETHTransactionHistory({ baseUrl: etherscan.baseUrl, address: params?.address, page: 0, offset: maxCount, apiKey: etherscan.apiKey, }) } return { total: transations.length, txs: transations.filter((_, index) => index >= offset && index < offset + limit), } } /** * Get the transaction details of a given transaction id. * * @param {string} txId The transaction id. * @param {string} assetAddress The asset address. (optional) * @returns {Tx} The transaction details of the given transaction id. * * @throws {"Need to provide valid txId"} * Thrown if the given txId is invalid. */ async getTransactionData(txId: string, assetAddress?: Address): Promise<Tx> { switch (this.getNetwork()) { case Network.Mainnet: { // use ethplorerAPI for mainnet - ignore assetAddress const txInfo = await ethplorerAPI.getTxInfo(this.ethplorerUrl, txId, this.ethplorerApiKey) if (!txInfo.operations?.length) return getTxFromEthplorerEthTransaction(txInfo) const tx = getTxFromEthplorerTokenOperation(txInfo.operations[0]) if (!tx) throw new Error('Could not parse transaction data') return tx } case Network.Testnet: { let tx const etherscan = this.getEtherscanProvider() const txInfo = await etherscan.getTransaction(txId) if (txInfo) { if (assetAddress) { tx = ( await etherscanAPI.getTokenTransactionHistory({ baseUrl: etherscan.baseUrl, assetAddress, startblock: txInfo.blockNumber, endblock: txInfo.blockNumber, apiKey: etherscan.apiKey, }) ).filter((info) => info.hash === txId)[0] ?? null } else { tx = ( await etherscanAPI.getETHTransactionHistory({ baseUrl: etherscan.baseUrl, startblock: txInfo.blockNumber, endblock: txInfo.blockNumber, apiKey: etherscan.apiKey, address: txInfo.from, }) ).filter((info) => info.hash === txId)[0] ?? null } } if (!tx) throw new Error('Could not get transaction history') return tx } } } /** * Call a contract function. * @template T The result interface. * @param {number} walletIndex (optional) HD wallet index * @param {Address} contractAddress The contract address. * @param {ContractInterface} abi The contract ABI json. * @param {string} funcName The function to be called. * @param {any[]} funcParams The parameters of the function. * @returns {T} The result of the contract function call. * * @throws {"contractAddress must be provided"} * Thrown if the given contract address is empty. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any async call<T>({ walletIndex = 0, contractAddress, abi, funcName, funcParams = [] }: CallParams): Promise<T> { if (!contractAddress) throw new Error('contractAddress must be provided') const contract = new ethers.Contract(contractAddress, abi, this.getProvider()).connect(this.getWallet(walletIndex)) return contract[funcName](...funcParams) } /** * Call a contract function. * @param {Address} contractAddress The contract address. * @param {ContractInterface} abi The contract ABI json. * @param {string} funcName The function to be called. * @param {any[]} funcParams The parameters of the function. * @param {number} walletIndex (optional) HD wallet index * @returns {BigNumber} The result of the contract function call. * * @throws {"contractAddress must be provided"} * Thrown if the given contract address is empty. */ async estimateCall({ contractAddress, abi, funcName, funcParams = [], walletIndex = 0, }: EstimateCallParams): Promise<BigNumber> { if (!contractAddress) throw new Error('contractAddress must be provided') const contract = new ethers.Contract(contractAddress, abi, this.getProvider()).connect(this.getWallet(walletIndex)) return contract.estimateGas[funcName](...funcParams) } /** * Check allowance. * * @param {Address} contractAddress The spender address. * @param {Address} spenderAddress The spender address. * @param {BaseAmount} amount The amount to check if it's allowed to spend or not (optional). * @param {number} walletIndex (optional) HD wallet index * @returns {boolean} `true` or `false`. */ async isApproved({ contractAddress, spenderAddress, amount, walletIndex = 0 }: IsApprovedParams): Promise<boolean> { // since amount is optional, set it to smallest amount by default const txAmount = BigNumber.from(amount?.amount().toFixed() ?? 1) const owner = this.getAddress(walletIndex) const allowance = await this.call<BigNumberish>({ contractAddress, abi: erc20ABI, funcName: 'allowance', funcParams: [owner, spenderAddress], }) return txAmount.lte(allowance) } /** * Check allowance. * * @param {Address} contractAddress The contract address. * @param {Address} spenderAddress The spender address. * @param {feeOptionKey} FeeOption Fee option (optional) * @param {BaseAmount} amount The amount of token. By default, it will be unlimited token allowance. (optional) * @param {number} walletIndex (optional) HD wallet index * * @returns {TransactionResponse} The transaction result. */ async approve({ contractAddress, spenderAddress, feeOptionKey: feeOption = FeeOption.Fastest, amount, walletIndex = 0, gasLimitFallback, }: ApproveParams): Promise<TransactionResponse> { const gasPrice = BigNumber.from( ( await this.estimateGasPrices() .then((prices) => prices[feeOption]) .catch(() => getDefaultGasPrices()[feeOption]) ) .amount() .toFixed(), ) const gasLimit = await this.estimateApprove({ walletIndex, spenderAddress, contractAddress, amount, }).catch(() => BigNumber.from(gasLimitFallback)) const txAmount = amount ? BigNumber.from(amount.amount().toFixed()) : MAX_APPROVAL return await this.call<TransactionResponse>({ walletIndex, contractAddress, abi: erc20ABI, funcName: 'approve', funcParams: [spenderAddress, txAmount, { from: this.getAddress(walletIndex), gasPrice, gasLimit }], }) } /** * Estimate gas limit of approve. * * @param {Address} contractAddress The contract address. * @param {Address} spenderAddress The spender address. * @param {number} walletIndex (optional) HD wallet index * @param {BaseAmount} amount The amount of token. By default, it will be unlimited token allowance. (optional) * @returns {BigNumber} The estimated gas limit. */ async estimateApprove({ contractAddress, spenderAddress, walletIndex = 0, amount, }: EstimateApproveParams): Promise<BigNumber> { const txAmount = amount ? BigNumber.from(amount.amount().toFixed()) : MAX_APPROVAL const gasLimit = await this.estimateCall({ walletIndex, contractAddress, abi: erc20ABI, funcName: 'approve', funcParams: [spenderAddress, txAmount, { from: this.getAddress(walletIndex) }], }) return gasLimit } /** * Transfer ETH. * * @param {TxParams} params The transfer options. * @param {feeOptionKey} FeeOption Fee option (optional) * @param {gasPrice} BaseAmount Gas price (optional) * @param {gasLimit} BigNumber Gas limit (optional) * * A given `feeOptionKey` wins over `gasPrice` and `gasLimit` * * @returns {TxHash} The transaction hash. */ async transfer({ walletIndex = 0, asset, memo, amount, recipient, feeOptionKey: feeOption, gasPrice, gasLimit, }: TxParams & { feeOptionKey?: FeeOption gasPrice?: BaseAmount gasLimit?: BigNumber }): Promise<TxHash> { const txAmount = BigNumber.from(amount.amount().toFixed()) let assetAddress if (asset && assetToString(asset) !== assetToString(AssetETH)) { assetAddress = getTokenAddress(asset) } const isETHAddress = assetAddress === ETHAddress // feeOption const defaultGasLimit: ethers.BigNumber = isETHAddress ? SIMPLE_GAS_COST : BASE_TOKEN_GAS_COST let overrides: TxOverrides = { gasLimit: gasLimit || defaultGasLimit, gasPrice: gasPrice && BigNumber.from(gasPrice.amount().toFixed()), } // override `overrides` if `feeOption` is provided if (feeOption) { const gasPrice = await this.estimateGasPrices() .then((prices) => prices[feeOption]) .catch(() => getDefaultGasPrices()[feeOption]) const gasLimit = await this.estimateGasLimit({ asset, recipient, amount, memo }).catch(() => defaultGasLimit) overrides = { gasLimit, gasPrice: BigNumber.from(gasPrice.amount().toFixed()), } } let txResult if (assetAddress && !isETHAddress) { // Transfer ERC20 txResult = await this.call<TransactionResponse>({ walletIndex, contractAddress: assetAddress, abi: erc20ABI, funcName: 'transfer', funcParams: [recipient, txAmount, Object.assign({}, overrides)], }) } else { // Transfer ETH const transactionRequest = Object.assign( { to: recipient, value: txAmount }, { ...overrides, data: memo ? toUtf8Bytes(memo) : undefined, }, ) txResult = await this.getWallet().sendTransaction(transactionRequest) } return txResult.hash } /** * Estimate gas price. * @see https://etherscan.io/apis#gastracker * * @returns {GasPrices} The gas prices (average, fast, fastest) in `Wei` (`BaseAmount`) */ async estimateGasPrices(): Promise<GasPrices> { try { // Note: `rates` are in `gwei` // @see https://gitlab.com/thorchain/thornode/-/blob/develop/x/thorchain/querier.go#L416-420 // To have all values in `BaseAmount`, they needs to be converted into `wei` (1 gwei = 1,000,000,000 wei = 1e9) const ratesInGwei = standardFeeRates(await this.getFeeRateFromThorchain()) return { [FeeOption.Average]: baseAmount(ratesInGwei[FeeOption.Average] * 10 ** 9, ETH_DECIMAL), [FeeOption.Fast]: baseAmount(ratesInGwei[FeeOption.Fast] * 10 ** 9, ETH_DECIMAL), [FeeOption.Fastest]: baseAmount(ratesInGwei[FeeOption.Fastest] * 10 ** 9, ETH_DECIMAL), } } catch (error) {} //should only get here if thor fails try { return await this.estimateGasPricesFromEtherscan() } catch (error) { return Promise.reject(new Error(`Failed to estimate gas price: ${error.msg ?? error.toString()}`)) } } /** * Estimate gas price. * @see https://etherscan.io/apis#gastracker * * @returns {GasPrices} The gas prices (average, fast, fastest) in `Wei` (`BaseAmount`) * * @throws {"Failed to estimate gas price"} Thrown if failed to estimate gas price. */ async estimateGasPricesFromEtherscan(): Promise<GasPrices> { const etherscan = this.getEtherscanProvider() const response: GasOracleResponse = await etherscanAPI.getGasOracle(etherscan.baseUrl, etherscan.apiKey) // Convert result of gas prices: `Gwei` -> `Wei` const averageWei = parseUnits(response.SafeGasPrice, 'gwei') const fastWei = parseUnits(response.ProposeGasPrice, 'gwei') const fastestWei = parseUnits(response.FastGasPrice, 'gwei') return { average: baseAmount(averageWei.toString(), ETH_DECIMAL), fast: baseAmount(fastWei.toString(), ETH_DECIMAL), fastest: baseAmount(fastestWei.toString(), ETH_DECIMAL), } } /** * Estimate gas. * * @param {TxParams} params The transaction and fees options. * @returns {BaseAmount} The estimated gas fee. */ async estimateGasLimit({ asset, recipient, amount, memo }: TxParams): Promise<BigNumber> { const txAmount = BigNumber.from(amount.amount().toFixed()) let assetAddress if (asset && assetToString(asset) !== assetToString(AssetETH)) { assetAddress = getTokenAddress(asset) } let estimate if (assetAddress && assetAddress !== ETHAddress) { // ERC20 gas estimate const contract = new ethers.Contract(assetAddress, erc20ABI, this.getProvider()) estimate = await contract.estimateGas.transfer(recipient, txAmount, { from: this.getAddress(), }) } else { // ETH gas estimate const transactionRequest = { from: this.getAddress(), to: recipient, value: txAmount, data: memo ? toUtf8Bytes(memo) : undefined, } estimate = await this.getProvider().estimateGas(transactionRequest) } return estimate } /** * Estimate gas prices/limits (average, fast fastest). * * @param {TxParams} params * @returns {FeesWithGasPricesAndLimits} The estimated gas prices/limits. */ async estimateFeesWithGasPricesAndLimits(params: TxParams): Promise<FeesWithGasPricesAndLimits> { // gas prices const gasPrices = await this.estimateGasPrices() const { fast: fastGP, fastest: fastestGP, average: averageGP } = gasPrices // gas limits const gasLimit = await this.estimateGasLimit({ asset: params.asset, amount: params.amount, recipient: params.recipient, memo: params.memo, }) return { gasPrices, fees: { type: FeeType.PerByte, average: getFee({ gasPrice: averageGP, gasLimit }), fast: getFee({ gasPrice: fastGP, gasLimit }), fastest: getFee({ gasPrice: fastestGP, gasLimit }), }, gasLimit, } } /** * Get fees. * * @param {TxParams} params * @returns {Fees} The average/fast/fastest fees. * * @throws {"Failed to get fees"} Thrown if failed to get fees. */ getFees(): never getFees(params: TxParams): Promise<Fees> async getFees(params?: TxParams): Promise<Fees> { if (!params) throw new Error('Params need to be passed') const { fees } = await this.estimateFeesWithGasPricesAndLimits(params) return fees } } export { Client }
the_stack
* @packageDocumentation * @module asset */ import { EDITOR, TEST } from 'internal:constants'; import { ccclass, serializable } from 'cc.decorator'; import { TextureType, TextureInfo } from '../gfx'; import { ImageAsset } from './image-asset'; import { PresumedGFXTextureInfo, SimpleTexture } from './simple-texture'; import { ITexture2DCreateInfo, Texture2D } from './texture-2d'; import { legacyCC } from '../global-exports'; import { js } from '../utils/js'; import { builtinResMgr } from '../builtin/builtin-res-mgr'; export type ITextureCubeCreateInfo = ITexture2DCreateInfo; /** * @en The texture cube mipmap interface * @zh 立方体贴图的 Mipmap 接口。 */ interface ITextureCubeMipmap { front: ImageAsset; back: ImageAsset; left: ImageAsset; right: ImageAsset; top: ImageAsset; bottom: ImageAsset; } /** * @en The index for all faces of the cube * @zh 立方体每个面的约定索引。 */ enum FaceIndex { right = 0, left = 1, top = 2, bottom = 3, front = 4, back = 5, } /** * @en The texture cube asset. * Each mipmap level of a texture cube have 6 [[ImageAsset]], represents 6 faces of the cube. * @zh 立方体贴图资源。 * 立方体贴图资源的每个 Mipmap 层级都为 6 张 [[ImageAsset]],分别代表了立方体贴图的 6 个面。 */ @ccclass('cc.TextureCube') export class TextureCube extends SimpleTexture { public static FaceIndex = FaceIndex; @serializable isRGBE = false; /** * @en All levels of mipmap images, be noted, automatically generated mipmaps are not included. * When setup mipmap, the size of the texture and pixel format could be modified. * @zh 所有层级 Mipmap,注意,这里不包含自动生成的 Mipmap。 * 当设置 Mipmap 时,贴图的尺寸以及像素格式可能会改变。 */ get mipmaps () { return this._mipmaps; } set mipmaps (value) { this._mipmaps = value; this._setMipmapLevel(this._mipmaps.length); if (this._mipmaps.length > 0) { const imageAsset: ImageAsset = this._mipmaps[0].front; this.reset({ width: imageAsset.width, height: imageAsset.height, format: imageAsset.format, mipmapLevel: this._mipmaps.length, }); this._mipmaps.forEach((mipmap, level) => { _forEachFace(mipmap, (face, faceIndex) => { this._assignImage(face, level, faceIndex); }); }); } else { this.reset({ width: 0, height: 0, mipmapLevel: this._mipmaps.length, }); } } /** * @en Level 0 mipmap image. * Be noted, `this.image = img` equals `this.mipmaps = [img]`, * sets image will clear all previous mipmaps. * @zh 0 级 Mipmap。 * 注意,`this.image = img` 等价于 `this.mipmaps = [img]`, * 也就是说,通过 `this.image` 设置 0 级 Mipmap 时将隐式地清除之前的所有 Mipmap。 */ get image () { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; } set image (value) { this.mipmaps = value ? [value] : []; } /** * @en Create a texture cube with an array of [[Texture2D]] which represents 6 faces of the texture cube. * @zh 通过二维贴图数组指定每个 Mipmap 的每个面创建立方体贴图。 * @param textures Texture array, the texture count must be multiple of 6. Every 6 textures are 6 faces of a mipmap level. * The order should obey [[FaceIndex]] order. * @param out Output texture cube, if not given, will create a new texture cube. * @returns The created texture cube. * @example * ```ts * const textures = new Array<Texture2D>(6); * textures[TextureCube.FaceIndex.front] = frontImage; * textures[TextureCube.FaceIndex.back] = backImage; * textures[TextureCube.FaceIndex.left] = leftImage; * textures[TextureCube.FaceIndex.right] = rightImage; * textures[TextureCube.FaceIndex.top] = topImage; * textures[TextureCube.FaceIndex.bottom] = bottomImage; * const textureCube = TextureCube.fromTexture2DArray(textures); * ``` */ public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) { const mipmaps: ITextureCubeMipmap[] = []; const nMipmaps = textures.length / 6; for (let i = 0; i < nMipmaps; i++) { const x = i * 6; mipmaps.push({ front: textures[x + FaceIndex.front].image!, back: textures[x + FaceIndex.back].image!, left: textures[x + FaceIndex.left].image!, right: textures[x + FaceIndex.right].image!, top: textures[x + FaceIndex.top].image!, bottom: textures[x + FaceIndex.bottom].image!, }); } out = out || new TextureCube(); out.mipmaps = mipmaps; return out; } @serializable public _mipmaps: ITextureCubeMipmap[] = []; public onLoaded () { this.mipmaps = this._mipmaps; } /** * @en Reset the current texture with given size, pixel format and mipmap images. * After reset, the gfx resource will become invalid, you must use [[uploadData]] explicitly to upload the new mipmaps to GPU resources. * @zh 将当前贴图重置为指定尺寸、像素格式以及指定 mipmap 层级。重置后,贴图的像素数据将变为未定义。 * mipmap 图像的数据不会自动更新到贴图中,你必须显式调用 [[uploadData]] 来上传贴图数据。 * @param info The create information */ public reset (info: ITextureCubeCreateInfo) { this._width = info.width; this._height = info.height; this._setGFXFormat(info.format); this._setMipmapLevel(info.mipmapLevel || 1); this._tryReset(); } public updateMipmaps (firstLevel = 0, count?: number) { if (firstLevel >= this._mipmaps.length) { return; } const nUpdate = Math.min( count === undefined ? this._mipmaps.length : count, this._mipmaps.length - firstLevel, ); for (let i = 0; i < nUpdate; ++i) { const level = firstLevel + i; _forEachFace(this._mipmaps[level], (face, faceIndex) => { this._assignImage(face, level, faceIndex); }); } } /** * 销毁此贴图,清空所有 Mipmap 并释放占用的 GPU 资源。 */ public destroy () { this._mipmaps = []; return super.destroy(); } /** * @en Release used GPU resources. * @zh 释放占用的 GPU 资源。 * @deprecated please use [[destroy]] instead */ public releaseTexture () { this.mipmaps = []; } public _serialize (ctxForExporting: any): Record<string, unknown> | null { if (EDITOR || TEST) { return { base: super._serialize(ctxForExporting), rgbe: this.isRGBE, mipmaps: this._mipmaps.map((mipmap) => ((ctxForExporting && ctxForExporting._compressUuid) ? { front: EditorExtends.UuidUtils.compressUuid(mipmap.front._uuid, true), back: EditorExtends.UuidUtils.compressUuid(mipmap.back._uuid, true), left: EditorExtends.UuidUtils.compressUuid(mipmap.left._uuid, true), right: EditorExtends.UuidUtils.compressUuid(mipmap.right._uuid, true), top: EditorExtends.UuidUtils.compressUuid(mipmap.top._uuid, true), bottom: EditorExtends.UuidUtils.compressUuid(mipmap.bottom._uuid, true), } : { front: mipmap.front._uuid, back: mipmap.back._uuid, left: mipmap.left._uuid, right: mipmap.right._uuid, top: mipmap.top._uuid, bottom: mipmap.bottom._uuid, })), }; } return null; } public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) { const data = serializedData; super._deserialize(data.base, handle); this.isRGBE = data.rgbe; this._mipmaps = new Array(data.mipmaps.length); for (let i = 0; i < data.mipmaps.length; ++i) { // Prevent resource load failed this._mipmaps[i] = { front: new ImageAsset(), back: new ImageAsset(), left: new ImageAsset(), right: new ImageAsset(), top: new ImageAsset(), bottom: new ImageAsset(), }; const mipmap = data.mipmaps[i]; const imageAssetClassId = js._getClassId(ImageAsset); handle.result.push(this._mipmaps[i], `front`, mipmap.front, imageAssetClassId); handle.result.push(this._mipmaps[i], `back`, mipmap.back, imageAssetClassId); handle.result.push(this._mipmaps[i], `left`, mipmap.left, imageAssetClassId); handle.result.push(this._mipmaps[i], `right`, mipmap.right, imageAssetClassId); handle.result.push(this._mipmaps[i], `top`, mipmap.top, imageAssetClassId); handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom, imageAssetClassId); } } protected _getGfxTextureCreateInfo (presumed: PresumedGFXTextureInfo): TextureInfo { const texInfo = new TextureInfo(TextureType.CUBE); texInfo.width = this._width; texInfo.height = this._height; texInfo.layerCount = 6; Object.assign(texInfo, presumed); return texInfo; } public initDefault (uuid?: string) { super.initDefault(uuid); const imageAsset = new ImageAsset(); imageAsset.initDefault(); this.mipmaps = [{ front: imageAsset, back: imageAsset, top: imageAsset, bottom: imageAsset, left: imageAsset, right: imageAsset, }]; } public validate () { return this._mipmaps.length !== 0 && !this._mipmaps.find((x) => !(x.top && x.bottom && x.front && x.back && x.left && x.right)); } } legacyCC.TextureCube = TextureCube; interface ITextureCubeSerializeData { base: string; rgbe: boolean; mipmaps: { front: string; back: string; left: string; right: string; top: string; bottom: string; }[]; } /** * @param {Mipmap} mipmap * @param {(face: ImageAsset) => void} callback */ function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void) { callback(mipmap.front, FaceIndex.front); callback(mipmap.back, FaceIndex.back); callback(mipmap.left, FaceIndex.left); callback(mipmap.right, FaceIndex.right); callback(mipmap.top, FaceIndex.top); callback(mipmap.bottom, FaceIndex.bottom); }
the_stack
import React from 'react'; import axios from 'axios'; import {Table, Icon, Tooltip} from 'antd'; import {PaginationConfig} from 'antd/lib/pagination'; import moment from 'moment'; import {ReplicationIcon} from 'utils/themeIcons'; import StorageBar from 'components/storageBar/storageBar'; import { DatanodeState, DatanodeStateList, DatanodeOpState, DatanodeOpStateList, IStorageReport } from 'types/datanode.types'; import './datanodes.less'; import {AutoReloadHelper} from 'utils/autoReloadHelper'; import AutoReloadPanel from 'components/autoReloadPanel/autoReloadPanel'; import {MultiSelect, IOption} from 'components/multiSelect/multiSelect'; import {ActionMeta, ValueType} from 'react-select'; import {showDataFetchError} from 'utils/common'; import {ColumnSearch} from 'utils/columnSearch'; interface IDatanodeResponse { hostname: string; state: DatanodeState; opState: DatanodeOpState; lastHeartbeat: number; storageReport: IStorageReport; pipelines: IPipeline[]; containers: number; openContainers: number; leaderCount: number; uuid: string; version: string; setupTime: number; revision: string; buildDate: string; } interface IDatanodesResponse { totalCount: number; datanodes: IDatanodeResponse[]; } interface IDatanode { hostname: string; state: DatanodeState; opState: DatanodeOpState; lastHeartbeat: number; storageUsed: number; storageTotal: number; storageRemaining: number; pipelines: IPipeline[]; containers: number; openContainers: number; leaderCount: number; uuid: string; version: string; setupTime: number; revision: string; buildDate: string; } interface IPipeline { pipelineID: string; replicationType: string; replicationFactor: string; leaderNode: string; } interface IDatanodesState { loading: boolean; dataSource: IDatanode[]; totalCount: number; lastUpdated: number; selectedColumns: IOption[]; columnOptions: IOption[]; } const renderDatanodeState = (state: DatanodeState) => { const stateIconMap = { HEALTHY: <Icon type='check-circle' theme='filled' twoToneColor='#1da57a' className='icon-success'/>, STALE: <Icon type='hourglass' theme='filled' className='icon-warning'/>, DEAD: <Icon type='close-circle' theme='filled' className='icon-failure'/> }; const icon = state in stateIconMap ? stateIconMap[state] : ''; return <span>{icon} {state}</span>; }; const renderDatanodeOpState = (opState: DatanodeOpState) => { const opStateIconMap = { IN_SERVICE: <Icon type='check-circle' theme='outlined' twoToneColor='#1da57a' className='icon-success'/>, DECOMMISSIONING: <Icon type='hourglass' theme='outlined' className='icon-warning'/>, DECOMMISSIONED: <Icon type='warning' theme='outlined' className='icon-warning'/>, ENTERING_MAINTENANCE: <Icon type='hourglass' theme='outlined' className='icon-warning'/>, IN_MAINTENANCE: <Icon type='warning' theme='outlined' className='icon-warning'/> }; const icon = opState in opStateIconMap ? opStateIconMap[opState] : ''; return <span>{icon} {opState}</span>; }; const COLUMNS = [ { title: 'State', dataIndex: 'state', key: 'state', isVisible: true, filterMultiple: true, filters: DatanodeStateList.map(state => ({text: state, value: state})), onFilter: (value: DatanodeState, record: IDatanode) => record.state === value, render: (text: DatanodeState) => renderDatanodeState(text), sorter: (a: IDatanode, b: IDatanode) => a.state.localeCompare(b.state), fixed: 'left' }, { title: 'Operational State', dataIndex: 'opState', key: 'opState', isVisible: true, filterMultiple: true, filters: DatanodeOpStateList.map(state => ({text: state, value: state})), onFilter: (value: DatanodeOpState, record: IDatanode) => record.opState === value, render: (text: DatanodeOpState) => renderDatanodeOpState(text), sorter: (a: IDatanode, b: IDatanode) => a.opState.localeCompare(b.opState), fixed: 'left' }, { title: 'Hostname', dataIndex: 'hostname', key: 'hostname', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.hostname.localeCompare(b.hostname), defaultSortOrder: 'ascend' as const, fixed: 'left' }, { title: 'Uuid', dataIndex: 'uuid', key: 'uuid', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.uuid.localeCompare(b.uuid), defaultSortOrder: 'ascend' as const }, { title: 'Storage Capacity', dataIndex: 'storageUsed', key: 'storageUsed', isVisible: true, sorter: (a: IDatanode, b: IDatanode) => a.storageRemaining - b.storageRemaining, render: (text: string, record: IDatanode) => ( <StorageBar total={record.storageTotal} used={record.storageUsed} remaining={record.storageRemaining}/> )}, { title: 'Last Heartbeat', dataIndex: 'lastHeartbeat', key: 'lastHeartbeat', isVisible: true, sorter: (a: IDatanode, b: IDatanode) => a.lastHeartbeat - b.lastHeartbeat, render: (heartbeat: number) => { return heartbeat > 0 ? moment(heartbeat).format('ll LTS') : 'NA'; } }, { title: 'Pipeline ID(s)', dataIndex: 'pipelines', key: 'pipelines', isVisible: true, render: (pipelines: IPipeline[], record: IDatanode) => { return ( <div> { pipelines.map((pipeline, index) => ( <div key={index} className='pipeline-container'> <ReplicationIcon replicationFactor={pipeline.replicationFactor} replicationType={pipeline.replicationType} leaderNode={pipeline.leaderNode} isLeader={pipeline.leaderNode === record.hostname}/> {pipeline.pipelineID} </div> )) } </div> ); } }, { title: <span> Leader Count&nbsp; <Tooltip title='The number of Ratis Pipelines in which the given datanode is elected as a leader.'> <Icon type='info-circle'/> </Tooltip> </span>, dataIndex: 'leaderCount', key: 'leaderCount', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.leaderCount - b.leaderCount }, { title: 'Containers', dataIndex: 'containers', key: 'containers', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.containers - b.containers }, { title: 'Open Containers', dataIndex: 'openContainers', key: 'openContainers', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.openContainers - b.openContainers }, { title: 'Version', dataIndex: 'version', key: 'version', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.version.localeCompare(b.version), defaultSortOrder: 'ascend' as const }, { title: 'SetupTime', dataIndex: 'setupTime', key: 'setupTime', isVisible: true, sorter: (a: IDatanode, b: IDatanode) => a.setupTime - b.setupTime, render: (uptime: number) => { return uptime > 0 ? moment(uptime).format('ll LTS') : 'NA'; } }, { title: 'Revision', dataIndex: 'revision', key: 'revision', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.revision.localeCompare(b.revision), defaultSortOrder: 'ascend' as const }, { title: 'BuildDate', dataIndex: 'buildDate', key: 'buildDate', isVisible: true, isSearchable: true, sorter: (a: IDatanode, b: IDatanode) => a.buildDate.localeCompare(b.buildDate), defaultSortOrder: 'ascend' as const } ]; const allColumnsOption: IOption = { label: 'Select all', value: '*' }; const defaultColumns: IOption[] = COLUMNS.map(column => ({ label: column.key, value: column.key })); export class Datanodes extends React.Component<Record<string, object>, IDatanodesState> { autoReload: AutoReloadHelper; constructor(props = {}) { super(props); this.state = { loading: false, dataSource: [], totalCount: 0, lastUpdated: 0, selectedColumns: [], columnOptions: defaultColumns }; this.autoReload = new AutoReloadHelper(this._loadData); } _handleColumnChange = (selected: ValueType<IOption>, _action: ActionMeta<IOption>) => { const selectedColumns = (selected as IOption[]); this.setState({ selectedColumns }); }; _getSelectedColumns = (selected: IOption[]) => { const selectedColumns = selected.length > 0 ? selected : COLUMNS.filter(column => column.isVisible).map(column => ({ label: column.key, value: column.key })); return selectedColumns; }; _loadData = () => { this.setState(prevState => ({ loading: true, selectedColumns: this._getSelectedColumns(prevState.selectedColumns) })); axios.get('/api/v1/datanodes').then(response => { const datanodesResponse: IDatanodesResponse = response.data; const totalCount = datanodesResponse.totalCount; const datanodes: IDatanodeResponse[] = datanodesResponse.datanodes; const dataSource: IDatanode[] = datanodes.map(datanode => { return { hostname: datanode.hostname, uuid: datanode.uuid, state: datanode.state, opState: datanode.opState, lastHeartbeat: datanode.lastHeartbeat, storageUsed: datanode.storageReport.used, storageTotal: datanode.storageReport.capacity, storageRemaining: datanode.storageReport.remaining, pipelines: datanode.pipelines, containers: datanode.containers, openContainers: datanode.openContainers, leaderCount: datanode.leaderCount, version: datanode.version, setupTime: datanode.setupTime, revision: datanode.revision, buildDate: datanode.buildDate }; }); this.setState({ loading: false, dataSource, totalCount, lastUpdated: Number(moment()) }); }).catch(error => { this.setState({ loading: false }); showDataFetchError(error.toString()); }); }; componentDidMount(): void { // Fetch datanodes on component mount this._loadData(); this.autoReload.startPolling(); } componentWillUnmount(): void { this.autoReload.stopPolling(); } onShowSizeChange = (current: number, pageSize: number) => { console.log(current, pageSize); }; render() { const {dataSource, loading, totalCount, lastUpdated, selectedColumns, columnOptions} = this.state; const paginationConfig: PaginationConfig = { showTotal: (total: number, range) => `${range[0]}-${range[1]} of ${total} datanodes`, showSizeChanger: true, onShowSizeChange: this.onShowSizeChange }; return ( <div className='datanodes-container'> <div className='page-header'> Datanodes ({totalCount}) <div className='filter-block'> <MultiSelect allowSelectAll isMulti maxShowValues={3} className='multi-select-container' options={columnOptions} closeMenuOnSelect={false} hideSelectedOptions={false} value={selectedColumns} allOption={allColumnsOption} onChange={this._handleColumnChange} /> Columns </div> <AutoReloadPanel isLoading={loading} lastUpdated={lastUpdated} togglePolling={this.autoReload.handleAutoReloadToggle} onReload={this._loadData} /> </div> <div className='content-div'> <Table dataSource={dataSource} columns={COLUMNS.reduce<any[]>((filtered, column) => { if (selectedColumns.some(e => e.value === column.key)) { if (column.isSearchable) { const newColumn = { ...column, ...new ColumnSearch(column).getColumnSearchProps(column.dataIndex) }; filtered.push(newColumn); } else { filtered.push(column); } } return filtered; }, [])} loading={loading} pagination={paginationConfig} rowKey='hostname' scroll={{x: true, y: false, scrollToFirstRowOnChange: true}} /> </div> </div> ); } }
the_stack
/// <reference path="core/ResourceItem.ts" /> /// <reference path="core/ResourceConfig.ts" /> /// <reference path="core/ResourceLoader.ts" /> /// <reference path="events/ResourceEvent.ts" /> /// <reference path="analyzer/BinAnalyzer.ts" /> /// <reference path="analyzer/ImageAnalyzer.ts" /> /// <reference path="analyzer/TextAnalyzer.ts" /> /// <reference path="analyzer/JsonAnalyzer.ts" /> /// <reference path="analyzer/SheetAnalyzer.ts" /> /// <reference path="analyzer/FontAnalyzer.ts" /> /// <reference path="analyzer/SoundAnalyzer.ts" /> /// <reference path="analyzer/XMLAnalyzer.ts" /> /// <reference path="version/IVersionController.ts" /> /// <reference path="version/Html5VersionController.ts" /> namespace RES { /** * Conduct mapping injection with class definition as the value. * @param type Injection type. * @param analyzerClass Injection type classes need to be resolved. * @version Egret 2.4 * @platform Web,Native * @includeExample extension/resource/Resource.ts * @language en_US */ /** * 以类定义为值进行映射注入。 * @param type 注入的类型。 * @param analyzerClass 注入类型需要解析的类。 * @version Egret 2.4 * @platform Web,Native * @includeExample extension/resource/Resource.ts * @language zh_CN */ export function registerAnalyzer(type:string, analyzerClass:any) { instance.registerAnalyzer(type, analyzerClass); } /** * Get mapping injection. * @param type Injection type. * @version Egret 3.2.6 * @platform Web,Native * @includeExample extension/resource/Resource.ts * @language en_US */ /** * 获取映射注入。 * @param type 注入的类型。 * @version Egret 3.2.6 * @platform Web,Native * @includeExample extension/resource/Resource.ts * @language zh_CN */ export function getAnalyzer(type:string):AnalyzerBase { return instance.$getAnalyzerByType(type); } /** * Register the VersionController * @param vcs The VersionController to register. * @version Egret 2.5 * @platform Web,Native * @language en_US */ /** * 注册版本控制器,通过RES模块加载资源时会从版本控制器获取真实url * @param vcs 注入的版本控制器。 * @version Egret 2.5 * @platform Web,Native * @language zh_CN */ export function registerVersionController(vcs:VersionController):void { instance.$registerVersionController(vcs); } /** * Returns the VersionController * @version Egret 2.5 * @platform Web,Native * @language en_US */ /** * 获得版本控制器. * @version Egret 2.5 * @platform Web,Native * @language zh_CN */ export function getVersionController():VersionController { return instance.vcs; } /** * Load configuration file and parse. * @param url Configuration file path (path resource.json). * @param resourceRoot Resource path. All URL in the configuration is the relative value of the path. The ultimate URL is the value of the sum of the URL of the string and the resource in the configuration. * @param type Configuration file format. Determine what parser to parse the configuration file. Default "json". * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 加载配置文件并解析。 * @param url 配置文件路径(resource.json的路径)。 * @param resourceRoot 资源根路径。配置中的所有url都是这个路径的相对值。最终url是这个字符串与配置里资源项的url相加的值。 * @param type 配置文件的格式。确定要用什么解析器来解析配置文件。默认"json" * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function loadConfig(url:string,resourceRoot:string="",type:string="json"):void{ instance.loadConfig(url,resourceRoot,type); } /** * Load a set of resources according to the group name. * @param name Group name to load the resource group. * @param priority Load priority can be negative, the default value is 0. * <br>A low priority group must wait for the high priority group to complete the end of the load to start, and the same priority group will be loaded at the same time. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 根据组名加载一组资源。 * @param name 要加载资源组的组名。 * @param priority 加载优先级,可以为负数,默认值为 0。 * <br>低优先级的组必须等待高优先级组完全加载结束才能开始,同一优先级的组会同时加载。 * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function loadGroup(name:string,priority:number=0):void{ instance.loadGroup(name,priority); } /** * Check whether a resource group has been loaded. * @param name Group name。 * @returns Is loading or not. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 检查某个资源组是否已经加载完成。 * @param name 组名。 * @returns 是否正在加载。 * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function isGroupLoaded(name:string):boolean{ return instance.isGroupLoaded(name); } /** * A list of groups of loading is obtained according to the group name. * @param name Group name. * @returns The resource item array of group. * @see RES.ResourceItem * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 根据组名获取组加载项列表。 * @param name 组名。 * @returns 加载项列表。 * @see RES.ResourceItem * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function getGroupByName(name:string):Array<ResourceItem>{ return instance.getGroupByName(name); } /** * Create a custom load resource group, note that this method is valid only after the resource configuration file is loaded. * <br>You can monitor the ResourceEvent.CONFIG_COMPLETE event to verify that the configuration is complete. * @param name Group name to create the load resource group. * @param keys To be included in the list of key keys, the corresponding configuration file in the name or sbuKeys property one or a resource group name. * @param override Is the default false for the same name resource group already exists. * @returns Create success or fail. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 创建自定义的加载资源组,注意:此方法仅在资源配置文件加载完成后执行才有效。 * <br>可以监听 ResourceEvent.CONFIG_COMPLETE 事件来确认配置加载完成。 * @param name 要创建的加载资源组的组名。 * @param keys 要包含的键名列表,key 对应配置文件里的 name 属性或 sbuKeys 属性的一项或一个资源组名。 * @param override 是否覆盖已经存在的同名资源组,默认 false。 * @returns 是否创建成功。 * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function createGroup(name:string,keys:string[],override:boolean = false):boolean{ return instance.createGroup(name,keys,override); } /** * Check whether the configuration file contains the specified resources. * @param key A sbuKeys attribute or name property in a configuration file. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 检查配置文件里是否含有指定的资源。 * @param key 对应配置文件里的 name 属性或 sbuKeys 属性的一项。 * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function hasRes(key:string):boolean{ return instance.hasRes(key); } /** * parse a configuration file at run time,it will not clean the exist data. * @param data Configuration file data, please refer to the resource.json configuration file format. JSON object can be introduced into the corresponding. * @param folder Path prefix for load. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 运行时动态解析一个配置文件,此操作不会清空之前已存在的配置。 * @param data 配置文件数据,请参考 resource.json 的配置文件格式。传入对应的 json 对象即可。 * @param folder 加载项的路径前缀。 * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function parseConfig(data:any, folder:string=""):void { instance.parseConfig(data,folder); } /** * The synchronization method for obtaining the cache has been loaded with the success of the resource. * <br>The type of resource and the corresponding return value types are as follows: * <br>RES.ResourceItem.TYPE_BIN : ArrayBuffer JavaScript primary object * <br>RES.ResourceItem.TYPE_IMAGE : img Html Object,or egret.BitmapData interface。 * <br>RES.ResourceItem.TYPE_JSON : Object * <br>RES.ResourceItem.TYPE_SHEET : Object * <br> 1. If the incoming parameter is the name of the entire SpriteSheet is returned is {image1: Texture, "image2": Texture}. * <br> 2. If the incoming is "sheet.image1", the return is a single resource. * <br> 3. If the incoming is the name of the "image1" single resource, the return is a single resource. * But if there are two SpriteSheet in a single picture of the same name, the return of the image after the load. * <br>RES.ResourceItem.TYPE_SOUND : HtmlSound Html Object * <br>RES.ResourceItem.TYPE_TEXT : string * @param key A subKeys attribute or name property in a configuration file. * @see RES.ResourceItem * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 同步方式获取缓存的已经加载成功的资源。 * <br>资源类型和对应的返回值类型关系如下: * <br>RES.ResourceItem.TYPE_BIN : ArrayBuffer JavaScript 原生对象 * <br>RES.ResourceItem.TYPE_IMAGE : img Html 对象,或者 egret.BitmapData 接口。 * <br>RES.ResourceItem.TYPE_JSON : Object * <br>RES.ResourceItem.TYPE_SHEET : Object * <br> 1. 如果传入的参数是整个 SpriteSheet 的名称返回的是 {"image1":Texture,"image2":Texture} 这样的格式。 * <br> 2. 如果传入的是 "sheet.image1",返回的是单个资源。 * <br> 3. 如果传入的是 "image1" 单个资源的名称,返回的是单个资源。但是如果有两张 SpriteSheet 中有单个图片资源名称相同,返回的是后加载的那个图片资源。 * <br>RES.ResourceItem.TYPE_SOUND : HtmlSound Html 对象 * <br>RES.ResourceItem.TYPE_TEXT : string * @param key 对应配置文件里的 name 属性或 subKeys 属性的一项。 * @see RES.ResourceItem * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function getRes(key:string):any{ return instance.getRes(key); } /** * Asynchronous mode to get the resources in the configuration. As long as the resources exist in the configuration file, you can get it in an asynchronous way. * @param key A sbuKeys attribute or name property in a configuration file. * @param compFunc Call back function. Example:compFunc(data,key):void. * @param thisObject This pointer of call back function. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 异步方式获取配置里的资源。只要是配置文件里存在的资源,都可以通过异步方式获取。 * @param key 对应配置文件里的 name 属性或 sbuKeys 属性的一项。 * @param compFunc 回调函数。示例:compFunc(data,key):void。 * @param thisObject 回调函数的 this 引用。 * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function getResAsync(key:string,compFunc:Function,thisObject:any):void{ instance.getResAsync(key,compFunc,thisObject); } /** * Access to external resources through the full URL. * @param url The external path to load the file. * @param compFunc Call back function. Example:compFunc(data,url):void。 * @param thisObject This pointer of call back function. * @param type File type (optional). Use the static constants defined in the ResourceItem class. If you do not set the file name extension. * @version Egret 2.4 * @platform Web,Native * @includeExample extension/resource/GetResByUrl.ts * @language en_US */ /** * 通过完整URL方式获取外部资源。 * @param url 要加载文件的外部路径。 * @param compFunc 回调函数。示例:compFunc(data,url):void。 * @param thisObject 回调函数的 this 引用。 * @param type 文件类型(可选)。请使用 ResourceItem 类中定义的静态常量。若不设置将根据文件扩展名生成。 * @version Egret 2.4 * @platform Web,Native * @includeExample extension/resource/GetResByUrl.ts * @language zh_CN */ export function getResByUrl(url:string,compFunc:Function,thisObject:any,type:string=""):void{ instance.getResByUrl(url,compFunc,thisObject,type); } /** * Destroy a single resource file or a set of resources to the cache data, to return whether to delete success. * @param name Name attribute or resource group name of the load item in the configuration file. * @param force Destruction of a resource group when the other resources groups have the same resource situation whether the resources will be deleted, the default value true. * @returns Are successful destruction. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 销毁单个资源文件或一组资源的缓存数据,返回是否删除成功。 * @param name 配置文件中加载项的name属性或资源组名。 * @param force 销毁一个资源组时其他资源组有同样资源情况资源是否会被删除,默认值 true。 * @see #setMaxRetryTimes * @returns 是否销毁成功。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function destroyRes(name:string, force?:boolean):boolean{ return instance.destroyRes(name, force); } /** * Sets the maximum number of concurrent load threads, the default value is 2. * @param thread The number of concurrent loads to be set. * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 设置最大并发加载线程数量,默认值是 2。 * @param thread 要设置的并发加载数。 * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function setMaxLoadingThread(thread:number):void{ instance.setMaxLoadingThread(thread); } /** * Sets the number of retry times when the resource failed to load, and the default value is 3. * @param retry To set the retry count. * @includeExample extension/resource/Resource.ts * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 设置资源加载失败时的重试次数,默认值是 3。 * @param retry 要设置的重试次数。 * @includeExample extension/resource/Resource.ts * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function setMaxRetryTimes(retry: number): void { instance.setMaxRetryTimes(retry); } /** * Add event listeners, reference ResourceEvent defined constants. * @param type Event name。 * @param listener Listener functions for handling events. This function must accept the Event object as its only parameter, and can't return any results, * As shown in the following example: function (evt:Event):void can have any name. * @param thisObject The this object that is bound to a function. * @param useCapture Determine the listener is running on the capture or running on the target and the bubbling phase. Set useCapture to true, * then the listener in the capture phase processing events, but not in the target or the bubbling phase processing events. * If useCapture is false, then the listener only in the target or the bubbling phase processing events. * To listen for events in all three stages, please call addEventListener two times: once the useCapture is set to true, once the useCapture is set to false. * @param priority Event listener priority. Priority is specified by a 32 - bit integer with a symbol. The higher the number, the higher the priority. * All listeners with a priority for n will be processed before the -1 n listener. * If two or more listeners share the same priority, they are processed in accordance with the order of their added. The default priority is 0. * @see RES.ResourceEvent * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 添加事件侦听器,参考 ResourceEvent 定义的常量。 * @param type 事件的类型。 * @param listener 处理事件的侦听器函数。此函数必须接受 Event 对象作为其唯一的参数,并且不能返回任何结果, * 如下面的示例所示: function(evt:Event):void 函数可以有任何名称。 * @param thisObject 侦听函数绑定的 this 对象。 * @param useCapture 确定侦听器是运行于捕获阶段还是运行于目标和冒泡阶段。如果将 useCapture 设置为 true, * 则侦听器只在捕获阶段处理事件,而不在目标或冒泡阶段处理事件。如果 useCapture 为 false,则侦听器只在目标或冒泡阶段处理事件。 * 要在所有三个阶段都侦听事件,请调用 addEventListener 两次:一次将 useCapture 设置为 true,一次将 useCapture 设置为 false。 * @param priority 事件侦听器的优先级。优先级由一个带符号的 32 位整数指定。数字越大,优先级越高。优先级为 n 的所有侦听器会在 * 优先级为 n -1 的侦听器之前得到处理。如果两个或更多个侦听器共享相同的优先级,则按照它们的添加顺序进行处理。默认优先级为 0。 * @see RES.ResourceEvent * @see #setMaxRetryTimes * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function addEventListener(type:string, listener:(event:egret.Event)=>void, thisObject:any, useCapture:boolean = false, priority:number = 0):void { instance.addEventListener(type,listener,thisObject,useCapture,priority); } /** * Remove event listeners, reference ResourceEvent defined constants. * @param type Event name。 * @param listener Listening function。 * @param thisObject The this object that is bound to a function. * @param useCapture Is used to capture, and this property is only valid in the display list. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 移除事件侦听器,参考ResourceEvent定义的常量。 * @param type 事件名。 * @param listener 侦听函数。 * @param thisObject 侦听函数绑定的this对象。 * @param useCapture 是否使用捕获,这个属性只在显示列表中生效。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export function removeEventListener(type:string, listener:(event:egret.Event)=>void,thisObject:any,useCapture:boolean = false):void { instance.removeEventListener(type,listener,thisObject,useCapture); } export function $getVirtualUrl(url){ if (instance.vcs){ return instance.vcs.getVirtualUrl(url); } else{ return url; } } /** * @internal */ class Resource extends egret.EventDispatcher{ /** * 构造函数 * @method RES.constructor * @private */ public constructor(){ super(); this.init(); } public vcs:VersionController; /** * 解析器字典 */ private analyzerDic:any = {}; private analyzerClassMap:any = {}; /** * 根据type获取对应的文件解析库 */ $getAnalyzerByType(type:string):AnalyzerBase{ let analyzer:AnalyzerBase = this.analyzerDic[type]; if (!analyzer) { let clazz = this.analyzerClassMap[type]; if (!clazz) { if (DEBUG) { egret.$error(3203, type); } return null; } analyzer = this.analyzerDic[type] = new clazz(); } return analyzer; } /** * 注册一个自定义文件类型解析器 * @param type 文件类型字符串,例如:bin,text,image,json等。 * @param analyzerClass 自定义解析器的类定义 */ public registerAnalyzer(type:string, analyzerClass:any):void { this.analyzerClassMap[type] = analyzerClass; } public $registerVersionController(vcs:VersionController){ this.vcs = vcs; } /** * 多文件队列加载器 */ private resLoader:ResourceLoader; /** * 初始化 */ private init():void{ this.vcs = new VersionController(); let analyzerClassMap = this.analyzerClassMap; analyzerClassMap[ResourceItem.TYPE_BIN] = BinAnalyzer; analyzerClassMap[ResourceItem.TYPE_IMAGE] = ImageAnalyzer; analyzerClassMap[ResourceItem.TYPE_TEXT] = TextAnalyzer; analyzerClassMap[ResourceItem.TYPE_JSON] = JsonAnalyzer; analyzerClassMap[ResourceItem.TYPE_SHEET] = SheetAnalyzer; analyzerClassMap[ResourceItem.TYPE_FONT] = FontAnalyzer; analyzerClassMap[ResourceItem.TYPE_SOUND] = SoundAnalyzer; analyzerClassMap[ResourceItem.TYPE_XML] = XMLAnalyzer; this.resConfig = new ResourceConfig(); this.resLoader = new ResourceLoader(); this.resLoader.callBack = this.onResourceItemComp; this.resLoader.resInstance = this; this.resLoader.addEventListener(ResourceEvent.GROUP_COMPLETE,this.onGroupComp,this); this.resLoader.addEventListener(ResourceEvent.GROUP_LOAD_ERROR,this.onGroupError,this); } /** * 配置文件组组名 */ private static GROUP_CONFIG:string = "RES__CONFIG"; private configItemList:any[] = []; private loadingConfigList:any[]; private callLaterFlag:boolean = false; /** * 配置文件加载解析完成标志 */ private configComplete:boolean = false; /** * 开始加载配置 * @method RES.loadConfig * @param url {string} * @param resourceRoot {string} * @param type {string} */ public loadConfig(url:string,resourceRoot:string,type:string="json"):void{ let configItem:any = {url:url,resourceRoot:resourceRoot,type:type}; this.configItemList.push(configItem); if(!this.callLaterFlag){ egret.callLater(this.startLoadConfig,this); this.callLaterFlag = true; } } private startLoadConfig():void{ this.callLaterFlag = false; let configList:any[] = this.configItemList; this.configItemList = []; this.loadingConfigList = configList; let length:number = configList.length; let itemList:Array<ResourceItem> = []; for(let i:number=0;i<length;i++){ let item:any = configList[i]; let resItem:ResourceItem = new ResourceItem(item.url,item.url,item.type); itemList.push(resItem); } let callback = { onSuccess:(data:any)=>{ this.resLoader.loadGroup(itemList,Resource.GROUP_CONFIG,Number.MAX_VALUE); }, onFail:(err:number,data:any)=>{ ResourceEvent.dispatchResourceEvent(this,ResourceEvent.CONFIG_LOAD_ERROR); } }; if (this.vcs){ this.vcs.fetchVersion(callback); } else{ this.resLoader.loadGroup(itemList,Resource.GROUP_CONFIG,Number.MAX_VALUE); } } /** * 已经加载过组名列表 */ private loadedGroups:string[] = []; /** * 检查某个资源组是否已经加载完成 * @method RES.isGroupLoaded * @param name {string} * @returns {boolean} */ public isGroupLoaded(name:string):boolean{ return this.loadedGroups.indexOf(name)!=-1; } /** * 根据组名获取组加载项列表 * @method RES.getGroupByName * @param name {string} * @returns {Array<egret.ResourceItem>} */ public getGroupByName(name:string):Array<ResourceItem>{ return this.resConfig.getGroupByName(name); } private groupNameList:any[] = []; /** * 根据组名加载一组资源 * @method RES.loadGroup * @param name {string} * @param priority {number} */ public loadGroup(name:string,priority:number=0):void{ if(this.loadedGroups.indexOf(name)!=-1){ ResourceEvent.dispatchResourceEvent(this,ResourceEvent.GROUP_COMPLETE,name); return; } if(this.resLoader.isGroupInLoading(name)) return; if(this.configComplete){ let group:Array<ResourceItem> = this.resConfig.getGroupByName(name); this.resLoader.loadGroup(group,name,priority); } else{ this.groupNameList.push({name:name,priority:priority}); } } /** * 创建自定义的加载资源组,注意:此方法仅在资源配置文件加载完成后执行才有效。 * 可以监听ResourceEvent.CONFIG_COMPLETE事件来确认配置加载完成。 * @method RES.ResourceConfig#createGroup * @param name {string} 要创建的加载资源组的组名 * @param keys {egret.string[]} 要包含的键名列表,key对应配置文件里的name属性或一个资源组名。 * @param override {boolean} 是否覆盖已经存在的同名资源组,默认false。 * @returns {boolean} */ public createGroup(name:string,keys:string[],override:boolean=false):boolean{ if(override){ let index:number = this.loadedGroups.indexOf(name); if(index!=-1){ this.loadedGroups.splice(index,1); } } return this.resConfig.createGroup(name,keys,override); } /** * res配置数据 */ private resConfig:ResourceConfig; /** * 队列加载完成事件 */ private onGroupComp(event:ResourceEvent):void{ if(event.groupName==Resource.GROUP_CONFIG){ let length:number = this.loadingConfigList.length; for(let i:number = 0;i < length;i++){ let config:any = this.loadingConfigList[i]; let resolver:AnalyzerBase = this.$getAnalyzerByType(config.type); let data:any = resolver.getRes(config.url); resolver.destroyRes(config.url); this.resConfig.parseConfig(data,config.resourceRoot); } this.configComplete = true; this.loadingConfigList = null; ResourceEvent.dispatchResourceEvent(this,ResourceEvent.CONFIG_COMPLETE); this.loadDelayGroups(); } else{ this.loadedGroups.push(event.groupName); this.dispatchEvent(event); } } /** * 启动延迟的组加载 */ private loadDelayGroups():void{ let groupNameList:any[] = this.groupNameList; this.groupNameList = []; let length:number = groupNameList.length; for(let i:number=0;i<length;i++){ let item:any = groupNameList[i]; this.loadGroup(item.name,item.priority); } } /** * 队列加载失败事件 */ private onGroupError(event:ResourceEvent):void{ if(event.groupName==Resource.GROUP_CONFIG){ this.loadingConfigList = null; ResourceEvent.dispatchResourceEvent(this,ResourceEvent.CONFIG_LOAD_ERROR); } else{ this.dispatchEvent(event); } } /** * 检查配置文件里是否含有指定的资源 * @method RES.hasRes * @param key {string} 对应配置文件里的name属性或sbuKeys属性的一项。 * @returns {boolean} */ public hasRes(key:string):boolean{ let type:string = this.resConfig.getType(key); if(type==""){ let prefix:string = RES.AnalyzerBase.getStringTail(key); type = this.resConfig.getType(prefix); if(type==""){ return false; } } return true; } /** * 运行时动态解析一个配置文件, * @param data {any} 配置文件数据,请参考resource.json的配置文件格式。传入对应的json对象即可。 * @param folder {string} 加载项的路径前缀。 */ public parseConfig(data:any, folder:string):void { this.resConfig.parseConfig(data,folder); if(!this.configComplete&&!this.loadingConfigList){ this.configComplete = true; this.loadDelayGroups(); } } /** * 通过key同步获取资源 * @method RES.getRes * @param key {string} * @returns {any} */ public getRes(key:string):any{ let type:string = this.resConfig.getType(key); if(type==""){ let prefix:string = RES.AnalyzerBase.getStringPrefix(key); type = this.resConfig.getType(prefix); if(type==""){ return null; } } let analyzer:AnalyzerBase = this.$getAnalyzerByType(type); return analyzer.getRes(key); } /** * 异步获取资源参数缓存字典 */ private asyncDic:any = {}; /** * 通过key异步获取资源 * @method RES.getResAsync * @param key {string} * @param compFunc {Function} 回调函数。示例:compFunc(data,url):void。 * @param thisObject {any} */ public getResAsync(key:string,compFunc:Function,thisObject:any):void{ let type:string = this.resConfig.getType(key); let name:string = this.resConfig.getName(key); if(type==""){ name = RES.AnalyzerBase.getStringPrefix(key); type = this.resConfig.getType(name); if(type==""){ egret.$callAsync(compFunc, thisObject); return; } } let analyzer:AnalyzerBase = this.$getAnalyzerByType(type); let res:any = analyzer.getRes(key); if(res){ egret.$callAsync(compFunc, thisObject, res, key); return; } let args:any = {key:key,compFunc:compFunc,thisObject:thisObject}; if(this.asyncDic[name]){ this.asyncDic[name].push(args); } else{ this.asyncDic[name] = [args]; let resItem:ResourceItem = this.resConfig.getResourceItem(name); this.resLoader.loadItem(resItem); } } private _loadedUrlTypes = {}; /** * 通过url获取资源 * @method RES.getResByUrl * @param url {string} * @param compFunc {Function} * @param thisObject {any} * @param type {string} */ public getResByUrl(url:string,compFunc:Function,thisObject:any,type:string=""):void{ if(!url){ egret.$callAsync(compFunc, thisObject); return; } if(!type) type = this.getTypeByUrl(url); if (this._loadedUrlTypes[url] != null && this._loadedUrlTypes[url] != type) { egret.$warn(3202); } this._loadedUrlTypes[url] = type; let analyzer:AnalyzerBase = this.$getAnalyzerByType(type); let name:string = url; let res:any = analyzer.getRes(name); if(res){ egret.$callAsync(compFunc, thisObject, res, url); return; } let args:any = {key:name,compFunc:compFunc,thisObject:thisObject}; if(this.asyncDic[name]){ this.asyncDic[name].push(args); } else{ this.asyncDic[name] = [args]; let resItem:ResourceItem = new ResourceItem(name,url,type); this.resLoader.loadItem(resItem); } } /** * 通过url获取文件类型 */ private getTypeByUrl(url:string):string{ let suffix:string = url.substr(url.lastIndexOf(".")+1); if(suffix){ suffix = suffix.toLowerCase(); } let type:string; switch(suffix){ case ResourceItem.TYPE_XML: case ResourceItem.TYPE_JSON: case ResourceItem.TYPE_SHEET: type = suffix; break; case "png": case "jpg": case "gif": case "jpeg": case "bmp": type = ResourceItem.TYPE_IMAGE; break; case "fnt": type = ResourceItem.TYPE_FONT; break; case "txt": type = ResourceItem.TYPE_TEXT; break; case "mp3": case "ogg": case "mpeg": case "wav": case "m4a": case "mp4": case "aiff": case "wma": case "mid": type = ResourceItem.TYPE_SOUND; break; default: type = ResourceItem.TYPE_BIN; break; } return type; } /** * 一个加载项加载完成 */ private onResourceItemComp(item:ResourceItem):void{ let argsList:any[] = this.asyncDic[item.name]; delete this.asyncDic[item.name]; let analyzer:AnalyzerBase = this.$getAnalyzerByType(item.type); let length:number = argsList.length; for(let i:number=0;i<length;i++){ let args:any = argsList[i]; let res:any = analyzer.getRes(args.key); args.compFunc.call(args.thisObject,res,args.key); } } /** * 销毁单个资源文件或一组资源的缓存数据,返回是否删除成功。 * @method RES.destroyRes * @param name {string} 配置文件中加载项的name属性或资源组名 * @param force {boolean} 销毁一个资源组时其他资源组有同样资源情况资源是否会被删除,默认值true * @returns {boolean} */ public destroyRes(name:string, force:boolean = true):boolean{ let group:any[] = this.resConfig.getRawGroupByName(name); if(group && group.length > 0){ let index:number = this.loadedGroups.indexOf(name); if(index!=-1){ this.loadedGroups.splice(index,1); } let length:number = group.length; for(let i:number=0;i<length;i++){ let item:any = group[i]; if(!force && this.isResInLoadedGroup(item.name)) { } else { item.loaded = false; let analyzer:AnalyzerBase = this.$getAnalyzerByType(item.type); analyzer.destroyRes(item.name); this.removeLoadedGroupsByItemName(item.name); } } return true; } else{ let type:string = this.resConfig.getType(name); if (type == "") { type = this._loadedUrlTypes[name]; if (type == null || type == "") { return false; } delete this._loadedUrlTypes[name]; let analyzer:AnalyzerBase = this.$getAnalyzerByType(type); analyzer.destroyRes(name); return true; } let item = this.resConfig.getRawResourceItem(name); item.loaded = false; let analyzer = this.$getAnalyzerByType(type); let result = analyzer.destroyRes(name); this.removeLoadedGroupsByItemName(item.name); return result; } } private removeLoadedGroupsByItemName(name:string):void { let loadedGroups:string[] = this.loadedGroups; let loadedGroupLength:number = loadedGroups.length; for(let i:number = 0 ; i < loadedGroupLength ; i++) { let group:any[] = this.resConfig.getRawGroupByName(loadedGroups[i]); let length:number = group.length; for(let j:number = 0 ; j < length ; j++) { let item:any = group[j]; if(item.name == name) { loadedGroups.splice(i, 1); i--; loadedGroupLength = loadedGroups.length; break; } } } } private isResInLoadedGroup(name:string):boolean { let loadedGroups:string[] = this.loadedGroups; let loadedGroupLength:number = loadedGroups.length; for(let i:number = 0 ; i < loadedGroupLength ; i++) { let group:any[] = this.resConfig.getRawGroupByName(loadedGroups[i]); let length:number = group.length; for(let j:number = 0 ; j < length ; j++) { let item:any = group[j]; if(item.name == name) { return true; } } } return false; } /** * 设置最大并发加载线程数量,默认值是2. * @method RES.setMaxLoadingThread * @param thread {number} 要设置的并发加载数。 */ public setMaxLoadingThread(thread:number):void{ if(thread<1){ thread = 1; } this.resLoader.thread = thread; } /** * 设置资源加载失败时的重试次数。 * @param retry 要设置的重试次数。 */ public setMaxRetryTimes(retry:number):void{ retry = Math.max(retry, 0); this.resLoader.maxRetryTimes = retry; } } /** * Resource单例 */ let instance:Resource = new Resource(); }
the_stack
export declare type callback = (e?: Error, respBody?: any, respInfo?: any) => void; export declare namespace auth { namespace digest { class Mac { accessKey: string; secretKey: string; constructor(accessKey?: string, secretKey?: string); } } } export declare namespace cdn { class CdnManager { mac: auth.digest.Mac; constructor(mac?: auth.digest.Mac); /** * 获取域名日志下载链接 * @see http://developer.qiniu.com/article/fusion/api/log.html * * @param domains 域名列表 如:['obbid7qc6.qnssl.com','7xkh68.com1.z0.glb.clouddn.com'] * @param logDay logDay 如 2016-07-01 * @param callback callbackFunc(err, respBody, respInfo) */ getCdnLogList(domains: string[], logDay: string, callback: callback): void; /** * 获取域名访问流量数据 * @see http://developer.qiniu.com/article/fusion/api/traffic-bandwidth.html#batch-flux * * @param startDate 开始日期,例如:2016-07-01 * @param endDate 结束日期,例如:2016-07-03 * @param granularity 粒度,取值:5min/hour/day * @param domains 域名列表 domain = ['obbid7qc6.qnssl.com','obbid7qc6.qnssl.com']; * @param callback callbackFunc(err, respBody, respInfo) */ getFluxData(startDate: string, endDate: string, granularity: string, domains: string[], callback: callback): void; /** * 获取域名带宽数据 * @see http://developer.qiniu.com/article/fusion/api/traffic-bandwidth.html#batch-flux * @param startDate 开始日期,例如:2016-07-01 * @param endDate 结束日期,例如:2016-07-03 * @param granularity 粒度,取值:5min/hour/day * @param domains 域名列表 domain = ['obbid7qc6.qnssl.com','obbid7qc6.qnssl.com']; * @param callback callbackFunc(err, respBody, respInfo) */ getBandwidthData(startDate: string, endDate: string, granularity: string, domains: string[], callback: callback): void; /** * 预取文件链接 * @see http://developer.qiniu.com/article/fusion/api/prefetch.html * * @param urls 预取urls urls = ['http://obbid7qc6.qnssl.com/023','http://obbid7qc6.qnssl.com/025'] * @param callback callbackFunc(err, respBody, respInfo) */ prefetchUrls(urls: string[], callback: callback): void; /** * 刷新链接 * @see http://developer.qiniu.com/article/fusion/api/refresh.html * * @param urls refreshUrls = ['http://obbid7qc6.qnssl.com/023','http://obbid7qc6.qnssl.com/025'] * @param callback callbackFunc(err, respBody, respInfo) */ refreshUrls(urls: string[], callback: callback): void; /** * 刷新目录列表,每次最多不可以超过10个目录, 刷新目录需要额外开通权限,可以联系七牛技术支持处理 * @see http://developer.qiniu.com/article/fusion/api/refresh.html * * @param dirs refreshDirs = ['http://obbid7qc6.qnssl.com/wo/','http://obbid7qc6.qnssl.com/'] * @param callback callbackFunc(err, respBody, respInfo) */ refreshDirs(dirs: string[], callback: callback): void; /** * 刷新目录和链接 * @param urls refreshUrls = ['http://obbid7qc6.qnssl.com/023','http://obbid7qc6.qnssl.com/025'] * @param dirs refreshDirs = ['http://obbid7qc6.qnssl.com/wo/','http://obbid7qc6.qnssl.com/'] * @param callback callbackFunc(err, respBody, respInfo) */ refreshUrlsAndDirs(urls: string[], dirs: string[], callback: callback): void; /** * 构建标准的基于时间戳的防盗链 * @param domain 自定义域名,例如 http://img.abc.com * @param fileName 待访问的原始文件名,必须是utf8编码,不需要进行urlencode * @param query 业务自身的查询参数,必须是utf8编码,不需要进行urlencode, 例如 {aa:"23", attname:"11111111111111"} * @param encryptKey 时间戳防盗链的签名密钥,从七牛后台获取 * @param deadline 链接的有效期时间戳,是以秒为单位的Unix时间戳 * @return signedUrl 最终的带时间戳防盗链的url */ createTimestampAntiLeechUrl(domain: string, fileName: string, query: any, encryptKey: string, deadline: number): string; } } export declare namespace conf { let ACCESS_KEY: string; let SECRET_KEY: string; let USER_AGENT: string; let BLOCK_SIZE: number; let FormMimeUrl: string; let FormMimeJson: string; let FormMimeRaw: string; let RS_HOST: string; let RPC_TIMEOUT: number; interface ConfigOptions { /** * @default false */ useHttpsDomain?: boolean; /** * @default true */ useCdnDomain?: boolean; /** * @default null */ zone?: Zone, /** * @default -1 */ zoneExpire?: number; } class Config implements ConfigOptions { constructor(options?: ConfigOptions); } class Zone { srcUpHosts: any; cdnUpHosts: any; ioHost: string; rsHost: string; rsfHost: string; apiHost: string; constructor(srcUpHosts?: any, cdnUpHosts?: any, ioHost?: string, rsHost?: string, rsfHost?: string, apiHost?: string); } } export declare namespace form_up { class FormUploader { conf: conf.Config; constructor(config?: conf.Config); /** * * @param uploadToken * @param key * @param rsStream * @param putExtra * @param callback */ putStream(uploadToken: string, key: string | null, rsStream: NodeJS.ReadableStream, putExtra: PutExtra | null, callback: callback): void; /** * * @param uploadToken * @param key * @param body * @param putExtra * @param callback */ put(uploadToken: string, key: string | null, body: any, putExtra: PutExtra | null, callback: callback): void; /** * * @param uploadToken * @param body * @param putExtra * @param callback */ putWithoutKey(uploadToken: string, body: any, putExtra: PutExtra | null, callback: callback): void; /** * 上传本地文件 * @param uploadToken 上传凭证 * @param key 目标文件名 * @param localFile 本地文件路径 * @param putExtra 额外选项 * @param callback */ putFile(uploadToken: string, key: string | null, localFile: string, putExtra: PutExtra | null, callback: callback): void; /** * * @param uploadToken * @param localFile * @param putExtra * @param callback */ putFileWithoutKey(uploadToken: string, localFile: string, putExtra: PutExtra | null, callback: callback): void; } class PutExtra { /** * @default '' */ fname: string; /** * @default {} */ params: any; /** * @default null */ mimeType?: string; /** * @default null */ crc32?: string; /** * @default 0|false */ checkCrc?: number | boolean; /** * 上传可选参数 * @param fname 请求体中的文件的名称 * @param params 额外参数设置,参数名称必须以x:开头 * @param mimeType 指定文件的mimeType * @param crc32 指定文件的crc32值 * @param checkCrc 指定是否检测文件的crc32值 */ constructor(fname?: string, params?: any, mimeType?: string, crc32?: string, checkCrc?: number | boolean); } } export declare namespace resume_up { class ResumeUploader { config: conf.Config; constructor(config?: conf.Config); /** * * @param uploadToken * @param key * @param rsStream * @param rsStreamLen * @param putExtra * @param callback */ putStream(uploadToken: string, key: string | null, rsStream: NodeJS.ReadableStream, rsStreamLen: number, putExtra: PutExtra | null, callback: callback): void; /** * * @param uploadToken * @param key * @param localFile * @param putExtra * @param callback */ putFile(uploadToken: string, key: string | null, localFile: string, putExtra: PutExtra | null, callback: callback): void; /** * * @param uploadToken * @param localFile * @param putExtra * @param callback */ putFileWithoutKey(uploadToken: string, localFile: string, putExtra: PutExtra | null, callback: callback): void; } class PutExtra { /** * @default '' */ fname?: string; /** * @default {} */ params?: any; /** * @default null */ mimeType?: string; /** * @default null */ resumeRecordFile?: string /** * @default null */ progressCallback?: (uploadBytes: number, totalBytes: number) => void /** * @default v1 */ version?: string /** * @default 4 * 1024 * 1024 */ partSize?: number /** * 上传可选参数 * @param fname 请求体中的文件的名称 * @param params 额外参数设置,参数名称必须以x:开头 * @param mimeType 指定文件的mimeType * @param resumeRecordFile * @param progressCallback * @param version 分片上传版本 目前支持v1/v2版本 默认v1 * @param partSize 分片上传v2必传字段 默认大小为4MB 分片大小范围为1 MB - 1 GB */ constructor(fname?: string, params?: any, mimeType?: string, resumeRecordFile?: string, version?:string, partSize?:number, progressCallback?: (uploadBytes: number, totalBytes: number) => void); } } export declare namespace util { function isTimestampExpired(timestamp: number): boolean; function encodedEntry(bucket: string, key?: string): string; function getAKFromUptoken(uploadToken: string): string; function getBucketFromUptoken(uploadToken: string): string; function base64ToUrlSafe(v: string): string; function urlSafeToBase64(v: string): string; function urlsafeBase64Encode(jsonFlags: string): string; function urlSafeBase64Decode(fromStr: string): string; function hmacSha1(encodedFlags: string | Buffer, secretKey: string | Buffer): string; /** * 创建AccessToken凭证 * @param mac AK&SK对象 * @param requestURI 请求URL * @param reqBody 请求Body,仅当请求的ContentType为application/x-www-form-urlencoded 时才需要传入该参数 */ function generateAccessToken(mac: auth.digest.Mac, requestURI: string, reqBody?: string): string; /** * 创建AccessToken凭证 * @param mac AK&SK对象 * @param requestURI 请求URL * @param reqMethod 请求方法,例如 GET,POST * @param reqContentType 请求类型,例如 application/json 或者 application/x-www-form-urlencoded * @param reqBody 请求Body,仅当请求的 ContentType 为 application/json 或者 application/x-www-form-urlencoded 时才需要传入该参数 */ function generateAccessTokenV2(mac: auth.digest.Mac, requestURI: string, reqMethod: string, reqContentType: string, reqBody?: string): string; /** * 校验七牛上传回调的Authorization * @param mac AK&SK对象 * @param requestURI 回调的URL中的requestURI * @param reqBody 回调的URL中的requestURI 请求Body,仅当请求的ContentType为application/x-www-form-urlencoded时才需要传入该参数 * @param callbackAuth 回调时请求的Authorization头部值 */ function isQiniuCallback(mac: auth.digest.Mac, requestURI: string, reqBody: string | null, callbackAuth: string): boolean; } export declare namespace rpc { interface Headers { 'User-Agent'?: string; Connection?: string; } /** * * @param requestURI * @param requestForm * @param headers * @param callback */ function post(requestURI: string, requestForm: Buffer | string | NodeJS.ReadableStream | null, headers: Headers | null, callback: callback): void; /** * * @param requestURI * @param requestForm * @param callback */ function postMultipart(requestURI: string, requestForm: Buffer | string | NodeJS.ReadableStream | null, callback: callback): void; /** * * @param requestURI * @param requestForm * @param token * @param callback */ function postWithForm(requestURI: string, requestForm: Buffer | string | NodeJS.ReadableStream | null, token: string | null, callback: callback): void; /** * * @param requestURI * @param token * @param callback */ function postWithoutForm(requestURI: string, token: string | null, callback: callback): void; } export declare namespace zone { //huadong const Zone_z0: conf.Zone; //huabei const Zone_z1: conf.Zone; //huanan const Zone_z2: conf.Zone; //beimei const Zone_na0: conf.Zone; //Southeast Asia const Zone_as0: conf.Zone; } export declare namespace fop { interface PfopOptions { /** * 回调业务服务器,通知处理结果 */ notifyURL?: string; /** * 结果是否强制覆盖已有的同名文件 */ force?: boolean; } class OperationManager { mac: auth.digest.Mac; config: conf.Config; constructor(mac?: auth.digest.Mac, config?: conf.Config); /** * 发送持久化数据处理请求 * @param bucket 空间名称 * @param key 文件名称 * @param fops 处理指令集合 * @param pipeline 处理队列名称 * @param options * @param callback */ pfop(bucket: string, key: string, fops: string[], pipeline: string, options: PfopOptions | null, callback: callback): void; /** * 查询持久化数据处理进度 * @param persistentId pfop操作返回的持久化处理ID * @param callback */ prefop(persistentId: string, callback: callback): void; } } export declare namespace rs { interface ListPrefixOptions { /** * 列举的文件前缀 */ prefix?: string; /** * 上一次列举返回的位置标记 */ marker?: any; /** * 每次返回的最大列举文件数量 */ limit?: number; /** * 指定目录分隔符 */ delimiter?: string; } class BucketManager { mac: auth.digest.Mac; config: conf.Config; constructor(mac?: auth.digest.Mac, config?: conf.Config); /** * 获取资源信息 * @see https://developer.qiniu.com/kodo/api/1308/stat * * @param bucket 空间名称 * @param key 文件名称 * @param callback */ stat(bucket: string, key: string, callback: callback): void; /** * 修改文件的类型 * @see https://developer.qiniu.com/kodo/api/1252/chgm * * @param bucket 空间名称 * @param key 文件名称 * @param newMime 新文件类型 * @param callback */ changeMime(bucket: string, key: string, newMime: string, callback: callback): void; /** * 修改文件的Headers * @see TODO * * @param bucket 空间名称 * @param key 文件名称 * @param headers Headers对象 * @param callback */ changeHeaders(bucket: string, key: string, headers: { [k: string]: string }, callback: callback): void; /** * 移动或重命名文件,当bucketSrc==bucketDest相同的时候,就是重命名文件操作 * @see https://developer.qiniu.com/kodo/api/1288/move * * @param srcBucket 源空间名称 * @param srcKey 源文件名称 * @param destBucket 目标空间名称 * @param destKey 目标文件名称 * @param options * @param callback */ move(srcBucket: string, srcKey: string, destBucket: string, destKey: string, options: { force?: boolean } | null, callback: callback): void; /** * 复制文件 * @see https://developer.qiniu.com/kodo/api/1254/copy * * @param srcBucket 源空间名称 * @param srcKey 源文件名称 * @param destBucket 目标空间名称 * @param destKey 目标文件名称 * @param options * @param callback */ copy(srcBucket: string, srcKey: string, destBucket: string, destKey: string, options: { force?: boolean } | null, callback: callback): void; /** * 删除资源 * @see https://developer.qiniu.com/kodo/api/1257/delete * * @param bucket 空间名称 * @param key 文件名称 * @param callback */ delete(bucket: string, key: string, callback: callback): void; /** * 更新文件的生命周期 * @see https://developer.qiniu.com/kodo/api/1732/update-file-lifecycle * * @param bucket 空间名称 * @param key 文件名称 * @param days 有效期天数 * @param callback */ deleteAfterDays(bucket: string, key: string, days: number, callback: callback): void; /** * 抓取资源 * @see https://developer.qiniu.com/kodo/api/1263/fetch * * @param resUrl 资源链接 * @param bucket 空间名称 * @param key 文件名称 * @param callback */ fetch(resUrl: string, bucket: string, key: string, callback: callback): void; /** * 更新镜像副本 * @see https://developer.qiniu.com/kodo/api/1293/prefetch * * @param bucket 空间名称 * @param key 文件名称 * @param callback */ prefetch(bucket: string, key: string, callback: callback): void; /** * 修改文件的存储类型 * @see https://developer.qiniu.com/kodo/api/3710/modify-the-file-type * * @param bucket 空间名称 * @param key 文件名称 * @param newType 0 表示标准存储;1 表示低频存储。 * @param callback */ changeType(bucket: string, key: string, newType: number, callback: callback): void; /** * 设置空间镜像源 * @see https://developer.qiniu.com/kodo/api/1370/mirror * * @param bucket 空间名称 * @param srcSiteUrl 镜像源地址 * @param srcHost 镜像Host * @param callback */ image(bucket: string, srcSiteUrl: string, srcHost: string, callback: callback): void; /** * 取消设置空间镜像源 * @see https://developer.qiniu.com/kodo/api/1370/mirror * * @param bucket 空间名称 * @param callback */ unimage(bucket: string, callback: callback): void; /** * 获取指定前缀的文件列表 * @see https://developer.qiniu.com/kodo/api/1284/list * * @param bucket 空间名称 * @param options 列举操作的可选参数 * @param callback */ listPrefix(bucket: string, options: ListPrefixOptions | null, callback: callback): void; /** * 批量文件管理请求,支持stat,chgm,chtype,delete,copy,move * @param operations * @param callback */ batch(operations: any, callback: callback): void; /** * 获取私有空间的下载链接 * @param domain 空间绑定的域名,比如以http或https开头 * @param fileName 原始文件名 * @param deadline 文件有效期时间戳(单位秒) */ privateDownloadUrl(domain: string, fileName: string, deadline: number): string; /** * 获取公开空间的下载链接 * @param domain 空间绑定的域名,比如以http或https开头 * @param fileName 原始文件名 */ publicDownloadUrl(domain: string, fileName: string): string; } /** * * @param bucket * @param key */ function statOp(bucket: string, key: string): string; /** * * @param bucket * @param key */ function deleteOp(bucket: string, key: string): string; /** * * @param bucket * @param key * @param days */ function deleteAfterDaysOp(bucket: string, key: string, days: number): string; /** * * @param bucket * @param key * @param newMime */ function changeMimeOp(bucket: string, key: string, newMime: string): string; /** * * @param bucket * @param key * @param headers */ function changeHeadersOp(bucket: string, key: string, headers: { [k: string]: string }): string; /** * * @param bucket * @param key * @param newType */ function changeTypeOp(bucket: string, key: string, newType: number): string; /** * * @param srcBucket * @param srcKey * @param destBucket * @param destKey * @param options */ function moveOp(srcBucket: string, srcKey: string, destBucket: string, destKey: string, options?: { force?: boolean }): string; /** * * @param srcBucket * @param srcKey * @param destBucket * @param destKey * @param options */ function copyOp(srcBucket: string, srcKey: string, destBucket: string, destKey: string, options?: { force?: boolean }): string; interface PutPolicyOptions { scope?: string; isPrefixalScope?: number; expires?: number; insertOnly?: number; saveKey?: string; endUser?: string; returnUrl?: string; returnBody?: string; callbackUrl?: string; callbackHost?: string; callbackBody?: string; callbackBodyType?: string; callbackFetchKey?: number; persistentOps?: string; persistentNotifyUrl?: string; persistentPipeline?: string; fsizeLimit?: number; fsizeMin?: number; mimeLimit?: string; detectMime?: number; deleteAfterDays?: number; fileType?: number; } class PutPolicy { constructor(options?: PutPolicyOptions); getFlags(): any; uploadToken(mac?: auth.digest.Mac): string; } }
the_stack
import Group from "./Group"; import MakiObject from "./MakiObject"; import { findDescendantByTypeAndId, getMousePosition, unimplementedWarning, } from "../utils"; import * as Actions from "../Actions"; import * as Selectors from "../Selectors"; import { ModernStore } from "../types"; import Layout from "./Layout"; import GuiObject from "./GuiObject"; class System extends MakiObject { _scriptGroup: MakiObject; _root: MakiObject; _store: ModernStore; _privateInt: Map<string, Map<string, number>>; _privateString: Map<string, Map<string, string>>; constructor(scriptGroup: MakiObject | null, store: ModernStore) { super(null, null); this._store = store; this._scriptGroup = scriptGroup == null ? new Group(null, null) : scriptGroup; this._root = this._scriptGroup; while (this._root.parent) { this._root = this._root.parent; } // TODO: Replace these with a DefaultMap once we have one. this._privateInt = new Map(); this._privateString = new Map(); } /** * getclassname() * * Returns the class name for the object. * @ret The class name. */ getclassname() { return "System"; } getscriptgroup() { return this._scriptGroup; } getcontainer(id: string) { return findDescendantByTypeAndId(this._root, "container", id); } getruntimeversion(): number { return 5.666; } // Retreive a token from a list of tokens seperated by separator. gettoken(str: string, separator: string, tokennum: number): string { const tokens = str.split(separator); if (tokens.length > tokennum) { return tokens[tokennum]; } return ""; } getparam(): string { unimplementedWarning("getparam"); return "Some String"; } getskinname(): string { unimplementedWarning("getskinname"); return "Some String"; } getplayitemstring(): string { unimplementedWarning("getplayitemstring"); return "Some String"; } geteq(): number { unimplementedWarning("geteq"); return 0; } oneqchanged(newstatus: number): void { this.js_trigger("onEqChanged", newstatus); } geteqband(band: number): number { unimplementedWarning("geteqband"); return 0; } geteqpreamp(): number { unimplementedWarning("geteqpreamp"); return 0; } getstatus(): number { unimplementedWarning("getstatus"); return 0; } messagebox( message: string, msgtitle: string, flag: number, notanymoreId: string ): number { console.log({ message, msgtitle, flag, notanymoreId }); return unimplementedWarning("getstatus"); } integertostring(value: number): string { return value.toString(); } stringtointeger(str: string): number { return parseInt(str, 10); } getprivateint(section: string, item: string, defvalue: number): number { if ( !this._privateInt.has(section) || // @ts-ignore We know this section exists !this._privateInt.get(section).has(item) ) { return defvalue; } // @ts-ignore We know this section exists return this._privateInt.get(section).get(item); } // I think `defvalue` here is a typo that we inherited from std.mi. It should just be `value`. setprivateint(section: string, item: string, defvalue: number): void { if (!this._privateInt.has(section)) { this._privateInt.set(section, new Map([[item, defvalue]])); } else { // @ts-ignore We know the section exists this._privateInt.get(section).set(item, defvalue); } } getleftvumeter(): number { return Selectors.getLeftVUMeter(this._store.getState()); } getrightvumeter(): number { return Selectors.getRightVUMeter(this._store.getState()); } // Seems like volume is 0-255 getvolume(): number { return Selectors.getVolume(this._store.getState()); } setvolume(volume: number): void { return this._store.dispatch(Actions.setVolume(volume)); } getplayitemlength(): number { unimplementedWarning("getplayitemlength"); return 100000; } seekto(pos: number): void { unimplementedWarning("seekto"); } getviewportheight(): number { return Math.max( document.documentElement.clientHeight, window.innerHeight || 0 ); } getviewportwidth(): number { return Math.max( document.documentElement.clientWidth, window.innerWidth || 0 ); } onscriptloaded(): void { this.js_trigger("onScriptLoaded"); } onscriptunloading(): void { this.js_trigger("onScriptUnloading"); } onquit(): void { this.js_trigger("onQuit"); } onsetxuiparam(param: string, value: string): void { this.js_trigger("onSetXuiParam", param, value); } onkeydown(key: string): void { this.js_trigger("onKeyDown", key); } onaccelerator(action: string, section: string, key: string): void { this.js_trigger("onAccelerator", action, section, key); } oncreatelayout(_layout: Layout): void { this.js_trigger("onCreateLayout", _layout); } onshowlayout(_layout: Layout): void { this.js_trigger("onShowLayout", _layout); } onhidelayout(_layout: Layout): void { this.js_trigger("onHideLayout", _layout); } onstop(): void { this.js_trigger("onStop"); } onplay(): void { this.js_trigger("onPlay"); } onpause(): void { this.js_trigger("onPause"); } onresume(): void { this.js_trigger("onResume"); } ontitlechange(newtitle: string): void { this.js_trigger("onTitleChange", newtitle); } ontitle2change(newtitle2: string): void { this.js_trigger("onTitle2Change", newtitle2); } oninfochange(info: string): void { this.js_trigger("onInfoChange", info); } onstatusmsg(msg: string): void { this.js_trigger("onStatusMsg", msg); } oneqbandchanged(band: number, newvalue: number): void { this.js_trigger("onEqBandChanged", band, newvalue); } oneqpreampchanged(newvalue: number): void { this.js_trigger("onEqPreampChanged", newvalue); } onvolumechanged(newvol: number): void { this.js_trigger("onVolumeChanged", newvol); } onseek(newpos: number): void { this.js_trigger("onSeek", newpos); } newdynamiccontainer(container_id: string) { return unimplementedWarning("newdynamiccontainer"); } newgroup(group_id: string) { return unimplementedWarning("newgroup"); } newgroupaslayout(group_id: string) { return unimplementedWarning("newgroupaslayout"); } getnumcontainers(): number { return unimplementedWarning("getnumcontainers"); } enumcontainer(num: number) { return unimplementedWarning("enumcontainer"); } getwac(wac_guid: string) { return unimplementedWarning("getwac"); } getplayitemmetadatastring(metadataname: string): string { return unimplementedWarning("getplayitemmetadatastring"); } getplayitemdisplaytitle(): string { return unimplementedWarning("getplayitemdisplaytitle"); } getextfamily(ext: string): string { return unimplementedWarning("getextfamily"); } playfile(playitem: string): void { return unimplementedWarning("playfile"); } play(): void { return unimplementedWarning("play"); } stop(): void { return unimplementedWarning("stop"); } pause(): void { return unimplementedWarning("pause"); } next(): void { return unimplementedWarning("next"); } previous(): void { return unimplementedWarning("previous"); } eject(): void { return unimplementedWarning("eject"); } getposition(): number { return unimplementedWarning("getposition"); } seteqband(band: number, value: number): void { return unimplementedWarning("seteqband"); } seteqpreamp(value: number): void { return unimplementedWarning("seteqpreamp"); } seteq(onoff: number): void { return unimplementedWarning("seteq"); } getmouseposx(): number { return getMousePosition().x; } getmouseposy(): number { return getMousePosition().y; } floattostring(value: number, ndigits: number): string { return value.toFixed(ndigits).toString(); } stringtofloat(str: string): number { return parseFloat(str); } _atLeastTwoDigits(n: number): string { return n > 9 ? n.toString() : `0${n}`; } // Convert a time in seconds to a HH:MM:SS value. integertolongtime(value: number): string { const hours = Math.floor(value / 3600); const remainingTime = value - hours * 3600; const minutes = Math.floor(remainingTime / 60); const seconds = Math.floor(remainingTime - minutes * 60); return `${this._atLeastTwoDigits(hours)}:${this._atLeastTwoDigits( minutes )}:${this._atLeastTwoDigits(seconds)}`; } // Convert a time in seconds to a MM:SS value. integertotime(value: number): string { const minutes = Math.floor(value / 60); const seconds = Math.floor(value - minutes * 60); return `${this._atLeastTwoDigits(minutes)}:${this._atLeastTwoDigits( seconds )}`; } _getDateTimeInMs(date: Date): number { const dateTime = date.getTime(); const dateCopy = new Date(dateTime); return dateTime - dateCopy.setHours(0, 0, 0, 0); } // datetime in HH:MM format (docs imply it is in the same format as integertotime // which would be MM:SS, but I tested in winamp and it is HH:MM) // (e.g. 17:44) datetotime(datetime: number): string { const date = new Date(datetime * 1000); const seconds = this._getDateTimeInMs(date) / 1000; const longtime = this.integertolongtime(seconds); return longtime.substring(0, longtime.length - 3); } // datetime in HH:MM:SS format // (e.g. 17:44:58) datetolongtime(datetime: number): string { const date = new Date(datetime * 1000); const seconds = this._getDateTimeInMs(date) / 1000; return this.integertolongtime(seconds); } // datetime in MM/DD/YY HH:MM:SS format // (e.g. 09/08/19 17:44:58) formatdate(datetime: number): string { const date = new Date(datetime * 1000); const seconds = this._getDateTimeInMs(date) / 1000; const dateString = date.toLocaleDateString("en-US", { year: "2-digit", month: "2-digit", day: "2-digit", }); const timeString = this.integertolongtime(seconds); return `${dateString} ${timeString}`; } // datetime in DayOfWeek, Month DD, YYYY HH:MM:SS format // (e.g. Sunday, September 08, 2019 17:44:58) formatlongdate(datetime: number): string { const date = new Date(datetime * 1000); const seconds = this._getDateTimeInMs(date) / 1000; const dateString = date.toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "2-digit", }); const timeString = this.integertolongtime(seconds); return `${dateString} ${timeString}`; } // returns the datetime's year since 1900 getdateyear(datetime: number): number { const date = new Date(datetime * 1000); return date.getFullYear() - 1900; } // returns the datetime's month (0-11) getdatemonth(datetime: number): number { const date = new Date(datetime * 1000); return date.getMonth(); } // returns the datetime's day of the month (1-31) getdateday(datetime: number): number { const date = new Date(datetime * 1000); return date.getDate(); } // returns the datetime's day of the week (0-6) // MAKI starts with Sunday like JS getdatedow(datetime: number): number { const date = new Date(datetime * 1000); return date.getDay(); } // returns the datetime's day of the year (0-365) getdatedoy(datetime: number): number { const date = new Date(datetime * 1000); const start = new Date(date.getFullYear(), 0, 0); return Math.floor((date.getTime() - start.getTime()) / 86400000); } // returns the datetime's hour (0-23) getdatehour(datetime: number): number { const date = new Date(datetime * 1000); return date.getHours(); } // returns the datetime's minutes (0-59) getdatemin(datetime: number): number { const date = new Date(datetime * 1000); return date.getMinutes(); } // returns the datetime's seconds (0-59) getdatesec(datetime: number): number { const date = new Date(datetime * 1000); return date.getSeconds(); } // Based on https://stackoverflow.com/questions/11887934/how-to-check-if-the-dst-daylight-saving-time-is-in-effect-and-if-it-is-whats _stdTimezoneOffset(date: Date): number { const jan = new Date(date.getFullYear(), 0, 1); const jul = new Date(date.getFullYear(), 6, 1); return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()); } // returns the datetime's daylight savings flag getdatedst(datetime: number): number { const date = new Date(datetime * 1000); return date.getTimezoneOffset() < this._stdTimezoneOffset(date) ? 1 : 0; } // returns the datetime in seconds, use with the above functions getdate(): number { return Math.floor(Date.now() / 1000); } // Get a substring from a string. strmid(str: string, start: number, len: number): string { return str.substring(start, start + len); } // Get a substring from a string, starting from the left. strleft(str: string, nchars: number): string { return str.substring(0, nchars); } // Get a substring from a string, starting from the right. Since // the start point is the right of the string (or the end). It will // extract the string starting from the END going towards the BEGINNING. strright(str: string, nchars: number): string { return str.substring(str.length - nchars); } // Search a string for any occurance of substring. If the substring was // found in the string, it will return the position of the substring in // the string searched. If the substring is not found, the return value // is -1. strsearch(str: string, substr: string): number { return str.indexOf(substr); } strlen(str: string): number { return str.length; } strupper(str: string): string { return str.toUpperCase(); } strlower(str: string): string { return str.toLowerCase(); } urlencode(url: string): string { return encodeURI(url); } removepath(str: string): string { return unimplementedWarning("removepath"); } getpath(str: string): string { return unimplementedWarning("getpath"); } getextension(str: string): string { return unimplementedWarning("getextension"); } sin(value: number): number { return Math.sin(value); } cos(value: number): number { return Math.cos(value); } tan(value: number): number { return Math.tan(value); } asin(value: number): number { return Math.asin(value); } acos(value: number): number { return Math.acos(value); } atan(value: number): number { return Math.atan(value); } atan2(y: number, x: number): number { return Math.atan2(y, x); } pow(value: number, pvalue: number): number { return Math.pow(value, pvalue); } sqr(value: number): number { return Math.pow(value, 2); } sqrt(value: number): number { return Math.sqrt(value); } random(max: number): number { return Math.floor(Math.random() * max); } setprivatestring(section: string, item: string, value: string): void { if (!this._privateString.has(section)) { this._privateString.set(section, new Map([[item, value]])); } else { // @ts-ignore We know the section exists this._privateString.get(section).set(item, value); } } getprivatestring(section: string, item: string, defvalue: string): string { if ( !this._privateString.has(section) || // @ts-ignore We know this section exists !this._privateString.get(section).has(item) ) { return defvalue; } // @ts-ignore We know the section exists return this._privateString.get(section).get(item); } setpublicstring(item: string, value: string): void { return unimplementedWarning("setpublicstring"); } setpublicint(item: string, value: number): void { return unimplementedWarning("setpublicint"); } getpublicstring(item: string, defvalue: string): string { return unimplementedWarning("getpublicstring"); } getpublicint(item: string, defvalue: number): number { return unimplementedWarning("getpublicint"); } getviewportwidthfrompoint(x: number, y: number): number { return unimplementedWarning("getviewportwidthfrompoint"); } getviewportheightfrompoint(x: number, y: number): number { return unimplementedWarning("getviewportheightfrompoint"); } getviewportleft(): number { return unimplementedWarning("getviewportleft"); } getviewportleftfrompoint(x: number, y: number): number { return unimplementedWarning("getviewportleftfrompoint"); } getviewporttop(): number { return unimplementedWarning("getviewporttop"); } getviewporttopfrompoint(x: number, y: number): number { return unimplementedWarning("getviewporttopfrompoint"); } debugstring(str: string, severity: number): void { return unimplementedWarning("debugstring"); } ddesend(application: string, command: string, mininterval: number): void { return unimplementedWarning("ddesend"); } onlookforcomponent(guid: string) { return unimplementedWarning("onlookforcomponent"); } getcurappleft(): number { return unimplementedWarning("getcurappleft"); } getcurapptop(): number { return unimplementedWarning("getcurapptop"); } getcurappwidth(): number { return unimplementedWarning("getcurappwidth"); } getcurappheight(): number { return unimplementedWarning("getcurappheight"); } isappactive(): boolean { return unimplementedWarning("isappactive"); } switchskin(skinname: string): void { return unimplementedWarning("switchskin"); } isloadingskin(): number { return unimplementedWarning("isloadingskin"); } lockui(): void { return unimplementedWarning("lockui"); } unlockui(): void { return unimplementedWarning("unlockui"); } getmainbrowser() { return unimplementedWarning("getmainbrowser"); } popmainbrowser(): void { return unimplementedWarning("popmainbrowser"); } navigateurl(url: string): void { return unimplementedWarning("navigateurl"); } isobjectvalid(o: MakiObject): boolean { return unimplementedWarning("isobjectvalid"); } // Takes a Double and returns the closest integer representation. integer(d: number): number { return Math.round(d); } frac(d: number): number { return d - Math.floor(d); } // Returns ms since midnight gettimeofday(): number { const date = new Date(); return this._getDateTimeInMs(date); } setmenutransparency(alphavalue: number): void { return unimplementedWarning("setmenutransparency"); } ongetcancelcomponent(guid: string, goingvisible: boolean): boolean { unimplementedWarning("ongetcancelcomponent"); this.js_trigger("onGetCancelComponent", guid, goingvisible); // TODO: not sure what we shuld return return true; } iskeydown(vk_code: number): number { return unimplementedWarning("iskeydown"); } setclipboardtext(_text: string): void { return unimplementedWarning("setclipboardtext"); } chr(charnum: number): string { return String.fromCharCode(charnum); } selectfile(extlist: string, id: string, prev_filename: string): string { return unimplementedWarning("selectfile"); } systemmenu(): void { return unimplementedWarning("systemmenu"); } windowmenu(): void { return unimplementedWarning("windowmenu"); } triggeraction( context: GuiObject, actionname: string, actionparam: string ): void { return unimplementedWarning("triggeraction"); } showwindow( guidorgroupid: string, preferedcontainer: string, transient: boolean ) { return unimplementedWarning("showwindow"); } hidewindow(hw: GuiObject): void { return unimplementedWarning("hidewindow"); } hidenamedwindow(guidorgroup: string): void { return unimplementedWarning("hidenamedwindow"); } isnamedwindowvisible(guidorgroup: string): boolean { return unimplementedWarning("isnamedwindowvisible"); } setatom(atomname: string, object: MakiObject): void { return unimplementedWarning("setatom"); } getatom(atomname: string) { return unimplementedWarning("getatom"); } invokedebugger(): void { return unimplementedWarning("invokedebugger"); } isvideo(): number { return unimplementedWarning("isvideo"); } isvideofullscreen(): number { return unimplementedWarning("isvideofullscreen"); } getidealvideowidth(): number { return unimplementedWarning("getidealvideowidth"); } getidealvideoheight(): number { return unimplementedWarning("getidealvideoheight"); } isminimized(): number { return unimplementedWarning("isminimized"); } minimizeapplication(): void { return unimplementedWarning("minimizeapplication"); } restoreapplication(): void { return unimplementedWarning("restoreapplication"); } activateapplication(): void { return unimplementedWarning("activateapplication"); } getplaylistlength(): number { return unimplementedWarning("getplaylistlength"); } getplaylistindex(): number { return unimplementedWarning("getplaylistindex"); } isdesktopalphaavailable(): boolean { return unimplementedWarning("isdesktopalphaavailable"); } istransparencyavailable(): boolean { return unimplementedWarning("istransparencyavailable"); } onshownotification(): number { this.js_trigger("onShowNotification"); return 1; // return 1 if you implement it } getsonginfotext(): string { return unimplementedWarning("getsonginfotext"); } getvisband(channel: number, band: number): number { return unimplementedWarning("getvisband"); } onviewportchanged(width: number, height: number): void { return unimplementedWarning("onviewportchanged"); } onurlchange(url: string): void { return unimplementedWarning("onurlchange"); } oneqfreqchanged(isiso: number): void { return unimplementedWarning("oneqfreqchanged"); } enumembedguid(num: number): string { return unimplementedWarning("enumembedguid"); } getmetadatastring(filename: string, metadataname: string): string { return unimplementedWarning("getmetadatastring"); } getcurrenttrackrating(): number { return unimplementedWarning("getcurrenttrackrating"); } oncurrenttrackrated(rating: number): void { return unimplementedWarning("oncurrenttrackrated"); } setcurrenttrackrating(rating: number): void { return unimplementedWarning("setcurrenttrackrating"); } getdecodername(playitem: string): string { return unimplementedWarning("getdecodername"); } getalbumart(playitem: string): number { return unimplementedWarning("getalbumart"); } downloadmedia( url: string, destinationPath: string, wantAddToML: boolean, notifyDownloadsList: boolean ): void { return unimplementedWarning("downloadmedia"); } downloadurl( url: string, destination_filename: string, progress_dialog_title: string ): void { return unimplementedWarning("downloadurl"); } ondownloadfinished(url: string, success: boolean, filename: string): void { return unimplementedWarning("ondownloadfinished"); } getdownloadpath(): string { return unimplementedWarning("getdownloadpath"); } setdownloadpath(new_path: string): void { return unimplementedWarning("setdownloadpath"); } enqueuefile(playitem: string): void { return unimplementedWarning("enqueuefile"); } urldecode(url: string): string { return unimplementedWarning("urldecode"); } parseatf(topass: string): string { return unimplementedWarning("parseatf"); } log10(value: number): number { return unimplementedWarning("log10"); } ln(value: number): number { return unimplementedWarning("ln"); } getviewportwidthfromguiobject(g: GuiObject): number { return unimplementedWarning("getviewportwidthfromguiobject"); } getmonitorwidth(): number { return unimplementedWarning("getmonitorwidth"); } getmonitorwidthfrompoint(x: number, y: number): number { return unimplementedWarning("getmonitorwidthfrompoint"); } getmonitorwidthfromguiobject(g: GuiObject): number { return unimplementedWarning("getmonitorwidthfromguiobject"); } onmousemove(x: number, y: number): void { return unimplementedWarning("onmousemove"); } getviewportheightfromguiobject(g: GuiObject): number { return unimplementedWarning("getviewportheightfromguiobject"); } getmonitorheight(): number { return unimplementedWarning("getmonitorheight"); } getmonitorheightfrompoint(x: number, y: number): number { return unimplementedWarning("getmonitorheightfrompoint"); } getmonitorheightfromguiobject(g: GuiObject): number { return unimplementedWarning("getmonitorheightfromguiobject"); } getmonitorleft(): number { return unimplementedWarning("getmonitorleft"); } getmonitorleftfromguiobject(g: GuiObject): number { return unimplementedWarning("getmonitorleftfromguiobject"); } getmonitorleftfrompoint(x: number, y: number): number { return unimplementedWarning("getmonitorleftfrompoint"); } getmonitortop(): number { return unimplementedWarning("getmonitortop"); } getmonitortopfromguiobject(g: GuiObject): number { return unimplementedWarning("getmonitortopfromguiobject"); } getmonitortopfrompoint(x: number, y: number): number { return unimplementedWarning("getmonitortopfrompoint"); } getviewportleftfromguiobject(g: GuiObject): number { return unimplementedWarning("getviewportleftfromguiobject"); } getviewporttopfromguiobject(g: GuiObject): number { return unimplementedWarning("getviewporttopfromguiobject"); } navigateurlbrowser(url: string): void { return unimplementedWarning("navigateurlbrowser"); } onopenurl(url: string): boolean { return unimplementedWarning("onopenurl"); } translate(str: string): string { return unimplementedWarning("translate"); } getstring(table: string, id: number): string { return unimplementedWarning("getstring"); } getlanguageid(): string { return unimplementedWarning("getlanguageid"); } selectfolder( wnd_title: string, wnd_info: string, default_path: string ): string { return unimplementedWarning("selectfolder"); } hasvideosupport(): number { return unimplementedWarning("hasvideosupport"); } clearplaylist(): void { return unimplementedWarning("clearplaylist"); } getsonginfotexttranslated(): string { return unimplementedWarning("getsonginfotexttranslated"); } iswa2componentvisible(guid: string): number { return unimplementedWarning("iswa2componentvisible"); } hidewa2component(guid: string): void { return unimplementedWarning("hidewa2component"); } isproversion(): boolean { return unimplementedWarning("isproversion"); } getwinampversion(): string { return unimplementedWarning("getwinampversion"); } getbuildnumber(): number { return unimplementedWarning("getbuildnumber"); } getfilesize(fullfilename: string): number { return unimplementedWarning("getfilesize"); } } export default System;
the_stack
import * as _ from 'lodash'; import { expect } from 'chai'; import * as validation from '../src/lib/validation'; const almostTooLongText = _.times(255, () => 'a').join(''); describe('validation', () => { describe('checkBooleanish', () => { it('returns true for a truthy or falsey value', () => { expect(validation.checkBooleanish(true)).to.equal(true); expect(validation.checkBooleanish('true')).to.equal(true); expect(validation.checkBooleanish('1')).to.equal(true); expect(validation.checkBooleanish(1)).to.equal(true); expect(validation.checkBooleanish('on')).to.equal(true); expect(validation.checkBooleanish(false)).to.equal(true); expect(validation.checkBooleanish('false')).to.equal(true); expect(validation.checkBooleanish('0')).to.equal(true); expect(validation.checkBooleanish(0)).to.equal(true); expect(validation.checkBooleanish('off')).to.equal(true); }); it('returns false for invalid values', () => { expect(validation.checkBooleanish({})).to.equal(false); expect(validation.checkBooleanish(10)).to.equal(false); expect(validation.checkBooleanish('on1')).to.equal(false); expect(validation.checkBooleanish('foo')).to.equal(false); expect(validation.checkBooleanish(undefined)).to.equal(false); expect(validation.checkBooleanish(null)).to.equal(false); expect(validation.checkBooleanish('')).to.equal(false); }); }); describe('checkFalsey', () => { it('returns false for a truthy value', () => { expect(validation.checkFalsey(true)).to.equal(false); expect(validation.checkFalsey('true')).to.equal(false); expect(validation.checkFalsey('1')).to.equal(false); expect(validation.checkFalsey(1)).to.equal(false); expect(validation.checkFalsey('on')).to.equal(false); }); it('returns true for a falsey value', () => { expect(validation.checkFalsey(false)).to.equal(true); expect(validation.checkFalsey('false')).to.equal(true); expect(validation.checkFalsey('0')).to.equal(true); expect(validation.checkFalsey(0)).to.equal(true); expect(validation.checkFalsey('off')).to.equal(true); }); it('returns false for invalid values', () => { expect(validation.checkFalsey({})).to.equal(false); expect(validation.checkFalsey(10)).to.equal(false); expect(validation.checkFalsey('on1')).to.equal(false); expect(validation.checkFalsey('foo')).to.equal(false); expect(validation.checkFalsey(undefined)).to.equal(false); expect(validation.checkFalsey(null)).to.equal(false); expect(validation.checkFalsey('')).to.equal(false); }); }); describe('checkTruthy', () => { it('returns true for a truthy value', () => { expect(validation.checkTruthy(true)).to.equal(true); expect(validation.checkTruthy('true')).to.equal(true); expect(validation.checkTruthy('1')).to.equal(true); expect(validation.checkTruthy(1)).to.equal(true); expect(validation.checkTruthy('on')).to.equal(true); }); it('returns false for a falsey value', () => { expect(validation.checkTruthy(false)).to.equal(false); expect(validation.checkTruthy('false')).to.equal(false); expect(validation.checkTruthy('0')).to.equal(false); expect(validation.checkTruthy(0)).to.equal(false); expect(validation.checkTruthy('off')).to.equal(false); }); it('returns false for invalid values', () => { expect(validation.checkTruthy({})).to.equal(false); expect(validation.checkTruthy(10)).to.equal(false); expect(validation.checkTruthy('on1')).to.equal(false); expect(validation.checkTruthy('foo')).to.equal(false); expect(validation.checkTruthy(undefined)).to.equal(false); expect(validation.checkTruthy(null)).to.equal(false); expect(validation.checkTruthy('')).to.equal(false); }); }); describe('checkString', () => { it('validates a string', () => { expect(validation.checkString('foo')).to.equal('foo'); expect(validation.checkString('bar')).to.equal('bar'); }); it('returns undefined for empty strings or strings that equal null or undefined', () => { expect(validation.checkString('')).to.be.undefined; expect(validation.checkString('null')).to.be.undefined; expect(validation.checkString('undefined')).to.be.undefined; }); it('returns undefined for things that are not strings', () => { expect(validation.checkString({})).to.be.undefined; expect(validation.checkString([])).to.be.undefined; expect(validation.checkString(123)).to.be.undefined; expect(validation.checkString(0)).to.be.undefined; expect(validation.checkString(null)).to.be.undefined; expect(validation.checkString(undefined)).to.be.undefined; }); }); describe('checkInt', () => { it('returns an integer for a string that can be parsed as one', () => { expect(validation.checkInt('200')).to.equal(200); expect(validation.checkInt('200.00')).to.equal(200); // Allow since no data is being lost expect(validation.checkInt('0')).to.equal(0); expect(validation.checkInt('-3')).to.equal(-3); }); it('returns the same integer when passed an integer', () => { expect(validation.checkInt(345)).to.equal(345); expect(validation.checkInt(-345)).to.equal(-345); }); it("returns undefined when passed something that can't be parsed as int", () => { expect(validation.checkInt({})).to.be.undefined; expect(validation.checkInt([])).to.be.undefined; expect(validation.checkInt('foo')).to.be.undefined; expect(validation.checkInt('')).to.be.undefined; expect(validation.checkInt(null)).to.be.undefined; expect(validation.checkInt(undefined)).to.be.undefined; expect(validation.checkInt('45notanumber')).to.be.undefined; expect(validation.checkInt('000123.45notanumber')).to.be.undefined; expect(validation.checkInt(50.55)).to.be.undefined; // Fractional digits expect(validation.checkInt('50.55')).to.be.undefined; // Fractional digits expect(validation.checkInt('0x11')).to.be.undefined; // Hexadecimal expect(validation.checkInt('0b11')).to.be.undefined; // Binary expect(validation.checkInt('0o11')).to.be.undefined; // Octal }); it('returns undefined when passed a negative or zero value and the positive option is set', () => { expect(validation.checkInt('-3', { positive: true })).to.be.undefined; expect(validation.checkInt('0', { positive: true })).to.be.undefined; }); }); describe('isValidShortText', () => { it('returns true for a short text', () => { expect(validation.isValidShortText('foo')).to.equal(true); expect(validation.isValidShortText('')).to.equal(true); expect(validation.isValidShortText(almostTooLongText)).to.equal(true); }); it('returns false for a text longer than 255 characters', () => expect(validation.isValidShortText(almostTooLongText + 'a')).to.equal( false, )); it('returns false when passed a non-string', () => { expect(validation.isValidShortText({})).to.equal(false); expect(validation.isValidShortText(1)).to.equal(false); expect(validation.isValidShortText(null)).to.equal(false); expect(validation.isValidShortText(undefined)).to.equal(false); }); }); describe('isValidAppsObject', () => { it('returns true for a valid object', () => { const apps = { '1234': { name: 'something', releaseId: 123, commit: 'bar', services: { '45': { serviceName: 'bazbaz', imageId: 34, image: 'foo', environment: {}, labels: {}, }, }, }, }; expect(validation.isValidAppsObject(apps)).to.equal(true); }); it('returns false with an invalid environment', () => { const apps = { '1234': { name: 'something', releaseId: 123, commit: 'bar', services: { '45': { serviceName: 'bazbaz', imageId: 34, image: 'foo', environment: { ' baz': 'bat' }, labels: {}, }, }, }, }; expect(validation.isValidAppsObject(apps)).to.equal(false); }); it('returns false with an invalid appId', () => { const apps = { boo: { name: 'something', releaseId: 123, commit: 'bar', services: { '45': { serviceName: 'bazbaz', imageId: 34, image: 'foo', environment: {}, labels: {}, }, }, }, }; expect(validation.isValidAppsObject(apps)).to.equal(false); }); it('returns true with a missing releaseId', () => { const apps = { '1234': { name: 'something', services: { '45': { serviceName: 'bazbaz', imageId: 34, image: 'foo', environment: {}, labels: {}, }, }, }, }; expect(validation.isValidAppsObject(apps)).to.equal(true); }); it('returns false with an invalid releaseId', () => { const apps = { '1234': { name: 'something', releaseId: '123a', services: { '45': { serviceName: 'bazbaz', imageId: 34, image: 'foo', environment: {}, labels: {}, }, }, }, }; expect(validation.isValidAppsObject(apps)).to.equal(false); }); }); describe('isValidDependentDevicesObject', () => { it('returns true for a valid object', () => { const devices: Dictionary<any> = {}; devices[almostTooLongText] = { name: 'foo', apps: { '234': { config: { bar: 'baz' }, environment: { dead: 'beef' }, }, }, }; expect(validation.isValidDependentDevicesObject(devices)).to.equal(true); }); it('returns false with a missing apps object', () => { const devices = { abcd1234: { name: 'foo', }, }; expect(validation.isValidDependentDevicesObject(devices)).to.equal(false); }); it('returns false with an invalid environment', () => { const devices = { abcd1234: { name: 'foo', apps: { '234': { config: { bar: 'baz' }, environment: { dead: 1 }, }, }, }, }; expect(validation.isValidDependentDevicesObject(devices)).to.equal(false); }); it('returns false if the uuid is too long', () => { const devices: Dictionary<any> = {}; devices[almostTooLongText + 'a'] = { name: 'foo', apps: { '234': { config: { bar: 'baz' }, environment: { dead: 'beef' }, }, }, }; expect(validation.isValidDependentDevicesObject(devices)).to.equal(false); }); }); });
the_stack
import { DoData, EditorClipboard, STATE_CLIPBOARD } from "./EditorClipboard"; import { File } from "../common/File"; import fs from "fs"; import { Logger } from "../common/Logger"; import { StringUtils, StringLineToken } from "../common/StringUtils"; import { FileReader, convertAttrToStatMode } from "../panel/FileReader"; import { T } from "../common/Translation"; import * as jschardet from "jschardet"; import * as iconv from "iconv-lite"; const log = Logger( "editor" ); export interface IViewBuffer { textLine?: number; // Text Position viewLine?: number; // screen view position nextLineNum?: number; // if over the one line, line number. isNext?: boolean; // Is this line over the one line? text?: string; selectInfo?: { // selected position all?: boolean; // selected line all start?: number; // selected start position end?: number; // selected end position }; } export interface IEditSelect { x1: number; y1: number; // select first position(x,y) x2: number; y2: number; // select last position (x,y) } export enum EDIT_MODE { EDIT, /// Edit Mode SELECT, /// Select Mode BLOCK, /// Block Select Mode SHIFT_SELECT /// Shift Mode } export abstract class Editor { line: number = 0; column: number = 0; curColumnMax: number = 0; firstLine: number = 0; lastLine: number = 0; viewCol: number = 0; viewLine: number = 0; curLine: number = 0; curColumn: number = 0; isInsert: boolean = false; isIndentMode: boolean = false; editMode: EDIT_MODE = EDIT_MODE.EDIT; editSelect: IEditSelect = { x1: 0, x2: 0, y1: 0, y2: 0 }; tabSize: number = 8; isReadOnly: boolean = false; isDosMode: boolean = false; title: string = ""; encoding: string = "utf8"; file: File = null; isBackup: boolean = false; findStr: string = ""; indexFindPosX: number = 0; indexFindPosY: number = 0; viewBuffers: IViewBuffer[]; buffers: string[]; doInfo: DoData[]; lastDoInfoLength: number = 0; // eslint-disable-next-line @typescript-eslint/no-empty-function constructor() { } destory() { this.doInfo = []; } abstract postLoad(): void; abstract postUpdateLines( line?: number, height?: number ): void; abstract inputBox(title: string, text: string, inputedText?: string, buttons?: string[]): Promise<string[]>; abstract messageBox(title, text, buttons?: string[]): Promise<string>; public selectSort(editSelect: IEditSelect) { if ( !editSelect ) return; const swap = ( obj: any, keyA: string, keyB: string ) => { const tmp = obj[keyA]; obj[keyA] = obj[keyB]; obj[keyB] = tmp; }; if ( editSelect.y1 > editSelect.y2 ) { swap( editSelect, "y1", "y2" ); swap( editSelect, "x1", "x2" ); } else if ( editSelect.y1 === editSelect.y2 ) { if ( editSelect.x1 > editSelect.x2 ) { swap( editSelect, "y1", "y2" ); swap( editSelect, "x1", "x2" ); } } } public selectedDel() { if ( this.isReadOnly ) return; this.selectSort(this.editSelect); if ( this.editSelect.y2 >= this.buffers.length ) { this.editMode = EDIT_MODE.EDIT; return; } if ( this.editSelect.y1 === this.editSelect.y2 ) { const str = this.buffers[ this.editSelect.y1 ]; this.doInfo.push( new DoData(this.curLine, this.curColumn, [ str ] )); const str1 = StringUtils.scrSubstr(str, 0, this.editSelect.x1); const str2 = StringUtils.scrSubstr(str, this.editSelect.x2, StringUtils.strWidth(str) - this.editSelect.x2 ); this.buffers[ this.editSelect.y1 ] = str1 + str2; } else { const saveTexts = []; const str1 = this.buffers[ this.editSelect.y1 ]; const str2 = this.buffers[ this.editSelect.y2 ]; const str3 = StringUtils.scrSubstr(str1, 0, this.editSelect.x1); const str4 = StringUtils.scrSubstr(str2, this.editSelect.x2); const str = str3 + str4; for ( let y = this.editSelect.y1; y < this.editSelect.y2; ++y ) { if ( this.editSelect.y1 === y ) { saveTexts.push( str1 ); this.buffers[this.editSelect.y1] = str; } else if ( this.editSelect.y2 === y ) { saveTexts.push( str2 ); this.buffers[this.editSelect.y2] = str; this.buffers.splice(this.editSelect.y1 + 1, 1); } else { saveTexts.push( this.buffers[ this.editSelect.y1 + 1 ] ); this.buffers.splice(this.editSelect.y1 + 1, 1); } } this.postUpdateLines( this.editSelect.y1, this.editSelect.y2 - this.editSelect.y1 + 1 ); this.doInfo.push( new DoData(this.editSelect.y1, this.editSelect.x1, saveTexts )); } this.curLine = this.editSelect.y1; this.curColumn = this.editSelect.x1; this.curColumnMax = this.curColumn; if ( this.curLine < this.firstLine ) this.firstLine = this.curLine - 10; this.editMode = EDIT_MODE.EDIT; if ( this.buffers.length === 0 ) { this.buffers.push( " " ); } } public screenMemSave( line: number, column: number ) { if ( this.curLine > 0 ) { if ( this.curLine >= this.buffers.length) this.curLine = this.buffers.length - 1; if ( this.curLine <= this.firstLine ) this.firstLine = this.firstLine - 1; if ( this.firstLine <= 0 ) this.firstLine = 0; if ( this.lastLine - this.firstLine >= 10 && this.lastLine - this.curLine <= 0 ) { if ( this.viewBuffers.length >= this.line ) { if ( this.firstLine <= this.buffers.length ) { this.firstLine++; } if ( this.buffers.length <= this.line - 5 ) { this.firstLine = 0; } } } } const isInside = (start: number, end: number, pos: number) => { return (start <= pos && end >= pos); }; const editSelect = { ...this.editSelect }; this.selectSort(editSelect); log.debug( "screenMemSave: line [%d] column [%d]", line, column); for(;;) { let viewLine = this.firstLine; if (viewLine < 0) return; this.viewBuffers = []; const strLineToken = new StringLineToken(); for ( let t = 0; t < line; t++ ) { if ( line <= this.viewBuffers.length ) { log.debug( "this.viewBuffers.length [%d] line [%d]", this.viewBuffers.length, line ); break; } if ( !strLineToken.next(true) ) { if ( viewLine >= this.buffers.length ) break; strLineToken.setString( this.buffers[viewLine++], column ); } const { text: viewStr, pos, endPos } = strLineToken.getToken() || { text: "", pos: 0 }; const lineInfo: IViewBuffer = {}; lineInfo.viewLine = t; lineInfo.textLine = viewLine - 1; lineInfo.text = viewStr; lineInfo.isNext = strLineToken.next(true); lineInfo.nextLineNum = strLineToken.curLine; if ( this.editMode === EDIT_MODE.SELECT || this.editMode === EDIT_MODE.SHIFT_SELECT ) { const selectInfo: any = {}; const { x1, y1, x2, y2 } = editSelect; if ( y1 < lineInfo.textLine && y2 > lineInfo.textLine ) { selectInfo.all = true; } else if ( y1 === lineInfo.textLine && y2 === lineInfo.textLine ) { if ( isInside(pos, endPos, x1) && isInside(pos, endPos, x2) ) { selectInfo.start = x1 - pos; selectInfo.end = x2 - pos; } else if ( isInside(pos, endPos, x1) ) { selectInfo.start = x1 - pos; selectInfo.end = -1; } else if ( isInside(pos, endPos, x2) ) { selectInfo.start = -1; selectInfo.end = x2 - pos; } else if ( isInside(x1, x2, pos) && isInside(x1, x2, endPos) ) { selectInfo.all = true; } } else if ( y1 === lineInfo.textLine ) { if ( isInside(pos, endPos, x1) ) { selectInfo.start = x1 - pos; selectInfo.end = -1; } else if ( x1 <= pos ) { selectInfo.all = true; } } else if ( y2 === lineInfo.textLine ) { if ( isInside(pos, endPos, x2) ) { selectInfo.start = -1; selectInfo.end = x2; } else if ( x2 >= endPos ) { selectInfo.all = true; } } lineInfo.selectInfo = selectInfo; /* if ( typeof(lineInfo.selectInfo.start) === "number" ) { log.debug( "SELECT1 [%d/%d] ~ [%d/%d] pos [%d/%d] selectInfo [%j] lineInfo [%j]", editSelect.x1, editSelect.y1, editSelect.x2, editSelect.y2, pos, endPos, selectInfo, lineInfo ); } */ } this.viewBuffers.push( lineInfo ); strLineToken.next(); } this.lastLine = viewLine - 1; //log.debug( "this.viewBuffers.length [%d] this.lastLine [%d]", this.viewBuffers.length, this.lastLine ); if ( this.viewBuffers.length > line - 3 ) { if ( this.lastLine === this.curLine && this.lastLine < this.viewBuffers.length && this.viewBuffers[this.lastLine].isNext ) { this.firstLine++; continue; } if ( this.lastLine < this.curLine ) { this.firstLine++; continue; } } break; } } setViewTitle( title = "" ) { this.title = title; } setEditor( backup: false ) { this.isBackup = backup; } getFile() { return this.file; } newFile( file: File ) { this.file = file; this.buffers = [ "" ]; this.encoding = "utf8"; this.firstLine = 0; this.curLine = 0; this.curColumn = 0; this.curColumnMax = 0; this.isInsert = true; this.findStr = ""; this.indexFindPosX = 0; this.indexFindPosY = 0; this.doInfo = []; if ( this.file ) { this.setViewTitle(this.file.fullname); } } load( file: File, _isReadonly: boolean = false ): boolean { this.newFile(file); if ( file && file.size > 3000000 ) { throw new Error("file size is too large. " + file.size); } const fsData: Buffer = fs.readFileSync( file.fullname ) as any; if ( !fsData ) { return false; } const binaryRead = () => { this.buffers = []; for ( let i = 0; i < fsData.byteLength; i += 20 ) { this.buffers.push( fsData.slice(i, i+20).toString("hex") + "\t[" + fsData.slice(i, i+20).toString("ascii") + "]" ); } this.encoding = "binary"; this.isReadOnly = true; }; let result = null; try { result = jschardet.detect( fsData ); } catch ( e ) { log.error( e ); } log.info( "jschardet: %j", result ); try { let data = null; if ( result && result.encoding ) { this.encoding = result.encoding; if ( [ "utf8", "ascii" ].indexOf(this.encoding) > -1 ) { data = fsData.toString("utf8"); } else { data = iconv.decode(fsData, this.encoding); } this.buffers = []; let dosMode = false; data.split("\n").map( (item) => { const item2 = item.replace( "\r", "" ); if ( item2 !== item ) { dosMode = true; } this.buffers.push( item2 ); }); this.isDosMode = dosMode; } else { binaryRead(); } } catch ( e ) { log.error( e ); binaryRead(); } this.postLoad(); return true; } save( file: File, encoding: string = null, isBackup: boolean = false ): boolean { const fileName = file.fullname; if ( !fileName ) { return false; } const mode = convertAttrToStatMode(file) || 0o644; const tmpFileName = fileName + ".tmp"; try { const saveData = this.buffers.join( this.isDosMode ? "\r\n" : "\n" ); if ( this.encoding !== "utf8" ) { const bufSaveData: Buffer = iconv.encode(saveData, this.encoding); fs.writeFileSync( tmpFileName, bufSaveData, { mode }); } else { fs.writeFileSync( tmpFileName, saveData, { encoding: encoding || "utf8", mode }); } } catch( e ) { log.error( e ); return false; } if ( isBackup ) { try { fs.renameSync( fileName, fileName + ".back" ); } catch( e ) { log.error( e ); } } try { fs.renameSync( tmpFileName, fileName ); fs.chmodSync( fileName, mode ); log.debug( "SAVE - CHMOD [%s] [%d]", fileName, mode ); } catch( e ) { log.error( e ); return false; } return true; } keyLeft() { if ( this.curColumn > 0 ) { const text = StringUtils.scrSubstr(this.buffers[this.curLine], 0, this.curColumn); this.curColumn = StringUtils.strWidth(text.substr(0, text.length - 1)); } else if ( this.curLine > 0) { this.curColumn = StringUtils.strWidth(this.buffers[ --this.curLine ]); } this.keyPressCommon(); } keyRight() { const str = this.buffers[this.curLine]; const strlen = StringUtils.strWidth(str); if ( strlen > this.curColumn ) { const text = StringUtils.scrSubstr(this.buffers[this.curLine], this.curColumn, StringUtils.strWidth("\t")); if ( text ) { this.curColumn += StringUtils.strWidth(text.substr(0, 1)); } } else if ( strlen === this.curColumn && this.curLine !== this.buffers.length - 1 ) { this.curLine++; this.curColumn = 0; } this.keyPressCommon(); } keyUp() { if ( this.curLine > 0 ) this.curLine--; if ( this.curColumnMax < this.curColumn ) { this.curColumnMax = this.curColumn; } else { this.curColumn = this.curColumnMax; } const strlen = StringUtils.strWidth(this.buffers[this.curLine]); if ( strlen < this.curColumn ) { this.curColumn = strlen; } else { this.keyRight(); this.keyLeft(); } this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; if ( this.editMode === EDIT_MODE.SHIFT_SELECT ) this.editMode = EDIT_MODE.EDIT; } keyDown() { if ( this.curLine < this.buffers.length - 1 ) this.curLine++; if ( this.curColumnMax < this.curColumn ) { this.curColumnMax = this.curColumn; } else { this.curColumn = this.curColumnMax; } const strlen = StringUtils.strWidth(this.buffers[this.curLine]); if ( strlen < this.curColumn ) { this.curColumn = strlen; } else { this.keyRight(); this.keyLeft(); } this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; if ( this.editMode === EDIT_MODE.SHIFT_SELECT ) this.editMode = EDIT_MODE.EDIT; } shiftMode( func: () => void ) { if ( this.editMode !== EDIT_MODE.SHIFT_SELECT ) { this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; } func(); this.editMode = EDIT_MODE.SELECT; } keyShiftLeft() { this.shiftMode( () => this.keyLeft() ); } keyShiftRight() { this.shiftMode( () => this.keyRight() ); } keyShiftUp() { this.shiftMode( () => this.keyUp() ); } keyShiftDown() { this.shiftMode( () => this.keyDown() ); } keyInsert() { this.isInsert = !this.isInsert; } keyDelete() { if ( this.isReadOnly ) return; if ( this.editMode !== EDIT_MODE.EDIT ) { this.selectedDel(); this.editMode = EDIT_MODE.EDIT; } let line = this.buffers[this.curLine]; if ( this.curColumn < StringUtils.strWidth(line) ) { this.doInfo.push( new DoData(this.curLine, this.curColumn, [ line ])); const firstText = StringUtils.scrSubstr(line, 0, this.curColumn); const lastText = line.substr(firstText.length + 1); line = firstText + lastText; this.buffers[this.curLine] = line; this.postUpdateLines(this.curLine); } else if ( this.curLine + 1 < this.buffers.length ) { const line2 = this.buffers[this.curLine + 1]; this.doInfo.push( new DoData(this.curLine, this.curColumn, [ line2 ] )); this.buffers[this.curLine] = line + line2; this.buffers.splice( this.curLine, 1 ); this.postUpdateLines(this.curLine); } this.curColumnMax = this.curColumn; if ( this.buffers.length === 0 ) { this.buffers.push( "" ); } } keyBS() { if ( this.isReadOnly ) return; if ( this.editMode !== EDIT_MODE.EDIT ) { this.selectedDel(); this.editMode = EDIT_MODE.EDIT; this.curLine = this.editSelect.y1; this.curColumn = this.editSelect.x1; this.curColumnMax = this.curColumn; } if ( this.curLine === 0 && this.curColumn === 0 ) return; if ( this.buffers.length > this.curLine ) { const line = this.buffers[this.curLine]; let line2 = ""; if ( this.curColumn === 0 && this.buffers.length > 0 && this.curLine > 0 ) { line2 = this.buffers[this.curLine - 1]; this.doInfo.push( new DoData(this.curLine - 1, this.curColumn, [ line2, line ] )); const tmpLine2Width = StringUtils.strWidth( line2 ); this.buffers[ this.curLine - 1 ] = line2 + line; this.buffers.splice( this.curLine, 1 ); this.postUpdateLines(this.curLine); this.keyUp(); this.curColumn = tmpLine2Width; } else { const strSize = StringUtils.strWidth( this.buffers[ this.curLine ] ); if ( this.curColumn <= strSize ) { this.doInfo.push( new DoData(this.curLine, this.curColumn, [ line ] )); let firstText = StringUtils.scrSubstr( this.buffers[this.curLine], 0, this.curColumn ); const lastText = this.buffers[this.curLine].substr(firstText.length); firstText = firstText.substr(0, firstText.length - 1); line2 = firstText + lastText; this.curColumn = StringUtils.strWidth(firstText); } this.buffers[ this.curLine ] = line2; this.postUpdateLines( this.curLine ); this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; } } this.curColumnMax = this.curColumn; } keyTab() { if ( this.isReadOnly ) return; if ( this.editMode !== EDIT_MODE.EDIT ) { this.selectSort( this.editSelect ); const save: string[] = []; for ( let y = this.editSelect.y1; y <= this.editSelect.y2; y++ ) { save.push( this.buffers[ y ] ); } this.doInfo.push( new DoData(this.editSelect.y1, 0, save, -1 )); for ( let y = this.editSelect.y1; y <= this.editSelect.y2; y++ ) { this.buffers[y] = "\t" + this.buffers[y]; } this.postUpdateLines( this.editSelect.y1, this.editSelect.y2 - this.editSelect.y1 + 1); } else { this.inputData( "\t" ); } } keyUntab() { if ( this.isReadOnly ) return; if ( this.editMode !== EDIT_MODE.EDIT ) { this.selectSort( this.editSelect ); const save: string[] = []; for ( let y = this.editSelect.y1; y <= this.editSelect.y2; y++ ) { save.push( this.buffers[ y ] ); } this.doInfo.push( new DoData(this.editSelect.y1, 0, save, -1 )); for ( let y = this.editSelect.y1; y <= this.editSelect.y2; y++ ) { if ( this.buffers[y].substr(0, 1) === "\t" ) { this.buffers[y] = this.buffers[y].substr(1); } } } else { if ( this.buffers[this.curLine].substr(0, 1) === "\t" ) { this.buffers[this.curLine] = this.buffers[this.curLine].substr(1); } } } indentMode() { this.isIndentMode = !this.indentMode; } inputData( textStr: string ) { if ( this.isReadOnly ) return; if ( this.editMode !== EDIT_MODE.EDIT ) { this.selectedDel(); this.editMode = EDIT_MODE.EDIT; } if ( this.curLine < this.buffers.length ) { let line = this.buffers[this.curLine] || ""; this.doInfo.push( new DoData(this.curLine, this.curColumn, [line]) ); if ( this.isInsert ) { line = StringUtils.scrSubstr( line, 0, this.curColumn) + textStr + StringUtils.scrSubstr( line, this.curColumn ); } else { line = StringUtils.scrSubstr( line, 0, this.curColumn) + textStr + StringUtils.scrSubstr( line, this.curColumn + StringUtils.strWidth(textStr) ); } this.buffers[this.curLine] = line; this.curColumn += StringUtils.strWidth(textStr); } this.curColumnMax = this.curColumn; } keyHome() { const line = this.buffers[this.curLine]; let ne = 0; const old = this.curColumn; for ( let n = 0; n < line.length; n++ ) { if (line[n] !== " " && line[n] !== "\t") { ne = n; break; } } this.curColumn = old === ne ? 0 : StringUtils.strWidth(line.substr(0, ne)); this.keyPressCommon(); } keyEnd() { if ( this.buffers[this.curLine] ) { this.curColumn = StringUtils.strWidth( this.buffers[this.curLine] ); } else { this.curColumn = 0; } this.keyPressCommon(); } keyPgUp() { const size = this.lastLine - this.firstLine; const cur = this.curLine - this.firstLine; if ( this.firstLine === 0 ) { this.curLine = 0; } else { this.firstLine = this.firstLine - size; if ( this.firstLine < 0 ) this.firstLine = 0; this.curLine = this.firstLine + cur; if ( this.curLine <= 0 ) this.curLine = 0; } if ( this.curColumnMax < this.curColumn ) { this.curColumnMax = this.curColumn; } else { this.curColumn = this.curColumnMax; } const strlen = StringUtils.strWidth(this.buffers[this.curLine]); if ( strlen < this.curColumn ) { this.curColumn = strlen; } this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; if ( this.editMode === EDIT_MODE.SHIFT_SELECT ) this.editMode = EDIT_MODE.EDIT; } keyPgDn() { const size = this.lastLine - this.firstLine; const cur = this.curLine - this.firstLine; if ( this.buffers.length < this.line - 1 ) { this.curLine = this.buffers.length - 1; } else if ( this.firstLine > this.buffers.length - this.line + 1 ) { this.curLine = this.buffers.length - 1; } else { this.curLine = this.firstLine + size + cur; this.firstLine = this.curLine - cur; if ( this.firstLine > this.buffers.length - this.line + 1 ) { this.firstLine = this.buffers.length - this.line + 1; } if ( this.buffers.length <= this.curLine ) { this.curLine = this.buffers.length - 1; } } if ( this.curColumnMax < this.curColumn ) { this.curColumnMax = this.curColumn; } else { this.curColumn = this.curColumnMax; } const strlen = StringUtils.strWidth(this.buffers[this.curLine]); if ( strlen < this.curColumn ) { this.curColumn = strlen; } this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; if ( this.editMode === EDIT_MODE.SHIFT_SELECT ) this.editMode = EDIT_MODE.EDIT; } keyEnter() { if ( this.isReadOnly ) return; if ( this.editMode !== EDIT_MODE.EDIT ) { this.selectedDel(); this.editMode = EDIT_MODE.EDIT; } const line = this.buffers[this.curLine]; let p1 = ""; if ( this.indentMode ) { for ( let n = 0; n < line.length; n++ ) { if (line[n] !== " " && line[n] !== "\t") { p1 = line.substr(0, n); break; } } } this.doInfo.push( new DoData(this.curLine, this.curColumn, [line], 2) ); if ( this.buffers.length > this.curLine ) { const firstLine = StringUtils.scrSubstr(line, 0, this.curColumn); const lastLine = p1 + line.substr(firstLine.length); this.buffers.splice( this.curLine, 0, lastLine ); this.buffers[ this.curLine ] = firstLine; this.buffers[ this.curLine+1 ] = lastLine; this.postUpdateLines(this.curLine); } else { this.buffers.push(p1); } this.screenMemSave( this.line, this.column ); this.curColumn = p1.length; this.curColumnMax = this.curColumn; log.debug( "CUR COL: [%d]", this.curColumn); this.keyDown(); } // eslint-disable-next-line @typescript-eslint/no-empty-function keyMouse() {} async gotoLinePromise() { const [ text, button ] = await this.inputBox( T("EditorMsg.TITLE_GOTO_NUMBER"), T("EditorMsg.GOTO_NUMBER"), "", [ T("OK"), T("Cancel") ] ); if ( button === T("Cancel") ) { return; } let number = -1; try { number = parseInt( text ); } catch ( e ) { await this.messageBox( T("ERROR"), T("EditorMsg.GOTO_NUMBER_INVALID") ); } if ( number > -1 && number < this.buffers.length ) { this.curLine = number - 1; if ( this.curLine <= 0 ) this.curLine = 0; this.firstLine = this.curLine - 10; if ( this.firstLine <= 0 ) this.firstLine = 0; } else { this.curLine = this.buffers.length - 1; this.firstLine = this.curLine - 10; } this.editMode = EDIT_MODE.EDIT; } gotoTop() { this.curLine = 0; this.firstLine = 0; this.editMode = EDIT_MODE.EDIT; } gotoLast() { this.curLine = this.buffers.length - 1; this.firstLine = this.curLine - 10; this.editMode = EDIT_MODE.EDIT; } copy() { if ( this.editMode === EDIT_MODE.EDIT ) return; this.selectSort( this.editSelect ); if ( this.editSelect.y2 >= this.buffers.length ) { this.editMode = EDIT_MODE.EDIT; return; } const strTexts = []; if ( this.editSelect.y1 === this.editSelect.y2 ) { const str = StringUtils.scrSubstr(this.buffers[ this.editSelect.y1 ], this.editSelect.x1, this.editSelect.x2 - this.editSelect.x1 ); strTexts.push( str ); } else { for ( let y = this.editSelect.y1; y <= this.editSelect.y2; y++ ) { let str = ""; if ( this.editSelect.y1 === y ) { str = StringUtils.scrSubstr(this.buffers[y], this.editSelect.x1 ); } else if ( this.editSelect.y2 === y ) { str = StringUtils.scrSubstr(this.buffers[y], 0, this.editSelect.x2 ); } else { str = this.buffers[y]; } strTexts.push( str ); } } EditorClipboard.instance().set( strTexts, STATE_CLIPBOARD.Copy ); this.curColumnMax = this.curColumn; this.editMode = EDIT_MODE.EDIT; } cut() { if ( this.editMode === EDIT_MODE.EDIT ) return; this.selectSort( this.editSelect ); if ( this.editSelect.y2 >= this.buffers.length ) { this.editMode = EDIT_MODE.EDIT; return; } const strTexts = []; if ( this.editSelect.y1 === this.editSelect.y2 ) { const str = StringUtils.scrSubstr(this.buffers[ this.editSelect.y1 ], this.editSelect.x1, this.editSelect.x2 - this.editSelect.x1 ); strTexts.push( str ); } else { for ( let y = this.editSelect.y1; y <= this.editSelect.y2; y++ ) { let str = ""; if ( this.editSelect.y1 === y ) { str = StringUtils.scrSubstr(this.buffers[y], this.editSelect.x1 ); } else if ( this.editSelect.y2 === y ) { str = StringUtils.scrSubstr(this.buffers[y], 0, this.editSelect.x2 ); } else { str = this.buffers[y]; } strTexts.push( str ); } } EditorClipboard.instance().set( strTexts, STATE_CLIPBOARD.Cut ); this.selectedDel(); this.curColumnMax = this.curColumn; this.editMode = EDIT_MODE.EDIT; } paste() { if ( this.isReadOnly ) return; if ( this.editMode !== EDIT_MODE.EDIT ) this.selectedDel(); const clips = EditorClipboard.instance().get(); const str = this.buffers[this.curLine]; const str1 = StringUtils.scrSubstr(str, 0, this.curColumn ); const str2 = StringUtils.scrSubstr(str, this.curColumn ); if ( clips.length === 1 ) { const clipStr = clips[0]; this.doInfo.push( new DoData(this.curLine, this.curColumn, [this.buffers[this.curLine]]) ); this.buffers[ this.curLine] = str1 + clips[0] + str2; this.curColumn += StringUtils.strWidth(clipStr); this.postUpdateLines( this.curLine ); } else { this.doInfo.push( new DoData(this.curLine, this.curColumn, [ this.buffers[this.curLine] ], clips.length ) ); for ( let y = 0; y < clips.length; y++ ) { if ( y === 0 ) { this.buffers[ this.curLine ] = str + clips[y]; } else if ( y === clips.length - 1 ) { const clip = clips[y]; const clip2 = clip + str2; this.buffers.splice( this.curLine + y, 0, clip2 ); this.curColumn = StringUtils.strWidth(clip2); this.curLine += clips.length - 1; } else { this.buffers.splice( this.curLine + y, 0, clips[y] ); } } this.postUpdateLines( this.curLine, clips.length + 1 ); } if ( this.curLine > this.lastLine ) { this.screenMemSave( this.curLine, this.curColumn ); } this.curColumnMax = this.curColumn; this.editMode = EDIT_MODE.EDIT; } undo() { let doData: DoData = null; if ( !this.doInfo.length ) return; doData = this.doInfo[ this.doInfo.length - 1 ]; if ( !doData ) return; const line = doData.line; if ( doData.delSize === -1 ) { // paste tab for ( let n = 0; n < doData.texts.length; n++ ) { this.buffers[ line + n ] = doData.texts[n]; } this.postUpdateLines( line, doData.texts.length ); } else if ( doData.delSize === 0 ) { // removed data (insert) for( let n = 0; n < doData.texts.length; n++ ) { if ( n === 0 ) { this.buffers[line] = doData.texts[n]; } else { this.buffers.splice( line + n, 0, doData.texts[n] ); } } this.postUpdateLines( line, doData.texts.length ); if ( doData.texts.length > 0 ) { this.curLine = line + doData.texts.length - 1; } if ( this.curLine < this.firstLine ) { this.firstLine = this.curLine; } } else { // inputed data (delete) const delSize = doData.delSize; let str; if ( doData.texts.length === 1 ) { str = doData.texts[0]; } for ( let y = line; y <= line+delSize; ++y ) { if ( line === y || line+delSize === y ) { this.buffers[line] = str; } else { this.buffers.splice( line + 1, 1 ); } } this.curLine = doData.line; this.postUpdateLines( line ); if ( this.curLine < this.firstLine ) { this.firstLine = this.curLine; } } this.curColumn = doData.column; this.doInfo.pop(); this.curColumnMax = this.curColumn; } keyEscape() { if ( this.editMode !== EDIT_MODE.EDIT ) this.editMode = EDIT_MODE.EDIT; } select() { if ( this.editMode === EDIT_MODE.SELECT ) this.editMode = EDIT_MODE.EDIT; else this.editMode = EDIT_MODE.SELECT; this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; this.editSelect.x1 = this.curColumn; this.editSelect.y1 = this.curLine; } selectAll() { this.editMode = EDIT_MODE.SHIFT_SELECT; this.editSelect.x1 = 0; this.editSelect.y1 = 0; this.editSelect.x2 = StringUtils.strWidth( this.buffers[this.buffers.length - 1] ); this.editSelect.y2 = this.buffers.length - 1; } blockSelect() { this.editMode = EDIT_MODE.BLOCK; this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; this.editSelect.x1 = this.curColumn; this.editSelect.y1 = this.curLine; } async fileNewPromise(): Promise<boolean> { if ( this.isReadOnly ) { await this.messageBox( T("Error"), T("EditorMsg.READ_ONLY_CURRENT_FILE") ); return false; } if ( this.lastDoInfoLength !== this.doInfo.length ) { const result = await this.messageBox( T("EditorMsg.NewFile"), T("EditorMsg.QUESTION_SAVE_FILE"), [ T("Yes"), T("No") ] ); if ( result === T("Yes") ) { await this.fileSavePromise(); } } const [ fileName, button ] = await this.inputBox( T("EditorMsg.NewFile"), T("EditorMsg.INPUT_FILENAME"), "", [ T("OK"), T("Cancel")] ); if ( button === T("Cancel") ) { return false; } if ( !fileName ) { return false; } const file = await FileReader.createFile( fileName, { virtualFile: true } ); this.newFile( file ); return true; } async fileSavePromise(): Promise<boolean> { if ( this.isReadOnly ) { await this.messageBox( T("Error"), T("EditorMsg.UNABLE_FILE_WRITE") ); return false; } try { if ( this.save( this.file, this.encoding, this.isBackup ) ) { this.lastDoInfoLength = this.doInfo.length; return true; } } catch( e ) { log.error( e ); await this.messageBox( T("Error"), T("EditorMsg.UNABLE_FILE_WRITE") + " " + e.message ); } return false; } async fileSaveAsPromise(): Promise<boolean> { const [ fileName, button ] = await this.inputBox( T("EditorMsg.NewFile"), T("EditorMsg.INPUT_FILENAME"), "", [ T("OK"), T("Cancel")]); if ( button === T("Cancel")) { return false; } if ( !fileName ) { return false; } try { this.file = await FileReader.createFile( fileName ); if ( this.save( this.file, this.encoding, this.isBackup ) ) { this.lastDoInfoLength = this.doInfo.length; } this.setViewTitle(this.file.fullname); } catch( e ) { log.error( e ); await this.messageBox( T("Error"), T("EditorMsg.UNABLE_FILE_WRITE") + " " + e.message ); } return true; } async findPromise() { const find = this.findStr; const [ inputText, button ] = await this.inputBox( T("Find"), T("EditorMsg.INPUT_SEARCH_TEXT"), find, [ T("OK"), T("Cancel")] ); if ( button === T("Cancel")) { return; } if ( !inputText ) { return; } this.findStr = inputText; this.indexFindPosX = 0; this.indexFindPosY = 0; await this.findNextPromise(); } async findNextPromise() { if ( !this.findStr ) return; if ( this.editMode === EDIT_MODE.EDIT ) { this.indexFindPosX = 0; this.indexFindPosY = this.curLine; } for(;;) { for( let n = this.indexFindPosY; n < this.buffers.length; n++ ) { const idx = this.buffers[n].indexOf(this.findStr, this.indexFindPosX); if ( idx > -1 ) { const textSize = StringUtils.strWidth(this.findStr); this.indexFindPosX = idx + textSize; this.indexFindPosY = n; this.editMode = EDIT_MODE.SHIFT_SELECT; this.editSelect.x1 = idx; this.editSelect.y1 = n; this.editSelect.x2 = idx + textSize; this.editSelect.y2 = n; this.curColumn = idx + textSize; this.curLine = n; this.curColumnMax = this.curColumn; this.firstLine = this.curLine - 10; return; } this.indexFindPosX = 0; } this.indexFindPosY = 0; const result = await this.messageBox( T("EditorMsg.FIND_NEXT"), T("EditorMsg.FIND_END_DOCUMENT"), [ T("Yes"), T("No") ] ); if ( result === T("Yes") ) { break; } } } async filePreviousPromise() { if ( !this.findStr ) return; if ( this.editMode === EDIT_MODE.EDIT ) { this.indexFindPosX = 0; this.indexFindPosY = this.curLine; } this.indexFindPosX -= StringUtils.strWidth(this.findStr); for(;;) { for( let n = this.indexFindPosY; n >= 0; --n ) { const idx = this.buffers[n].lastIndexOf(this.findStr); if ( idx > -1 ) { const textSize = StringUtils.strWidth(this.findStr); this.indexFindPosX = idx; this.indexFindPosY = n; this.editMode = EDIT_MODE.SHIFT_SELECT; this.editSelect.x1 = idx; this.editSelect.y1 = n; this.editSelect.x2 = idx + textSize; this.editSelect.y2 = n; this.curColumn = idx + textSize; this.curLine = n; this.curColumnMax = this.curColumn; this.firstLine = this.curLine - 10; return; } if ( n > 0 ) { this.indexFindPosX = StringUtils.strWidth(this.buffers[n-1]); } } this.indexFindPosY = this.buffers.length - 1; const result = await this.messageBox( T("FIND_PREVIOUS"), T("EditorMsg.FIND_FIRST_DOCUMENT"), [ T("Yes"), T("No") ] ); if ( result === T("Yes") ) { break; } } } async quitPromise(): Promise<boolean> { if ( this.isReadOnly ) { this.destory(); return true; } log.debug( "DO INFO [%j]", this.doInfo ); if ( this.lastDoInfoLength !== this.doInfo.length ) { const result = await this.messageBox( T("Save"), T("EditorMsg.QUIT_QUESTION_UNSAVED"), [ T("Yes"), T("No"), T("Cancel") ]); if ( result === T("Yes") ) { await this.fileSavePromise(); } if ( result === T("No") ) { log.debug( T("No") ); } else { return false; } } this.destory(); return true; } isEditMode() { return this.editMode === EDIT_MODE.EDIT; } keyPressCommon() { this.editSelect.x2 = this.curColumn; this.editSelect.y2 = this.curLine; this.curColumnMax = this.curColumn; if ( this.editMode === EDIT_MODE.SHIFT_SELECT ) { this.editMode = EDIT_MODE.EDIT; } } }
the_stack
import { Component, OnInit, ComponentFactoryResolver, ReflectiveInjector, ElementRef ,EventEmitter, Output, Inject, Input,ViewChild} from '@angular/core'; import {FilterTagsComponent} from '../../secondary-components/filter-tags/filter-tags.component'; import { Filter } from '../../secondary-components/jazz-table/jazz-filter'; import { Sort } from '../../secondary-components/jazz-table/jazz-table-sort'; import { Router, ActivatedRoute } from '@angular/router'; import { ToasterService } from 'angular2-toaster'; import { AdvancedFiltersComponent } from './../../secondary-components/advanced-filters/internal/advanced-filters.component'; import { RequestService, MessageService, DataCacheService, AuthenticationService } from '../../core/services/index'; import { AdvancedFilterService } from './../../advanced-filter.service'; import { AdvFilters } from './../../adv-filter.directive'; import { environment as env_oss} from './../../../environments/environment.oss'; import { environment as env_internal } from './../../../environments/environment.internal'; import { EnvAssetsSectionComponent } from '../environment-assets/env-assets-section.component'; import * as _ from 'lodash'; declare let Promise; @Component({ selector: 'env-logs-section', templateUrl: './env-logs-section.component.html', providers: [RequestService], styleUrls: ['./env-logs-section.component.scss'] }) export class EnvLogsSectionComponent implements OnInit { private http: any; @ViewChild('filtertags') FilterTags: FilterTagsComponent; @ViewChild(AdvFilters) advFilters: AdvFilters; @Input() radioContent; componentFactoryResolver:ComponentFactoryResolver; advanced_filter_input:any = { time_range:{ show:true, }, slider:{ show:true, }, period:{ show:false, }, statistics:{ show:false, }, path:{ show:false, }, environment:{ show:false, }, method:{ show:false, }, account:{ show:true, }, region:{ show:true, }, asset:{ show:true, }, sls_resource:{ show: false } } public assetWithDefaultValue:any=[] fromlogs:boolean = true; private subscription: any; limitValue: number = 20; offsetValue: number = 0; payload: any; filterloglevel: string = 'ERROR'; loadingState: string = 'default'; backupLogs = []; public assetList:any = []; errBody: any; parsedErrBody: any; errMessage: any; responseArray: any = []; private toastmessage: any; private env: any; refreshData: any; slider: any; sliderFrom = 1; sliderPercentFrom; sliderMax: number = 7; rangeList: Array<string> = ['Day', 'Week', 'Month', 'Year']; selectedTimeRange: string = this.rangeList[0]; selectedAssetName: any; assetsNameArray:any = []; allAssetsNameArray: any = []; @Input() service: any = {}; tableHeader = [ { label: 'Time', key: 'time', sort: true, filter: { type: 'dateRange' } }, { label: 'Message', key: 'message', sort: true, filter: { type: 'input' } }, { label: 'Request ID', key: 'requestId', sort: true, filter: { type: '' } }, { label: 'Log Level', key: 'logLevel', sort: true, filter: { type: 'dropdown', data: ['ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE'] } } ] logs = []; filtersList = ['ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE']; selected = ['ERROR']; filterSelected: Boolean = false; searchActive: Boolean = false; searchbar: string = ''; filter: any; sort: any; paginationSelected: Boolean = true; totalPagesTable: number = 7; prevActivePage: number = 1; expandText: string = 'Expand all'; errorTime: any; errorURL: any; errorAPI: any; errorRequest: any = {}; errorResponse: any = {}; errorUser: any; selectedEnv: any; errorChecked: boolean = true; errorInclude: any = ""; json: any = {}; model: any = { userFeedback: '' }; accList=env_internal.urls.accounts; regList=env_internal.urls.regions; accSelected:string = this.accList[0]; regSelected:string=this.regList[0]; public assetSelected:string; public resourceSelected: any; lambdaResourceNameArr; lambdaResource; instance_yes; assetNameFilterWhiteList = [ 'all', 'lambda', 'apigateway' ]; getFilter(filterServ){ this.service['islogs']=true; this.service['isServicelogs']=true; if(this.assetList){ this.service['assetList']=this.assetList; } this.service['allAssetsNameArray'] = this.allAssetsNameArray; this.advanced_filter_input.sls_resource.show = true; let filtertypeObj = filterServ.addDynamicComponent({"service" : this.service, "advanced_filter_input" : this.advanced_filter_input}); let componentFactory = this.componentFactoryResolver.resolveComponentFactory(filtertypeObj.component); var comp = this; let viewContainerRef = this.advFilters.viewContainerRef; viewContainerRef.clear(); let componentRef = viewContainerRef.createComponent(componentFactory); this.instance_yes=(<AdvancedFiltersComponent>componentRef.instance); (<AdvancedFiltersComponent>componentRef.instance).data = {"service" : this.service, "advanced_filter_input" : this.advanced_filter_input}; (<AdvancedFiltersComponent>componentRef.instance).onFilterSelect.subscribe(event => { comp.onFilterSelect(event); }); this.instance_yes.onAssetSelect.subscribe(event => { comp.onAssetSelect(event); if(event !== 'all'){ this.service['lambdaResourceNameArr'] = this.lambdaResourceNameArr; this.advanced_filter_input.sls_resource.show = true; (<AdvancedFiltersComponent>componentRef.instance).data = {"service" : this.service, "advanced_filter_input" : this.advanced_filter_input}; } }); } onAssetSelect(event){ this.FilterTags.notify('filter-Asset',event); this.assetSelected=event; if(event != 'all' && this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1){ this.setAssetName(this.responseArray,this.assetSelected); this.onResourceSelect('all'); } } onResourceSelect(event){ this.FilterTags.notifyLogs('filter-Asset-Name', event); this.resourceSelected = event; } onaccSelected(event){ this.accSelected=event; } onregSelected(event){ this.regSelected=event; } expandall() { for (var i = 0; i < this.logs.length; i++) { var rowData = this.logs[i]; rowData['expanded'] = true; } this.expandText = 'Collapse all'; } fetchAssetName(type, name) { let assetName; let tokens; switch(type) { case 'lambda': case 'sqs': case 'iam_role': tokens = name.split(':'); assetName = tokens[tokens.length - 1]; break; case 'dynamodb': case 'cloudfront': case 'kinesis': tokens = name.split('/'); assetName = tokens[tokens.length - 1]; break; case 's3': tokens = name.split(':::'); assetName = tokens[tokens.length - 1].split('/')[0]; break; case 'apigateway': case 'apigee_proxy': tokens = name.split(this.selectedEnv + '/'); assetName = tokens[tokens.length - 1]; break; } return assetName; } setAssetName(val, selected) { let assetObj = []; this.lambdaResourceNameArr = []; val.map((item) => { assetObj.push({ type:item.asset_type, name: item.provider_id, env: item.environment }); }) if (selected === 'all') { assetObj.map((item) => { if(item.env === this.selectedEnv) { this.selectedAssetName = this.fetchAssetName(item.type, item.name); if (this.selectedAssetName) { this.allAssetsNameArray.push(this.selectedAssetName); } }}) this.allAssetsNameArray.map((item,index)=>{ if(item === 'all'){ this.allAssetsNameArray.splice(index,1) } }) this.allAssetsNameArray.sort(); this.allAssetsNameArray.splice(0,0,'all'); } else { assetObj.map((item) => { if (item.type === selected && item.env === this.selectedEnv) { this.selectedAssetName = this.fetchAssetName(item.type, item.name); if (this.selectedAssetName) { this.lambdaResourceNameArr.push(this.selectedAssetName); } } }) this.lambdaResourceNameArr.map((item,index)=>{ if(item === 'all'){ this.lambdaResourceNameArr.splice(index,1) } }) this.lambdaResourceNameArr.sort(); this.lambdaResourceNameArr.splice(0,0,'all'); } } collapseall() { for (var i = 0; i < this.logs.length; i++) { var rowData = this.logs[i]; rowData['expanded'] = false; } this.expandText = 'Expand all'; } onRowClicked(row, index) { var rowData = this.logs[index]; if (rowData) { rowData['expanded'] = !rowData['expanded']; this.expandText = 'Collapse all'; for (var i = 0; i < this.logs.length; i++) { var rowData = this.logs[i]; if (rowData['expanded'] == false) { this.expandText = 'Expand all'; break; } } } } onFilter(column) { for (var i = 0; i < this.tableHeader.length; i++) { var col = this.tableHeader[i] if (col.filter != undefined && col.filter['_value'] != undefined) { if (col.filter['type'] == 'dateRange') { // code... } else { this.logs = this.filter.filterFunction(col.key, col.filter['_value'], this.logs); } } } }; onSort(sortData) { var col = sortData.key; var reverse = false; if (sortData.reverse == true) { reverse = true } this.logs = this.sort.sortByColumn(col, reverse, function (x: any) { return x; }, this.logs); }; trim_Message() { if (this.logs != undefined) for (var i = 0; i < this.logs.length; i++) { var reg = new RegExp(this.logs[i].timestamp, "g"); this.logs[i].message = this.logs[i].message.replace(reg, ''); this.logs[i].request_id = this.logs[i].request_id.substring(0, this.logs[i].request_id.length - 1); this.logs[i].message = this.logs[i].message.replace(this.logs[i].request_id, ''); } } paginatePage(currentlyActivePage) { this.expandText = 'Expand all'; if (this.prevActivePage != currentlyActivePage) { this.prevActivePage = currentlyActivePage; this.logs = []; this.offsetValue = (this.limitValue * (currentlyActivePage - 1)); this.payload.offset = this.offsetValue; this.callLogsFunc(); /* * Required:- we need the total number of records from the api, which will be equal to totalPagesTable. * We should be able to pass start number, size/number of records on each page to the api, where, * start = (size * currentlyActivePage) + 1 */ } } resetPayload() { this.payload.offset = 0; $(".pagination.justify-content-center li:nth-child(2)")[0].click(); this.callLogsFunc(); } onFilterSelected(filters) { this.loadingState = 'loading'; var filter; if (filters[0]) { filter = filters[0]; } this.filterloglevel = filter; this.payload.type = this.filterloglevel; this.resetPayload(); } getRange(e) { this.sliderFrom = e.from; this.sliderPercentFrom = e.from_percent; this.FilterTags.notifyLogs('filter-TimeRangeSlider',this.sliderFrom); var resetdate = this.getStartDate(this.selectedTimeRange, this.sliderFrom); this.payload.start_time = resetdate; this.resetPayload(); } getRangefunc(e){ this.FilterTags.notify('filter-TimeRangeSlider',e); this.sliderFrom=1; this.sliderPercentFrom=1; var resetdate = this.getStartDate(this.selectedTimeRange, this.sliderFrom); this.callLogsFunc(); } onRangeListSelected(range) { this.sliderFrom = 1; var resetdate = this.getStartDate(range, this.sliderFrom); // this.resetPeriodList(range); this.selectedTimeRange = range; this.payload.start_time = resetdate; this.resetPayload(); } sendDefaults(range){ switch(range){ case 'Day':{ this.FilterTags.notify('filter-Period','15 Minutes') break; } case 'Week':{ this.FilterTags.notify('filter-Period','1 Hour') break; } case 'Month':{ this.FilterTags.notify('filter-Period','6 Hours') break; } case 'Year':{ this.FilterTags.notify('filter-Period','7 Days') break; } } } getStartDate(filter, sliderFrom) { var todayDate = new Date(); switch (filter) { case "Day": this.sliderMax = 7; var resetdate = new Date(todayDate.setDate(todayDate.getDate() - sliderFrom)).toISOString(); break; case "Week": this.sliderMax = 5; var resetdate = new Date(todayDate.setDate(todayDate.getDate() - (sliderFrom * 7))).toISOString(); break; case "Month": this.sliderMax = 12; var currentMonth = new Date((todayDate).toISOString()).getMonth(); var currentDay = new Date((todayDate).toISOString()).getDate(); currentMonth++; var currentYear = new Date((todayDate).toISOString()).getFullYear(); var diffMonth = currentMonth - sliderFrom; if (diffMonth > 0) { var resetYear = currentYear; var resetMonth = diffMonth; } else if (diffMonth === 0) { var resetYear = currentYear - 1; var resetMonth = 12; } else if (diffMonth < 0) { var resetYear = currentYear - 1; // var resetMonth = sliderFrom - currentMonth; var resetMonth = 12 + diffMonth; } if (currentDay == 31) currentDay = 30; var newStartDateString = resetYear + "-" + resetMonth + "-" + currentDay + " 00:00:00" var newStartDate = new Date(newStartDateString); var resetdate = newStartDate.toISOString(); break; case "Year": this.sliderMax = 6; var currentYear = new Date((todayDate).toISOString()).getFullYear(); var newStartDateString = (currentYear - 6).toString() + "/" + "1" + "/" + "1"; var newStartDate = new Date(newStartDateString); var resetdate = newStartDate.toISOString(); break; } return resetdate; } onServiceSearch(searchbar) { this.logs = this.filter.searchFunction("any", searchbar); }; constructor(private route: ActivatedRoute, private request: RequestService, private router: Router, private cache: DataCacheService, private authenticationservice: AuthenticationService, @Inject(ComponentFactoryResolver) componentFactoryResolver,private advancedFilters: AdvancedFilterService , private toasterService: ToasterService, private messageservice: MessageService) { this.toasterService = toasterService; this.http = request; this.toastmessage = messageservice; this.componentFactoryResolver = componentFactoryResolver; var comp = this; setTimeout(function(){ comp.getFilter(advancedFilters); document.getElementById('hidethis').classList.add('hide') },10); } refresh() { this.callLogsFunc(); } getAssetType(data?){ let self=this; return this.http.get('/jazz/assets',{ domain: self.service.domain, service: self.service.name, status: "active" }, self.service.id).toPromise().then((response:any)=>{ if(response&&response.data&&response.data.assets){ this.assetsNameArray.push(response); let assets=_(response.data.assets).map('asset_type').uniq().value(); const filterWhitelist = [ 'lambda', 'apigateway' ]; assets = assets.filter(item => filterWhitelist.includes(item)); let validAssetList = assets.filter(asset => (env_oss.assetTypeList.indexOf(asset) > -1)); validAssetList.splice(0, 0, 'all'); this.responseArray = this.assetsNameArray[0].data.assets.filter(asset=>(validAssetList.indexOf(asset.asset_type)>-1)); self.assetWithDefaultValue = validAssetList; for (var i = 0; i < self.assetWithDefaultValue.length; i++) { self.assetList[i] = self.assetWithDefaultValue[i].replace(/_/g, " "); } self.assetSelected=validAssetList[0].replace(/_/g ," "); if (!data) { self.assetSelected = validAssetList[0].replace(/_/g, " "); } if (this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1) { self.setAssetName(self.responseArray, self.assetSelected); } self.getFilter(self.advancedFilters); self.instance_yes.showAsset = true; self.instance_yes.assetSelected = validAssetList[0].replace(/_/g ," "); } }) .catch((error) => { return Promise.reject(error); }) } callLogsFunc() { this.loadingState = 'loading'; if (this.subscription) { this.subscription.unsubscribe(); } this.subscription = this.http.post('/jazz/logs', this.payload, this.service.id).subscribe( response => { if(response.data.logs !== undefined) { this.logs = response.data.logs || response.data.data.logs; if(this.logs !== undefined) if (this.logs && this.logs.length != 0) { var pageCount = response.data.count; if (pageCount) { this.totalPagesTable = Math.ceil(pageCount / this.limitValue); if(this.totalPagesTable === 1){ this.paginationSelected = false; } else { this.totalPagesTable = 0; } this.backupLogs = this.logs; this.sort = new Sort(this.logs); this.loadingState = 'default'; this.trim_Message(); } else { this.loadingState = 'empty'; } } else { this.loadingState = 'empty'; } } }, err => { this.loadingState = 'error'; this.errBody = err._body; this.errMessage = this.toastmessage.errorMessage(err, "serviceLogs"); try { this.parsedErrBody = JSON.parse(this.errBody); if (this.parsedErrBody.message != undefined && this.parsedErrBody.message != '') { this.errMessage = this.errMessage || this.parsedErrBody.message; } this.getTime(); this.errorURL = window.location.href; this.errorAPI = env_oss.baseurl+"/jazz/logs"; this.errorRequest = this.payload; this.errorUser = this.authenticationservice.getUserId(); this.errorResponse = err._body; this.cache.set('feedback', this.model.userFeedback) this.cache.set('api', this.errorAPI) this.cache.set('request', this.errorRequest) this.cache.set('resoponse', this.errorResponse) this.cache.set('url', this.errorURL) this.cache.set('time', this.errorTime) this.cache.set('user', this.errorUser) this.cache.set('bugreport', this.json) } catch (e) { console.log(e); } }) }; cancelFilter(event){ switch(event){ case 'time-range':{ this.instance_yes.onRangeListSelected('Day'); break; } case 'time-range-slider':{ this.instance_yes.onTimePeriodSelected(1); break; } case 'period':{ this.instance_yes.onPeriodSelected('15 Minutes'); break; } case 'statistic':{ this.instance_yes.onStatisticSelected('Average'); break; } case 'account':{ this.instance_yes.onaccSelected('Acc 1'); break; } case 'region':{ this.instance_yes.onregSelected('reg 1'); break; } case 'env':{ this.instance_yes.onEnvSelect('prod'); break; } case 'method':{ this.instance_yes.onMethodListSelected('POST'); break; } case 'asset':{ this.instance_yes.getAssetType('all'); break; } case 'asset-iden':{ this.instance_yes.getResourceType('all'); break; } case 'all':{ this.instance_yes.onRangeListSelected('Day'); this.instance_yes.onPeriodSelected('15 Minutes'); this.instance_yes.onTimePeriodSelected(1); this.instance_yes.onStatisticSelected('Average'); this.instance_yes.onaccSelected('Acc 1'); this.instance_yes.onregSelected('reg 1'); this.instance_yes.onEnvSelect('prod'); this.instance_yes.onMethodListSelected('POST'); this.instance_yes.getAssetType('all'); this.instance_yes.getResourceType('all'); break; } } this.getRangefunc(1); } onFilterSelect(event){ switch(event.key){ case 'slider':{ this.getRange(event.value); break; } case 'range':{ this.sendDefaults(event.value); this.FilterTags.notifyLogs('filter-TimeRange',event.value); this.sliderFrom =1; this.FilterTags.notifyLogs('filter-TimeRangeSlider',this.sliderFrom); var resetdate = this.getStartDate(event.value, this.sliderFrom); // this.resetPeriodList(range); this.selectedTimeRange = event.value; this.payload.start_time = resetdate; this.resetPayload(); break; } case 'account':{ this.FilterTags.notify('filter-Account',event.value); this.accSelected=event.value; break; } case 'region':{ this.FilterTags.notify('filter-Region',event.value); this.regSelected=event.value; break; } case 'asset' :{ this.FilterTags.notify('filter-Asset',event.value) this.assetSelected=event.value; if (this.assetSelected !== 'all') { this.payload.asset_type = this.assetSelected.replace(/ /g, "_"); var value = (<HTMLInputElement>document.getElementById('Allidentifier')) if(value != null) { var inputValue = value.checked = true; } delete this.payload['asset_identifier'] } else { delete this.payload['asset_type']; } this.resetPayload(); break; } case "resource" : { this.FilterTags.notifyLogs('filter-Asset-Name', event.value); this.resourceSelected = event.value; this.payload.asset_identifier = this.resourceSelected; if(this.resourceSelected.toLowerCase() === 'all'){ delete this.payload['asset_identifier']; } this.resetPayload(); break; } } } getTime() { var now = new Date(); this.errorTime = ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':' + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now.getSeconds()) : (now.getSeconds()))); } ngOnChanges(x: any) { this.route.params.subscribe( params => { this.env = params.env; }); if (this.env == 'prd') this.env = 'prod'; if(x.service.currentValue.domain) { this.getAssetType() } } ngOnInit() { var todayDate = new Date(); this.payload = { "service": this.service.name,//"logs", // "domain": this.service.domain,//"jazz", // "environment": this.env, //"dev" "category": this.service.serviceType === "custom" ? "sls-app" : this.service.serviceType,//"api",// "size": this.limitValue, "offset": this.offsetValue, "type": this.filterloglevel || "ERROR", "end_time": (new Date().toISOString()).toString(), "start_time": new Date(todayDate.setDate(todayDate.getDate() - this.sliderFrom)).toISOString() } if( this.assetSelected !== 'all') { this.payload["asset_type"] = this.assetSelected; } this.selectedEnv = this.env; this.callLogsFunc(); this.filter = new Filter(this.logs); this.sort = new Sort(this.logs); } }
the_stack
import { responseType } from '../../content/modules/content-getChapters'; import { Code } from '../../content/types/Code'; import { Footnote } from '../../content/types/Footnote'; import { Img } from '../../content/types/Img'; import { reConfigCollectionType } from '../../options/options-utils'; import { Item } from '../types/BestMarksJson'; import { ChapInfoUpdated } from '../types/ChapInfoJson'; import { Updated } from '../types/Updated'; import { sendAlertMsg, sendMessageToContentScript, sortByKey, } from './bg-utils'; import { Config } from './bg-vars'; import { Wereader } from './bg-wereader-api'; export { getBookMarks, getTitleAddedPreAndSuf }; // 给标题添加前后缀 function getTitleAddedPreAndSuf(title: string, level: number) { let newTitle = ''; switch (level) { case 1: case 2: case 3: newTitle = Config[`lev${level}Pre`] + title + Config[`lev${level}Suf`]; break; case 4: //添加 4 5 6 级及 default 是为了处理特别的书(如导入的书籍) case 5: case 6: default: const {lev3Pre, lev3Suf} = Config; newTitle = `${lev3Pre}${title}${lev3Suf}`; break; } return newTitle; } // 获取标注数据 interface ChapAndMarks{ isCurrent: unknown; marks: Array<Updated | ThoughtsInAChap>; title: string; level: number; anchors?: { title: string; level: number; [key: string]: any }[]; bookId?: string; bookVersion?: number; chapterUid?: number; markText?: string; range?: string; style?: number; type?: number; createTime?: number; bookmarkId?: string; } async function getBookMarks(isAddThou?: boolean) { const wereader = new Wereader(window.bookId); const {updated: marks} = await wereader.getBookmarks(); if(!marks.length) return; /* 请求得到 chapters 方便导出不含标注的章节的标题, 另外,某些书包含标注但标注数据中没有章节记录(一般发生在导入书籍中),此时则必须使用请求获取章节信息 */ let chapters = await getChapters() || []; /* 生成标注数据 */ let chaptersAndMarks: ChapAndMarks[] = chapters.map((chap)=>{ let chapAndMarks: ChapAndMarks = chap as unknown as ChapAndMarks; //取得章内标注并初始化 range let marksInAChap = marks.filter((mark)=>mark.chapterUid == chapAndMarks.chapterUid); marksInAChap.map((curMark)=>{ curMark.range = curMark.range.replace(/"(\d*)-\d*"/, "$1"); return curMark; }); // 排序*大多数时候数据是有序的,但存在特殊情况所以必须排序* chapAndMarks.marks = sortByKey(marksInAChap, "range") as Updated[]; return chapAndMarks; }); // addThoughts 参数用于显式指明不包含想法 if(isAddThou !== false && Config.addThoughts) chaptersAndMarks = await addThoughts(chaptersAndMarks, chapters); return chaptersAndMarks; } // 给某一条标注添加图片等内容 function addMarkedData(mark: any, markedData: any, footnoteContent: string) { let abstract = mark.abstract; let markText = abstract ? abstract : mark.markText; for (const markedDataIdx of mark.markedDataIdxes) { // 遍历索引,逐个替换 const {imgSrc, alt, isInlineImg, footnote, footnoteName, code} = markedData[markedDataIdx]; let replacement = ''; /* 生成替换字符串 */ if(imgSrc) { // 图片 let insert1 = '', insert2 = ''; // 非行内图片单独占行(即使它与文字一起标注) if(!isInlineImg && markText.indexOf('[插图]') > 0) // 不为行内图片且'[插图]'前有内容 insert1 = '\n\n' if(!isInlineImg && markText.indexOf('[插图]') != (markText.length - 4)) // 不为行内图片且'[插图]'后有内容 insert2 = '\n\n' replacement = `${insert1}![${alt}](${imgSrc})${insert2}` }else if (footnote) { //注释 const footnoteId = footnoteName.replace(/[\s<>"]/, '-'); const footnoteNum = footnoteName.match(/(?<=注)(\d)*$/)[0]; replacement = `<sup><a id="${footnoteId}-ref" href="#${footnoteId}">${footnoteNum}</a></sup>`; footnoteContent += `<p id="${footnoteId}">${footnoteNum}. ${footnote}<a href="#${footnoteId}-ref">&#8617;</a></p>\n`; }else if (code) { //代码块 let insert1 = '', insert2 = '' if(markText.indexOf('[插图]') > 0) //'[插图]'前有内容 insert1 = '\n\n' if(markText.indexOf('[插图]') != (markText.length - 4)) //'[插图]'后有内容 insert2 = '\n\n' replacement = `${insert1}${Config.codePre}\n${code}${Config.codeSuf}${insert2}` } if (replacement) { // 替换 markText = markText.replace(/\[插图\]/, replacement); if (abstract) mark.abstract = markText; // 新字符串赋值回 mark else mark.markText = markText; } else console.log(mark, markedData, replacement); } // footnoteContent 不断更新,最后在 traverseMarks 中追加到文字末尾 return [mark, footnoteContent]; } // 在 marks 中添加替换数据索引(每一个“[插图]”用哪个位置的 markedData 替换) export function addRangeIndexST(marks: any) { let used: {[key: string]: any} = {}; // “[插图]”的 range 作为键,该“[插图]”所对应的数据在 markedData 中的索引作为值 // 获得 str 中子字符串 subStr 出现的所有位置(返回 index 数组) function getIndexes(str: string, subStr: string){ let indexes = []; var idx = str.indexOf(subStr); while(idx > -1){ indexes.push(idx); idx = str.indexOf(subStr, idx+1); } return indexes; } const name = '[插图]'; let markedDataIdx = 0; // markedData 索引 for (let i = 0; i < marks.length; i++) { // 遍历标注 let {abstract, range} = marks[i]; let markText = abstract ? abstract : marks[i].markText; let indexes = getIndexes(markText, name); let markedDataIdxes = []; for (const idx of indexes) { // indexes:所有“[插图]”在 markText 中出现的位置 // idx:某一个“[插图]”在 markText 中的位置 let imgRange = range + idx; // 每一个“[插图]”在本章标注中的唯一位置 if (used[imgRange] == undefined) { // 该“[插图]”没有记录过 used[imgRange] = markedDataIdx; // 记录某个位置的“[插图]”所对应的替换数据 markedDataIdxes.push(markedDataIdx++); } else { // “[插图]”被记录过(同一个“[插图]”多次出现) markedDataIdxes.push(used[imgRange]); } } marks[i].markedDataIdxes = markedDataIdxes; } return marks; } // 处理章内标注 export function traverseMarks(marks: (Updated | ThoughtsInAChap)[], markedData: Array<Img|Footnote|Code> = []) { function isThought(mark: object): mark is ThoughtsInAChap { return ('abstract' in mark && 'content' in mark); } function isUpdated(mark: object): mark is Updated { return 'markText' in mark; } let res = "", footnoteContent = ""; for (let j = 0; j < marks.length; j++) { // 遍历章内标注 let mark = marks[j]; if (markedData.length) [marks[j], footnoteContent] = addMarkedData(marks[j], markedData, footnoteContent); if(isThought(mark)){ // 如果为想法 // 想法所标注的内容加入 res res += `${Config.thouMarkPre}${mark.abstract}${Config.thouMarkSuf}\n\n`; // 想法加入 res res += `${Config.thouPre}${mark.content}${Config.thouSuf}\n\n`; } else if(isUpdated(mark)){ // 不是想法(为标注) // 则进行正则匹配 let markText = regexpReplace(mark.markText); res += `${addMarkPreAndSuf(markText, mark.style)}\n\n`; } } if (markedData.length && footnoteContent) res += footnoteContent; return res; } export async function getChapters(){ const wereader = new Wereader(window.bookId); const chapInfos = await wereader.getChapInfos(); const response = await sendMessageToContentScript({message: {isGetChapters: true}}) as responseType; if(!response || !chapInfos) { alert("获取目录出错。"); return; } const chaps = chapInfos.data[0].updated; let checkedChaps = chaps.map((chap)=>{ let chapsFromDom = response.chapters; //某些书没有标题,或者读书页标题与数据库标题不同(往往读书页标题多出章节信息) if(!chapsFromDom.filter((chap: any)=>chap.title===chap.title).length){ // 将 chapsFromDom 中的信息赋值给 chapsFromServer if(chapsFromDom[chap.chapterIdx-1]) chap.title = chapsFromDom[chap.chapterIdx-1].title; } //某些书没有目录级别 if(!chap.level){ let targetChapFromDom = chapsFromDom.filter((chapter: any)=>chapter.title===chap.title); if(targetChapFromDom.length) chap.level = targetChapFromDom[0].level; else chap.level = 1; } chap.isCurrent = chap.title === response.currentContent || response.currentContent.indexOf(chap.title)>-1 return chap; }); return checkedChaps; } // 获取热门标注数据 export async function getBestBookMarks() { const wereader = new Wereader(window.bookId); let {items: bestMarksData} = await wereader.getBestBookmarks(); //处理书本无热门标注的情况 if(!bestMarksData || !bestMarksData.length){ sendAlertMsg({text: "该书无热门标注",icon:'warning'}); return; } //查找每章节热门标注 let chapters = await getChapters() || []; let bestMarks = chapters.map((chap)=>{ interface ChapInfoUpdatedExtra extends ChapInfoUpdated{ bestMarks?: any } let tempChap: ChapInfoUpdatedExtra = chap; //取得章内热门标注并初始化 range let bestMarksInAChap = bestMarksData.filter((bestMark)=>bestMark.chapterUid == tempChap.chapterUid) .reduce((tempBestMarksInAChap: Item[], curBestMark)=>{ curBestMark.range = parseInt(curBestMark.range.toString().replace(/"(\d*)-\d*"/, "$1")); tempBestMarksInAChap.push(curBestMark); return tempBestMarksInAChap; },[]); //排序章内标注并加入到章节内 tempChap.bestMarks = sortByKey(bestMarksInAChap, "range");; return tempChap; }); return bestMarks; } // 获取想法 interface ThoughtsInAChap{ range: string; abstract: string; content: string } export async function getMyThought() { const wereader = new Wereader(window.bookId); let data = await wereader.getThoughts(); //获取 chapterUid 并去重、排序 let chapterUidArr = Array.from(new Set(JSON.stringify(data).match(/(?<="chapterUid":\s*)(\d*)(?=,)/g))).map((uid)=>{ return parseInt(uid); }); chapterUidArr.sort() //查找每章节标注并总结好 let thoughtsMap: Map<number, ThoughtsInAChap[]> = new Map<number, ThoughtsInAChap[]>(); //遍历章节 chapterUidArr.forEach(chapterUid=>{ let thoughtsInAChap: ThoughtsInAChap[] = []; //遍历所有想法,将章内想法放入一个数组 for (const item of data.reviews) { //处理有书评的情况 if (item.review.chapterUid == undefined || item.review.chapterUid != chapterUid) continue //找到指定章节的想法 let abstract = item.review.abstract //替换想法前后空字符 let content = item.review.content.replace(/(^\s*|\s*$)/g,'') let range = item.review.range.replace(/"(\d*)-\d*"/, "$1") //如果没有发生替换(为章末想法时发生) if(item.review.range.indexOf('-') < 0){ abstract = "章末想法"; range = item.review.createTime.toString(); } thoughtsInAChap.push({ abstract: abstract, content: content, range: range }) } thoughtsMap.set(chapterUid, sortByKey(thoughtsInAChap, "range") as ThoughtsInAChap[]) }); return thoughtsMap; } // 在标注中添加想法 async function addThoughts(chaptersAndMarks: ChapAndMarks[], chapters: ChapInfoUpdated[]){ let chapsMap = chapters.reduce((tempChapsMap, aChap)=>{ // 整理格式 tempChapsMap.set(aChap.chapterUid, aChap); return tempChapsMap; }, new Map<number, ChapInfoUpdated>()); let thoughtsMap = await getMyThought(); // 遍历各章节想法 thoughtsMap.forEach((thoughtsInAChap, chapterUid) => { // 遍历章节依次将各章节章内想法添加进 marks let addedToMarks = false for(let i=0; i<chaptersAndMarks.length; i++){ if(chaptersAndMarks[i].chapterUid != chapterUid) continue; // 找到想法所在章节 // 想法与标注合并后按 range 排序 let marks = chaptersAndMarks[i].marks.concat(thoughtsInAChap); chaptersAndMarks[i].marks = sortByKey(marks, "range") as Updated[]; addedToMarks = true; break; } // 如果想法未被成功添加进标注(想法所在章节不存在标注的情况下发生) if(!addedToMarks) { let m = chapsMap.get(chapterUid); chaptersAndMarks.push({ isCurrent: m !== undefined && m.isCurrent, level: m === undefined ? 0 : m.level , chapterUid: chapterUid, title: m === undefined ? "" : m.title, marks: thoughtsInAChap }); } }); // 章节排序 let sorted = sortByKey(chaptersAndMarks, "chapterUid") as ChapAndMarks[]; return sorted; } // 给 markText 进行正则替换 function regexpReplace(markText: string){ let regexpConfig = Config.re for(let reId in regexpConfig){ let replaceMsg = regexpConfig[reId as keyof reConfigCollectionType].replacePattern.match(/^s\/(.+?)\/(.*?)\/(\w*)$/) if(!regexpConfig[reId as keyof reConfigCollectionType].checked || replaceMsg == null || replaceMsg.length < 4){//检查是否选中以及是否满足格式 continue } let pattern = replaceMsg[1] let replacement = replaceMsg[2] let flag = replaceMsg[3] let regexpObj = new RegExp(pattern, flag) if(regexpObj.test(markText)){ markText = markText.replace(regexpObj, replacement) //匹配一次后结束匹配 break } } return markText } // 根据标注类型获取前后缀 function addMarkPreAndSuf(markText: string, style: number){ const pre = (style == 0) ? Config["s1Pre"] : (style == 1) ? Config["s2Pre"] : (style == 2) ? Config["s3Pre"] : "" const suf = (style == 0) ? Config["s1Suf"] : (style == 1) ? Config["s2Suf"] : (style == 2) ? Config["s3Suf"] : "" return pre + markText + suf }
the_stack
import { Gantt } from '../base/gantt'; import { getValue, Internationalization, isNullOrUndefined } from '@syncfusion/ej2-base'; import { Tooltip, TooltipEventArgs } from '@syncfusion/ej2-popups'; import { BeforeTooltipRenderEventArgs, ITaskData } from '../base/interface'; import { TaskbarEdit } from '../actions/taskbar-edit'; import * as cls from '../base/css-constants'; /** * File for handling taskbar editing tooltip in Gantt. */ export class EditTooltip { public parent: Gantt; public toolTipObj: Tooltip; public taskbarTooltipContainer: HTMLElement; public taskbarTooltipDiv: HTMLElement; private taskbarEdit: TaskbarEdit; constructor(gantt: Gantt, taskbarEdit: TaskbarEdit) { this.parent = gantt; this.taskbarEdit = taskbarEdit; } /** * To create tooltip. * * @param {string} opensOn . * @param {boolean} mouseTrail . * @param {string} target . * @returns {void} * @private */ public createTooltip(opensOn: string, mouseTrail: boolean, target?: string): void { this.toolTipObj = new Tooltip( { opensOn: opensOn, position: 'TopRight', mouseTrail: mouseTrail, cssClass: cls.ganttTooltip, target: target ? target : null, animation: { open: { effect: 'None' }, close: { effect: 'None' } } } ); this.toolTipObj.beforeRender = (args: TooltipEventArgs) => { const argsData: BeforeTooltipRenderEventArgs = { data: this.taskbarEdit.taskBarEditRecord, args: args, content: this.toolTipObj.content }; this.parent.trigger('beforeTooltipRender', argsData); }; this.toolTipObj.afterOpen = (args: TooltipEventArgs) => { this.updateTooltipPosition(args); }; this.toolTipObj.isStringTemplate = true; this.toolTipObj.appendTo(this.parent.chartPane); } /** * Method to update tooltip position * * @param {TooltipEventArgs} args . * @returns {void} . */ private updateTooltipPosition(args: TooltipEventArgs): void { const containerPosition: { top: number, left: number } = this.parent.getOffsetRect(this.parent.chartPane); const leftEnd: number = containerPosition.left + this.parent.chartPane.offsetWidth; let tooltipPositionX: number = args.element.offsetLeft; if (leftEnd < (tooltipPositionX + args.element.offsetWidth)) { tooltipPositionX += leftEnd - (tooltipPositionX + args.element.offsetWidth); } args.element.style.left = tooltipPositionX + 'px'; args.element.style.visibility = 'visible'; } /** * To show/hide taskbar edit tooltip. * * @param {boolean} bool . * @param {number} segmentIndex . * @returns {void} * @private */ public showHideTaskbarEditTooltip(bool: boolean, segmentIndex: number): void { if (bool && this.parent.tooltipSettings.showTooltip) { this.createTooltip('Custom', false); this.parent.tooltipModule.toolTipObj.close(); this.updateTooltip(segmentIndex); if (this.taskbarEdit.connectorSecondAction === 'ConnectorPointLeftDrag') { this.toolTipObj.open( this.taskbarEdit.connectorSecondElement.querySelector('.' + cls.connectorPointLeft)); } else if (this.taskbarEdit.connectorSecondAction === 'ConnectorPointRightDrag') { this.toolTipObj.open( this.taskbarEdit.connectorSecondElement.querySelector('.' + cls.connectorPointRight)); } else { this.toolTipObj.open(this.taskbarEdit.taskBarEditElement); } } else if (!isNullOrUndefined(this.toolTipObj)) { this.toolTipObj.destroy(); this.toolTipObj = null; } } /** * To update tooltip content and position. * * @param {number} segmentIndex . * @returns {void} . * @private */ public updateTooltip(segmentIndex: number): void { const ganttProp: ITaskData = this.taskbarEdit.taskBarEditRecord.ganttProperties; const taskWidth: number = segmentIndex === -1 ? ganttProp.width : ganttProp.segments[segmentIndex].width; const progressWidth: number = segmentIndex === -1 ? ganttProp.progressWidth : ganttProp.segments[segmentIndex].progressWidth; const left: number = segmentIndex === -1 ? ganttProp.left : ganttProp.left + ganttProp.segments[segmentIndex].left; if (!isNullOrUndefined(this.toolTipObj)) { if (this.taskbarEdit.taskBarEditAction === 'ConnectorPointLeftDrag' || this.taskbarEdit.taskBarEditAction === 'ConnectorPointRightDrag') { this.toolTipObj.content = this.getTooltipText(segmentIndex); this.toolTipObj.offsetY = -3; } else { this.toolTipObj.content = this.getTooltipText(segmentIndex); this.toolTipObj.refresh(this.taskbarEdit.taskBarEditElement); if (this.taskbarEdit.taskBarEditAction === 'LeftResizing') { this.toolTipObj.offsetX = -taskWidth; } else if (this.taskbarEdit.taskBarEditAction === 'RightResizing' || this.taskbarEdit.taskBarEditAction === 'ParentResizing') { this.toolTipObj.offsetX = 0; } else if (this.taskbarEdit.taskBarEditAction === 'ProgressResizing') { this.toolTipObj.offsetX = -(taskWidth - progressWidth); } else if (this.taskbarEdit.taskBarEditAction === 'MilestoneDrag') { this.toolTipObj.offsetX = -(this.parent.chartRowsModule.milestoneHeight / 2); } else if (taskWidth > 5) { this.toolTipObj.offsetX = -(taskWidth + left - this.taskbarEdit.tooltipPositionX); } } } } /** * To get updated tooltip text. * * @param {number} segmentIndex . * @returns {void} . * @private */ private getTooltipText(segmentIndex: number): string | HTMLElement { let tooltipString: string | HTMLElement = ''; const instance: Internationalization = this.parent.globalize; let editRecord: ITaskData = this.taskbarEdit.taskBarEditRecord.ganttProperties as ITaskData; if (!isNullOrUndefined(editRecord.segments) && editRecord.segments.length > 0 && segmentIndex !== -1 && this.taskbarEdit.taskBarEditAction !== 'ProgressResizing') { editRecord = editRecord.segments[segmentIndex]; } if (this.parent.tooltipSettings.editing) { const templateNode: NodeList = this.parent.tooltipModule.templateCompiler( this.parent.tooltipSettings.editing, this.parent, this.taskbarEdit.taskBarEditRecord, 'TooltipEditingTemplate'); if (getValue('tooltipEle', this.toolTipObj)) { this.parent.renderTemplates(); } tooltipString = (templateNode[0] as HTMLElement); } else { let startDate: string; let endDate: string; let duration: string; if (!isNullOrUndefined(editRecord.startDate)) { startDate = '<tr><td class = "e-gantt-tooltip-label">' + this.parent.localeObj.getConstant('startDate') + '</td><td>:</td><td class = "e-gantt-tooltip-value">' + instance.formatDate(editRecord.startDate, { format: this.parent.getDateFormat() }) + '</td></tr>'; } if (!isNullOrUndefined(editRecord.endDate)) { endDate = '<tr><td class = "e-gantt-tooltip-label">' + this.parent.localeObj.getConstant('endDate') + '</td><td>:</td><td class = "e-gantt-tooltip-value">' + instance.formatDate(editRecord.endDate, { format: this.parent.getDateFormat() }) + '</td></tr>'; } if (!isNullOrUndefined(editRecord.duration)) { duration = '<tr><td class = "e-gantt-tooltip-label">' + this.parent.localeObj.getConstant('duration') + '</td><td>:</td><td class = "e-gantt-tooltip-value">' + this.parent.getDurationString(editRecord.duration, (editRecord as ITaskData).durationUnit) + '</td></tr>'; } switch (this.taskbarEdit.taskBarEditAction) { case 'ProgressResizing': const progress: string = '<tr><td class = "e-gantt-tooltip-label">' + this.parent.localeObj.getConstant('progress') + '</td><td>:</td><td class = "e-gantt-tooltip-value">' + (editRecord as ITaskData).progress + '</td></tr>'; tooltipString = '<table class = "e-gantt-tooltiptable"><tbody>' + progress + '</tbody></table>'; break; case 'LeftResizing': tooltipString = '<table class = "e-gantt-tooltiptable"><tbody>' + startDate + duration + '</tbody></table>'; break; case 'RightResizing': case 'ParentResizing': tooltipString = '<table class = "e-gantt-tooltiptable"><tbody>' + endDate + duration + '</tbody></table>'; break; case 'ChildDrag': case 'ParentDrag': case 'MilestoneDrag': case 'ManualParentDrag': let sDate: string = ''; let eDate: string = ''; if (!isNullOrUndefined(this.taskbarEdit.taskBarEditRecord.ganttProperties.startDate)) { sDate = startDate; } if (!isNullOrUndefined(this.taskbarEdit.taskBarEditRecord.ganttProperties.endDate)) { eDate = endDate; } tooltipString = '<table class = "e-gantt-tooltiptable"><tbody>' + sDate + eDate + '</tbody></table>'; break; case 'ConnectorPointLeftDrag': case 'ConnectorPointRightDrag': tooltipString = this.parent.connectorLineModule.tooltipTable; if (isNullOrUndefined(this.toolTipObj)) { this.parent.connectorLineModule.tooltipTable.innerHTML = this.parent.connectorLineModule.getConnectorLineTooltipInnerTd( this.parent.editModule.taskbarEditModule.taskBarEditRecord.ganttProperties.taskName, this.parent.editModule.taskbarEditModule.fromPredecessorText, '', '' ); } break; } } return tooltipString; } }
the_stack
import {Observable} from "data/observable"; import {ObservableArray} from "data/observable-array"; import TypeUtils = require("utils/types"); class Batch implements IBatch { private _firstOperation: BatchOperation; private _invokeFinishedCheckForAll: boolean = false; private _invokeStrategy: InvokeStrategy = InvokeStrategy.Automatic; private _items: ObservableArray<any>; private _name: string; private _object: Observable; private _operations: BatchOperation[]; private _result: any; private _value: any; constructor(firstAction : (ctx : IBatchOperationContext) => void) { this._items = new ObservableArray<any>(); this._object = new Observable(); this._operations = []; this._firstOperation = new BatchOperation(this, firstAction); } public addItems(...items: any[]) : Batch { for (var i = 0; i < items.length; i++) { this._items .push(items[i]); } return this } public addLogger(action : (ctx : IBatchLogContext) => void) : Batch { this.loggers .push(action); return this; } public after(afterAction : (ctx : IBatchOperationContext) => void) : Batch { this.afterAction = afterAction; return this; } public afterAction : (ctx : IBatchOperationContext) => void; public before(beforeAction : (ctx : IBatchOperationContext) => void) : Batch { this.beforeAction = beforeAction; return this; } public beforeAction : (ctx : IBatchOperationContext) => void; public get firstOperation() : BatchOperation { return this._firstOperation; } public id : string; public invokeFinishedCheckForAll(flag?: boolean) : Batch { this._invokeFinishedCheckForAll = arguments.length < 1 ? true : flag; return this; } public get invokeStrategy(): InvokeStrategy { return this._invokeStrategy; } public set invokeStrategy(newStradegy: InvokeStrategy) { this._invokeStrategy = newStradegy; } public loggers = []; public get items() : ObservableArray<any> { return this._items; } public name : string; public get object() : Observable { return this._object; } public get operations(): BatchOperation[] { return this._operations; } public setInvokeStrategy(newStradegy: InvokeStrategy) : Batch { this._invokeStrategy = newStradegy; return this; } public setObjectProperties(properties) : Batch { if (!TypeUtils.isNullOrUndefined(properties)) { for (var p in properties) { this._object.set(p, properties[p]); } } return this; } public setResult(value : any) : Batch { this._result = value; return this; } public setResultAndValue(value : any) : Batch { return this.setResult(value) .setValue(value); } public setValue(value : any) : Batch { this._value = value; return this; } public start() : any { var finishedFlags: boolean[] = []; for (var i = 0; i < this._operations.length; i++) { finishedFlags.push(false); } var me = this; var result = this._result; var previousValue; var nextInvokeStradegy: InvokeStrategy; var skipWhile : (ctx : IBatchOperationContext) => boolean; var value : any = this._value; var createCheckIfFinishedAction = function(index) { return function() { finishedFlags[index] = true; for (var i = 0; i < finishedFlags.length; i++) { if (!finishedFlags[i]) { return; } } if (!TypeUtils.isNullOrUndefined(me.whenAllFinishedAction)) { var finishedOperation = new BatchOperation(me, me.whenAllFinishedAction, false); var ctx = new BatchOperationContext(previousValue); ctx.result = result; ctx.value = value; ctx.setExecutionContext(BatchOperationExecutionContext.finished); finishedOperation.action(ctx); } }; }; var invokeNextOperation: (previousIndex: number) => void; invokeNextOperation = (previousIndex: number) => { var i = previousIndex + 1; if (i >= me.operations.length) { return; // no more operations } var ctx = new BatchOperationContext(previousValue, me.operations, i); ctx.result = result; ctx.value = value; ctx.nextInvokeStradegy = null; // invoke stradegy var operationInvokeStradegy = nextInvokeStradegy; if (TypeUtils.isNullOrUndefined(operationInvokeStradegy)) { // use operation's default operationInvokeStradegy = ctx.operation.invokeStrategy; } if (TypeUtils.isNullOrUndefined(operationInvokeStradegy)) { // use batch default operationInvokeStradegy = me.invokeStrategy; } if (TypeUtils.isNullOrUndefined(operationInvokeStradegy)) { // use default operationInvokeStradegy = InvokeStrategy.Automatic; } var updateNextValues = () => { previousValue = ctx.nextValue; value = ctx.value; result = ctx.result; nextInvokeStradegy = ctx.nextInvokeStradegy; skipWhile = ctx.skipWhilePredicate; }; var updateAndInvokeNextOperation = () => { updateNextValues(); invokeNextOperation(i); }; ctx.invokeNext = (): BatchOperationContext => { operationInvokeStradegy = InvokeStrategy.Manually; updateAndInvokeNextOperation(); return ctx; }; ctx.checkIfFinishedAction = createCheckIfFinishedAction(i); if (!TypeUtils.isNullOrUndefined(skipWhile)) { if (skipWhile(ctx)) { ctx.checkIfFinishedAction(); invokeNextOperation(i); return; } } skipWhile = undefined; var checkIfCancelled = function() { if (ctx.cancelled) { ctx.setExecutionContext(BatchOperationExecutionContext.cancelled); if (!TypeUtils.isNullOrUndefined(me.whenCancelledAction)) { me.whenCancelledAction(ctx); } return true; } return false; }; var invokeCompletedAction = function() : boolean { ctx.setExecutionContext(BatchOperationExecutionContext.complete); if (ctx.invokeComplete && ctx.operation.completeAction) { ctx.operation.completeAction(ctx); } if (me._invokeFinishedCheckForAll) { ctx.checkIfFinished(); } return !checkIfCancelled(); }; var handleErrorAction = true; try { // global "before" action if (ctx.invokeBefore && ctx.operation.beforeAction) { ctx.setExecutionContext(BatchOperationExecutionContext.before); ctx.operation.beforeAction(ctx); if (checkIfCancelled()) { return; // cancelled } } // action to invoke if (ctx.invokeAction && ctx.operation.action) { ctx.setExecutionContext(BatchOperationExecutionContext.execution); ctx.operation.action(ctx); if (checkIfCancelled()) { return; // cancelled } } // global "after" action if (ctx.invokeAfter && ctx.operation.batch.afterAction) { ctx.setExecutionContext(BatchOperationExecutionContext.after); ctx.operation.batch.afterAction(ctx); if (checkIfCancelled()) { return; // cancelled } } // success action if (ctx.invokeSuccess && ctx.operation.successAction) { handleErrorAction = false; ctx.setExecutionContext(BatchOperationExecutionContext.success); ctx.operation.successAction(ctx); if (checkIfCancelled()) { return; // cancelled } } if (!invokeCompletedAction()) { return; // cancelled } } catch (e) { ctx.setError(e); ctx.setExecutionContext(BatchOperationExecutionContext.error); if (handleErrorAction && ctx.operation.errorAction) { if (ctx.invokeError) { ctx.operation.errorAction(ctx); } } else { if (!ctx.operation.ignoreOperationErrors) { throw e; } } if (checkIfCancelled()) { return; // cancelled } if (!invokeCompletedAction()) { return; // cancelled } } if (operationInvokeStradegy != InvokeStrategy.Automatic) { return; } updateAndInvokeNextOperation(); }; invokeNextOperation(-1); return result; } public whenAllFinished(action : (ctx : IBatchOperationContext) => void) : Batch { this.whenAllFinishedAction = action; return this; } public whenAllFinishedAction : (ctx : IBatchOperationContext) => void; public whenCancelled(action : (ctx : IBatchOperationContext) => void) : Batch { this.whenCancelledAction = action; return this; } public whenCancelledAction : (ctx : IBatchOperationContext) => void; } class BatchLogContext implements IBatchLogContext { private _context : BatchOperationContext; private _message : any; private _time : Date; constructor(ctx : BatchOperationContext, time : Date, msg: any) { this._context = ctx; this._message = msg; } public get batch() : Batch { return this.operation.batch; } public get context() : BatchOperationContext { return this._context; } public get message() : any { return this._message; } public get operation() : BatchOperation { return this.context.operation; } public get time() : Date { return this._time; } } class BatchOperation implements IBatchOperation { private _batch: Batch; private _id: string; private _invokeStrategy: InvokeStrategy; private _skipBefore: boolean = false; constructor(batch : Batch, action : (ctx : IBatchOperationContext) => void, appendOperation: boolean = true) { this._batch = batch; this.action = action; if (appendOperation) { batch.operations.push(this); } } public action : (ctx : IBatchOperationContext) => void; public addItems(...items: any[]) : BatchOperation { for (var i = 0; i < items.length; i++) { this._batch.items .push(items[i]); } return this; } public addLogger(action : (ctx : IBatchLogContext) => void) : BatchOperation { this._batch.addLogger(action); return this; } public after(afterAction : (ctx : IBatchOperationContext) => void) : BatchOperation { this._batch.afterAction = afterAction; return this; } public get batch() : Batch { return this._batch; } public get batchId() : string { return this._batch.id; } public set batchId(value : string) { this._batch.id = value; } public get batchName() : string { return this._batch.name; } public set batchName(value : string) { this._batch.name = value; } public before(beforeAction : (ctx : IBatchOperationContext) => void) : BatchOperation { this._batch.beforeAction = beforeAction; return this; } public get beforeAction() { return this._batch.beforeAction; } public complete(completedAction : (ctx : IBatchOperationContext) => void) : BatchOperation { this.completeAction = completedAction; return this; } public completeAction : (ctx : IBatchOperationContext) => void; public error(errAction : (ctx : IBatchOperationContext) => void) : BatchOperation { this.errorAction = errAction; return this; } public errorAction : (ctx : IBatchOperationContext) => void; public get id(): string { return this._id; } public set id(value: string) { // check for duplicate for (var i = 0; i < this._batch.operations.length; i++) { var bo = this._batch.operations[i]; if (bo === this) { continue; } if (bo.id == value) { throw "ID '" + value + "' has already be defined in operation #" + i + "!"; } } this._id = value; } public ignoreErrors(flag? : boolean) : BatchOperation { this.ignoreOperationErrors = arguments.length < 1 ? true : flag; return this; } public ignoreOperationErrors : boolean = false; public invokeFinishedCheckForAll(flag?: boolean) : BatchOperation { if (arguments.length < 1) { this._batch.invokeFinishedCheckForAll(); } else { this._batch.invokeFinishedCheckForAll(flag); } return this; } public get invokeStrategy(): InvokeStrategy { return this._invokeStrategy; } public set invokeStrategy(newStradegy: InvokeStrategy) { this._invokeStrategy = newStradegy; } public get items() : ObservableArray<any> { return this._batch.items; } public name : string; public next(action: (ctx : IBatchOperationContext) => void) : BatchOperation { return new BatchOperation(this._batch, action); } public get object() : Observable { return this._batch.object; } public setBatchId(value : string) : BatchOperation { this._batch.id = value; return this; } public setBatchName(value : string) : BatchOperation { this._batch.name = value; return this; } public setId(value : string) : BatchOperation { this.id = value; return this; } public setInvokeStrategy(newStradegy: InvokeStrategy) : BatchOperation { this._invokeStrategy = newStradegy; return this; } public setName(value : string) : BatchOperation { this.name = value; return this; } public setObjectProperties(properties) : BatchOperation { this._batch.setObjectProperties(properties); return this; } public setResult(value : any) : BatchOperation { this._batch.setResult(value); return this; } public setResultAndValue(value : any) : BatchOperation { this._batch.setResultAndValue(value); return this; } public setValue(value : any) : BatchOperation { this._batch.setValue(value); return this; } public skipBefore(value? : boolean) : BatchOperation { this._skipBefore = arguments.length < 1 ? true : value; return this; } public start() { this._batch.start(); } public success(successAction : (ctx : IBatchOperationContext) => void) : BatchOperation { this.successAction = successAction; return this; } public successAction : (ctx : IBatchOperationContext) => void; public then(action : (ctx : IBatchOperationContext) => void) : BatchOperation { return this.next(action); } public whenAllFinished(action : (ctx : IBatchOperationContext) => void) : BatchOperation { this._batch.whenAllFinishedAction = action; return this; } public whenCancelled(action : (ctx : IBatchOperationContext) => void) : BatchOperation { this._batch.whenCancelledAction = action; return this; } } class BatchOperationContext implements IBatchOperationContext { private _error : any; private _index : number; private _isLast : boolean; private _operation : BatchOperation; private _prevValue; private _executionContext : BatchOperationExecutionContext; private _nextInvokeStradegy: InvokeStrategy; constructor(previousValue : any, operations? : BatchOperation[], index? : number) { this._index = index; if (arguments.length > 2) { this._operation = operations[index]; this._isLast = index >= (operations.length - 1); } this._prevValue = previousValue; this.checkIfFinishedAction = () => { }; } public get batch() : Batch { return this.operation.batch; } public get batchId() : string { return this.operation.batch.id; } public get batchName() : string { return this.operation.batch.name; } public cancel(flag?: boolean) : BatchOperationContext { this.cancelled = arguments.length < 1 ? true : flag; return this; } public cancelled : boolean = false; public checkIfFinished() : BatchOperationContext { this.checkIfFinishedAction(); return this; } public checkIfFinishedAction : () => void; public get context() : string { var execCtx = this.executionContext; if (TypeUtils.isNullOrUndefined(execCtx)) { return undefined; } return BatchOperationExecutionContext[execCtx]; } public get executionContext() : BatchOperationExecutionContext { return this._executionContext; } public get error() : any { return this._error; } public get id() : string { return this.operation.id; } public get index() : number { return this._index; } public invokeAction : boolean = true; public invokeAfter : boolean = true; public invokeBefore : boolean = true; public invokeComplete : boolean = true; public invokeError : boolean = true; public invokeNext: () => BatchOperationContext; public invokeSuccess : boolean = true; public get isBetween() : boolean { if (this._index !== undefined) { return 0 !== this._index && !this._isLast; } return undefined; } public get isFirst() : boolean { if (this._index !== undefined) { return 0 === this._index; } return undefined; } public get isLast() : boolean { return this._isLast; } public get items(): ObservableArray<any> { return this._operation.items; } public log(msg) : BatchOperationContext { var ctx = new BatchLogContext(this, new Date(), msg); for (var i = 0; i < this.batch.loggers.length; i++) { try { var l = this.batch.loggers[i]; l(ctx); } catch (e) { // ignore } } return this; } public get name() : string { return this.operation.name; } public get nextInvokeStradegy() : InvokeStrategy { return this._nextInvokeStradegy; } public set nextInvokeStradegy(newValue: InvokeStrategy) { this._nextInvokeStradegy = newValue; } public nextValue : any; public get object(): Observable { return this._operation.object; } public get operation() : BatchOperation { return this._operation; } public get prevValue() : any { return this._prevValue; } public result : any; public setExecutionContext(value : BatchOperationExecutionContext) : BatchOperationContext { this._executionContext = value; return this; } public setError(error : any) : BatchOperationContext { this._error = error; return this; } public setNextInvokeStradegy(newValue: InvokeStrategy) : BatchOperationContext { this._nextInvokeStradegy = newValue; return this; } public setResultAndValue(value : any) : BatchOperationContext { this.result = value; this.value = value; return this; } public skip(cnt? : number) : BatchOperationContext { if (arguments.length < 1) { cnt = 1; } return this.skipWhile((ctx) => cnt-- > 0); } public skipAll(flag? : boolean) : BatchOperationContext { if (arguments.length < 1) { flag = true; } return this.skipWhile(() => flag); } public skipNext(flag? : boolean) : BatchOperationContext { this.skip(arguments.length < 1 ? 1 : (flag ? 1 : 0)); return this; } public skipWhile(predicate : (ctx : IBatchOperationContext) => boolean) : BatchOperationContext { this.skipWhilePredicate = predicate; return this; } public skipWhilePredicate : (ctx : IBatchOperationContext) => boolean; public value : any; } /** * List of batch operation execution types. */ export enum BatchOperationExecutionContext { /** * Global "before" action. */ before, /** * Operation action is executed. */ execution, /** * Global "after" action. */ after, /** * "Success" action is executed. */ success, /** * "Error" action is executed. */ error, /** * "Completed" action is executed. */ complete, /** * Global "finish all" action. */ finished, /** * Global "cancelled" action. */ cancelled } /** * Describes a batch. */ export interface IBatch { /** * Adds one or more items for the object in 'items' property. * * @chainable * * @param any ...items One or more item to add. */ addItems(...items: any[]) : IBatch; /** * Adds a logger. * * @chainable * * @param {Function} action The logger action. */ addLogger(action : (ctx : IBatchLogContext) => void) : IBatch; /** * Defines the global action that is invoke AFTER each operation. * * @chainable * * @param {Function} action The action to invoke. */ after(action : (ctx : IBatchOperationContext) => void) : IBatch; /** * Defines the global action that is invoke BEFORE each operation. * * @chainable * * @param {Function} action The action to invoke. */ before(action : (ctx : IBatchOperationContext) => void) : IBatch; /** * Gets or sets the ID of the batch. * * @property */ id : string; /** * Defines if "checkIfFinished" method should be autmatically invoked after * each operation. * * @chainable * * @param {Boolean} [flag] Automatically invoke "checkIfFinished" method or not. Default: (true) */ invokeFinishedCheckForAll(flag?: boolean) : IBatch; /** * Gets or sets the default invoke stradegy for an operation. */ invokeStrategy: InvokeStrategy; /** * Gets the batch wide (observable) array of items. * * @property */ items : ObservableArray<any>; /** * Gets the batch wide (observable) object. * * @property */ object : Observable; /** * Gets or sets the name of the batch. * * @property */ name : string; /** * Sets the invoke stradegy for an operation. * * @chainable * * @param {InvokeStrategy} stradegy The (new) value. */ setInvokeStrategy(stradegy: InvokeStrategy) : IBatch; /** * Sets properties for the object in 'object' property. * * @chainable * * @param {Object} properties The object that contains the properties. */ setObjectProperties(properties) : IBatch; /** * Sets the initial result value. * * @chainable * * @param any value The value. */ setResult(value : any) : IBatch; /** * Sets the initial result and execution value. * * @chainable * * @param any value The value. */ setResultAndValue(value : any) : IBatch; /** * Sets the initial execution value. * * @chainable * * @param any value The value. */ setValue(value : any) : IBatch; /** * Starts all operations. * * @return any The result of the last / of all operations. */ start() : any; /** * Defines the logic that is invoked after all operations have been finished. * * @chainable * * @param {Function} action The action. */ whenAllFinished(action : (ctx : IBatchOperationContext) => void) : IBatch; /** * Defined the logic that is invoked when batch have been cancelled. * * @chainable * * @param {Function} action The action. */ whenCancelled(action : (ctx : IBatchOperationContext) => void) : IBatch; } /** * Describes a batch log context. */ export interface IBatchLogContext { /** * Gets the underlying batch. * * @property */ batch? : IBatch; /** * Gets the underlying batch operation context. * * @property */ context? : IBatchOperationContext; /** * Gets the log message (value). */ message : any; /** * Gets the underlying batch operation. * * @property */ operation? : IBatchOperation; /** * Gets the timestamp. */ time : Date; } /** * Describes a logger. */ export interface IBatchLogger { /** * Logs a message. * * @chainable * * @param any msg The message to log. */ log(msg) : IBatchLogger; } /** * Describes a batch operation. */ export interface IBatchOperation { /** * Adds one or more items for the object in 'items' property. * * @chainable * * @param any ...items One or more item to add. */ addItems(...items: any[]) : IBatchOperation; /** * Adds a logger. * * @chainable * * @param {Function} action The logger action. */ addLogger(action : (ctx : IBatchLogContext) => void) : IBatchOperation; /** * Defines the global action that is invoke AFTER each operation. * * @chainable * * @param {Function} action The action to invoke. */ after(action : (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Gets the underlying batch. * * @property */ batch : IBatch; /** * Gets or sets the ID of the underlying batch. * * @property */ batchId : string; /** * Gets or sets the name of the underlying batch. * * @property */ batchName : string; /** * Defines the global action that is invoke BEFORE each operation. * * @chainable * * @param {Function} action The action to invoke. */ before(action : (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Defines the "completed" action. * * @chainable * * @param {Function} completedAction The "completed" action. */ complete(completedAction : (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Defines the "error" action. * * @chainable * * @param {Function} errorAction The "error" action. */ error(errorAction : (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Gets or sets the ID of the operation. * * @property */ id : string; /** * Ignores error of that operation. * * @chainable * * @param {Boolean} [flag] The flag to set. Default: (true) */ ignoreErrors(flag? : boolean) : IBatchOperation; /** * Defines if "checkIfFinished" method should be autmatically invoked after * each operation. * * @chainable * * @param {Boolean} [flag] Automatically invoke "checkIfFinished" method or not. Default: (true) */ invokeFinishedCheckForAll(flag?: boolean) : IBatchOperation; /** * Gets or sets the invoke stradegy for that operation. */ invokeStrategy: InvokeStrategy; /** * Gets the batch wide (observable) array of items. * * @property */ items : ObservableArray<any>; /** * Gets the batch wide (observable) object. * * @property */ object : Observable; /** * Gets or sets the name of the operation. * * @property */ name : string; /** * Defines the next operation. * * @chainable * * @param {Function} action The logic of the next operation. */ next(action: (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Sets the ID of the underlying batch. * * @param {String} id The new ID. * * @chainable */ setBatchId(id : string) : IBatchOperation; /** * Sets the name of the underlying batch. * * @param {String} name The new name. * * @chainable */ setBatchName(name : string) : IBatchOperation; /** * Sets the ID of the operation. * * @param {String} id The new ID. * * @chainable */ setId(id : string) : IBatchOperation; /** * Sets the invoke stradegy for that operation. * * @chainable * * @param {InvokeStrategy} stradegy The (new) value. */ setInvokeStrategy(stradegy: InvokeStrategy) : IBatchOperation; /** * Sets the name of the operation. * * @param {String} name The new name. * * @chainable */ setName(name : string) : IBatchOperation; /** * Sets properties for the object in 'object' property. * * @chainable * * @param {Object} properties The object that contains the properties. */ setObjectProperties(properties) : IBatchOperation; /** * Sets the initial result value for all operations. * * @chainable * * @param any value The value. */ setResult(value : any) : IBatchOperation; /** * Sets the initial result and execution value for all operations. * * @chainable * * @param any value The value. */ setResultAndValue(value : any) : IBatchOperation; /** * Sets the initial execution value for all operations. * * @chainable * * @param any value The value. */ setValue(value : any) : IBatchOperation; /** * Starts all operations. * * @return any The result of the last / of all operations. */ start() : any; /** * Defines the "success" action. * * @chainable * * @param {Function} successAction The "success" action. */ success(successAction : (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Alias for 'next()'. * * @chainable * * @param {Function} action The logic of the next operation. */ then(action: (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Defines the logic that is invoked after all operations have been finished. * * @chainable * * @param {Function} action The action. */ whenAllFinished(action : (ctx : IBatchOperationContext) => void) : IBatchOperation; /** * Defined the logic that is invoked when batch have been cancelled. * * @chainable * * @param {Function} action The action. */ whenCancelled(action : (ctx : IBatchOperationContext) => void) : IBatchOperation; } /** * Describes a context of a batch operation. */ export interface IBatchOperationContext extends IBatchLogger { /** * Gets the underlying batch. * * @property */ batch : IBatch; /** * Gets the ID of the underlying batch. * * @property */ batchId : string; /** * Gets the name of the underlying batch. * * @property */ batchName : string; /** * Cancels all upcoming operations. * * @chainable * * @param {Boolean} [flag] Cancel upcoming operations or not. Default: (true) */ cancel(flag?: boolean) : IBatchOperationContext; /** * Marks that operation as finished. * * @chainable */ checkIfFinished() : IBatchOperationContext; /** * Gets the name of the execution context. * * @property */ context : string; /** * Gets the thrown error. * * @property */ error? : any; /** * Gets the current execution context. * * @property */ executionContext? : BatchOperationExecutionContext; /** * Gets the ID of the underlying operation. * * @property */ id : string; /** * Gets the zero based index. * * @property */ index : number; /** * Defines if action should be invoked or not. */ invokeAction : boolean; /** * Defines if global "after" action should be invoked or not. */ invokeAfter : boolean; /** * Defines if global "before" action should be invoked or not. */ invokeBefore : boolean; /** * Defines if "completed" action should be invoked or not. */ invokeComplete : boolean; /** * Defines if "error" action should be invoked or not. */ invokeError : boolean; /** * Invokes the next operation. * * @chainable */ invokeNext() : IBatchOperationContext; /** * Defines if "success" action should be invoked or not. */ invokeSuccess : boolean; /** * Gets if the operation is NOT the first AND NOT the last one. * * @property */ isBetween : boolean; /** * Gets if that operation is the FIRST one. * * @property */ isFirst : boolean; /** * Gets if that operation is the LAST one. * * @property */ isLast : boolean; /** * Gets the batch wide (observable) array of items. * * @property */ items: ObservableArray<any>; /** * Gets the name of the underlying operation. * * @property */ name : string; /** * Gets or sets the invoke stradegy for the next operation. */ nextInvokeStradegy : InvokeStrategy; /** * Gets or sets the value for the next operation. * * @property */ nextValue : any; /** * Gets the batch wide (observable) object. * * @property */ object: Observable; /** * Gets the underlying operation. * * @property */ operation : IBatchOperation; /** * Gets the value from the previous operation. * * @property */ prevValue : any; /** * Gets or sets the result for all operations. * * @property */ result : any; /** * Sets the invoke stradegy for the next operation. * * @chainable * * @param {InvokeStrategy} stradegy The (new) value. */ setNextInvokeStradegy(stradegy: InvokeStrategy) : IBatchOperationContext; /** * Sets the values for 'result' any 'value' properties. * * @chainable * * @param any value The value to set. */ setResultAndValue(value : any) : IBatchOperationContext; /** * Sets the number of operations to skip. * * @chainable * * @param {Number} cnt The number of operations to skip. Default: 1 */ skip(cnt? : number) : IBatchOperationContext; /** * Skips all upcoming operations. * * @chainable * * @param {Boolean} [flag] Skip all upcoming operations or not. Default: (true) */ skipAll(flag? : boolean) : IBatchOperationContext; /** * Defines if next operation should be skipped or not. * * @chainable * * @param {Boolean} [flag] Skip next operation or not. Default: (true) */ skipNext(flag? : boolean) : IBatchOperationContext; /** * Skips all upcoming operations that matches a predicate. * * @chainable * * @param {Function} predicate The predicate to use. */ skipWhile(predicate : (ctx : IBatchOperationContext) => boolean) : IBatchOperationContext; /** * Gets or sets the value for that and all upcoming operations. */ value : any; } /** * List of invoke stradegies. */ export enum InvokeStrategy { /** * Automatic */ Automatic, /** * From batch operation. */ Manually, } /** * Creates a new batch. * * @function newBatch * * @return {IBatchOperation} The first operation of the created batch. */ export function newBatch(firstAction : (ctx : IBatchOperationContext) => void) : IBatchOperation { return new Batch(firstAction).firstOperation; }
the_stack
import type { BaseCanvas, BaseCanvasElement, BaseCanvasRenderingContext2D } from './BaseCanvas'; export const fontRegExp = /([\d.]+)(px|pt|pc|in|cm|mm|%|em|ex|ch|rem|q)/i; export const getFontHeight = (() => { const kCache = new Map<string, number>(); return (font: string): number => { // If it was already parsed, do not parse again const previous = kCache.get(font); if (previous) return previous; // Test for required properties first, return null if the text is invalid const sizeFamily = fontRegExp.exec(font); if (!sizeFamily) return 0; let size = Number(sizeFamily[1]); const unit = sizeFamily[2]; switch (unit) { case 'pt': size /= 0.75; break; case 'pc': size *= 16; break; case 'in': size *= 96; break; case 'cm': size *= 96.0 / 2.54; break; case 'mm': size *= 96.0 / 25.4; break; case 'em': case 'rem': size *= 16 / 0.75; break; case 'q': size *= 96 / 25.4 / 4; break; } kCache.set(font, size); return size; }; })(); export const textWrap = < CanvasType extends BaseCanvasElement, ContextType extends BaseCanvasRenderingContext2D, ImageType extends Parameters<ContextType['drawImage']>[0], TextMetricsType extends ReturnType<ContextType['measureText']> >( canvas: BaseCanvas<CanvasType, ContextType, ImageType, TextMetricsType>, text: string, wrapWidth: number ): string => { const result = []; const buffer = []; const spaceWidth = canvas.measureText(' ').width; // Run the loop for each line for (const line of text.split(/\r?\n/)) { let spaceLeft = wrapWidth; // Run the loop for each word for (const word of line.split(' ')) { const wordWidth = canvas.measureText(word).width; // eslint-disable-next-line @typescript-eslint/restrict-plus-operands const wordWidthWithSpace = wordWidth + spaceWidth; if (wordWidthWithSpace > spaceLeft) { if (buffer.length) { result.push(buffer.join(' ')); buffer.length = 0; } buffer.push(word); spaceLeft = wrapWidth - wordWidth; } else { spaceLeft -= wordWidthWithSpace; buffer.push(word); } } if (buffer.length) { result.push(buffer.join(' ')); buffer.length = 0; } } return result.join('\n'); }; /** * The names of the filters that take a string argument. */ type LiteralFilters = 'url'; export type Percentage<T extends number = number> = `${T}%`; /** * The names of the filters that take a percentage argument. */ type PercentageFilters = 'brightness' | 'contrast' | 'grayscale' | 'invert' | 'opacity' | 'saturate' | 'sepia'; type RelativeLengthUnits = 'cap' | 'ch' | 'em' | 'ex' | 'ic' | 'lh' | 'rem' | 'rlh'; type RelativeUnits = RelativeLengthUnits | '%'; type ViewportPercentageUnits = 'vh' | 'vw' | 'vi' | 'vb' | 'vmin' | 'vmax'; type AbsoluteLengthUnits = 'px' | 'cm' | 'mm' | 'Q' | 'in' | 'pc' | 'pt'; type LengthUnits = RelativeUnits | ViewportPercentageUnits | AbsoluteLengthUnits; export type Length<T extends number = number> = `${T}${LengthUnits}`; /** * The names of the filters that take a length argument. */ type LengthFilters = 'blur'; type AngleUnits = 'deg' | 'grad' | 'rad' | 'turn'; export type Angle<T extends number = number> = `${T}${AngleUnits}`; /** * The names of the filters that take an angle argument. */ type AngleFilters = 'hue-rotate'; export type Color = ColorKeyword | ColorHexadecimal | ColorRGB | ColorRGBA | ColorHSL | ColorHSLA; interface Filter { <K extends LiteralFilters, V extends string>(name: K, url: V): `${K}(${V})`; <K extends PercentageFilters, V extends Percentage>(name: K, percentage: V): `${K}(${V})`; <K extends LengthFilters, V extends Length>(name: K, length: V): `${K}(${V})`; <K extends AngleFilters, V extends Angle>(name: K, angle: V): `${K}(${V})`; <Vx extends Length, Vy extends Length>(name: 'drop-shadow', x: Vx, y: Vy): `drop-shadow(${Vx} ${Vy})`; <Vx extends Length, Vy extends Length, Vb extends Length>(name: 'drop-shadow', x: Vx, y: Vy, blur: Vb): `drop-shadow(${Vx} ${Vy} ${Vb})`; <Vx extends Length, Vy extends Length, Vc extends Color>(name: 'drop-shadow', x: Vx, y: Vy, color: Vc): `drop-shadow(${Vx} ${Vy} ${Vc})`; <Vx extends Length, Vy extends Length, Vb extends Length, Vc extends Color>( name: 'drop-shadow', x: Vx, y: Vy, blur: Vb, color: Vc ): `drop-shadow(${Vx} ${Vy} ${Vb} ${Vc})`; (value: 'none'): 'none'; } // @ts-expect-error: Overload hell export const filter: Filter = (name: string, ...args: readonly any[]) => `${name}(${args.join(' ')})` as const; /** * Represents a formatted hexadecimal value. */ export type ColorHexadecimal<T extends string = string> = `#${T}`; /** * Utility to format an hexadecimal string into a CSS hexadecimal string. * @param hex The hexadecimal code. * @example * hex('FFF'); // -> '#FFF' * hex('0F0F0F'); // -> '#0F0F0F' */ export const hex = <T extends string>(hex: T): ColorHexadecimal<T> => `#${hex}` as const; /** * Represents a formatted RGB value. */ export type ColorRGB<R extends number = number, G extends number = number, B extends number = number> = `rgb(${R}, ${G}, ${B})`; /** * Utility to format a RGB set of values into a string. * @param red The red value, must be a number between 0 and 255 inclusive. * @param green The green value, must be a number between 0 and 255 inclusive. * @param blue The blue value, must be a number between 0 and 255 inclusive. * @see https://en.wikipedia.org/wiki/RGB_color_model#Geometric_representation * @example * rgb(255, 150, 65); // -> 'rgb(255, 150, 65)' */ export const rgb = <R extends number, G extends number, B extends number>(red: R, green: G, blue: B): ColorRGB<R, G, B> => `rgb(${red}, ${green}, ${blue})` as const; /** * Represents a formatted RGBA value. */ export type ColorRGBA< R extends number = number, G extends number = number, B extends number = number, A extends number = number > = `rgba(${R}, ${G}, ${B}, ${A})`; /** * Utility to format a RGBA set of values into a string. * @param red The red value, must be a number between 0 and 255 inclusive. * @param green The green value, must be a number between 0 and 255 inclusive. * @param blue The blue value, must be a number between 0 and 255 inclusive. * @param alpha The alpha value, must be a number between 0 and 1 inclusive. * @see https://en.wikipedia.org/wiki/RGB_color_model#Geometric_representation * @example * rgba(255, 150, 65, 0.3); // -> 'rgba(255, 150, 65, 0.3)' */ export const rgba = <R extends number, G extends number, B extends number, A extends number>( red: R, green: G, blue: B, alpha: A ): ColorRGBA<R, G, B, A> => `rgba(${red}, ${green}, ${blue}, ${alpha})` as const; /** * Represents a formatted HSL value. */ export type ColorHSL<H extends number = number, S extends number = number, L extends number = number> = `hsl(${H}, ${S}%, ${L}%)`; /** * Utility to format a HSL set of values into a string. * @param hue The hue, must be a number between 0 and 360 inclusive. * @param saturation The saturation, must be a number between 0 and 100 inclusive. * @param lightness The lightness, must be a number between 0 and 100 inclusive, 0 will make it black, 100 will make it white. * @see https://en.wikipedia.org/wiki/HSL_and_HSV * @example * hsl(120, 100, 40); // -> 'hsl(120, 100, 40)' */ export const hsl = <H extends number, S extends number, L extends number>(hue: H, saturation: S, lightness: L): ColorHSL<H, S, L> => `hsl(${hue}, ${saturation}%, ${lightness}%)` as const; /** * Represents a formatted HSL value. */ export type ColorHSLA< H extends number = number, S extends number = number, L extends number = number, A extends number = number > = `hsla(${H}, ${S}%, ${L}%, ${A})`; /** * Utility to format a HSLA set of values into a string. * @param hue The hue, must be a number between 0 and 360 inclusive. * @param saturation The saturation, must be a number between 0 and 100 inclusive. * @param lightness The lightness, must be a number between 0 and 100 inclusive, 0 will make it black, 100 will make it white * @param alpha The alpha value, must be a number between 0 and 1 inclusive. * @see https://en.wikipedia.org/wiki/HSL_and_HSV * @example * hsla(120, 100, 40, 0.4); // -> 'hsla(120, 100, 40, 0.4)' */ export const hsla = <H extends number, S extends number, L extends number, A extends number>( hue: H, saturation: S, lightness: L, alpha: A ): ColorHSLA<H, S, L, A> => `hsla(${hue}, ${saturation}%, ${lightness}%, ${alpha})` as const; /** * Utility to type-safely use CSS colors. * @param color The CSS keyword color. * @example * color('silver'); // ✔ * color('some-imaginary-number'); // ❌ */ export const color = (color: ColorKeyword): ColorKeyword => color; export type ColorKeyword = ColorKeywordLevel1 | ColorKeywordLevel2 | ColorKeywordLevel3 | ColorKeywordLevel4; export type ColorKeywordLevel1 = | 'black' | 'silver' | 'gray' | 'white' | 'maroon' | 'red' | 'purple' | 'fuchsia' | 'green' | 'lime' | 'olive' | 'yellow' | 'navy' | 'blue' | 'teal' | 'aqua'; export type ColorKeywordLevel2 = 'orange'; export type ColorKeywordLevel3 = | 'aliceblue' | 'antiquewhite' | 'aquamarine' | 'azure' | 'beige' | 'bisque' | 'blanchedalmond' | 'blueviolet' | 'brown' | 'burlywood' | 'cadetblue' | 'chartreuse' | 'chocolate' | 'coral' | 'cornflowerblue' | 'cornsilk' | 'crimson' | 'cyan' | 'darkblue' | 'darkcyan' | 'darkgoldenrod' | 'darkgray' | 'darkgreen' | 'darkgrey' | 'darkkhaki' | 'darkmagenta' | 'darkolivegreen' | 'darkorange' | 'darkorchid' | 'darkred' | 'darksalmon' | 'darkseagreen' | 'darkslateblue' | 'darkslategray' | 'darkslategrey' | 'darkturquoise' | 'darkviolet' | 'deeppink' | 'deepskyblue' | 'dimgray' | 'dimgrey' | 'dodgerblue' | 'firebrick' | 'floralwhite' | 'forestgreen' | 'gainsboro' | 'ghostwhite' | 'gold' | 'goldenrod' | 'greenyellow' | 'grey' | 'honeydew' | 'hotpink' | 'indianred' | 'indigo' | 'ivory' | 'khaki' | 'lavender' | 'lavenderblush' | 'lawngreen' | 'lemonchiffon' | 'lightblue' | 'lightcoral' | 'lightcyan' | 'lightgoldenrodyellow' | 'lightgray' | 'lightgreen' | 'lightgrey' | 'lightpink' | 'lightsalmon' | 'lightseagreen' | 'lightskyblue' | 'lightslategray' | 'lightslategrey' | 'lightsteelblue' | 'lightyellow' | 'limegreen' | 'linen' | 'magenta' | 'mediumaquamarine' | 'mediumblue' | 'mediumorchid' | 'mediumpurple' | 'mediumseagreen' | 'mediumslateblue' | 'mediumspringgreen' | 'mediumturquoise' | 'mediumvioletred' | 'midnightblue' | 'mintcream' | 'mistyrose' | 'moccasin' | 'navajowhite' | 'oldlace' | 'olivedrab' | 'orangered' | 'orchid' | 'palegoldenrod' | 'palegreen' | 'paleturquoise' | 'palevioletred' | 'papayawhip' | 'peachpuff' | 'peru' | 'pink' | 'plum' | 'powderblue' | 'rosybrown' | 'royalblue' | 'saddlebrown' | 'salmon' | 'sandybrown' | 'seagreen' | 'seashell' | 'sienna' | 'skyblue' | 'slateblue' | 'slategray' | 'slategrey' | 'snow' | 'springgreen' | 'steelblue' | 'tan' | 'thistle' | 'tomato' | 'turquoise' | 'violet' | 'wheat' | 'whitesmoke' | 'yellowgreen'; export type ColorKeywordLevel4 = 'rebeccapurple';
the_stack
import { clone } from 'gl-vec2'; import { QuaggaContext } from '../QuaggaContext'; import _initBuffers from './initBuffers'; import _getViewPort from './getViewPort'; import ImageWrapper from '../common/image_wrapper'; import BarcodeDecoder from '../decoder/barcode_decoder'; import _initCanvas from './initCanvas'; import BarcodeLocator from '../locator/barcode_locator'; import InputStream from '../input/input_stream/input_stream'; import FrameGrabber from '../input/frame_grabber.js'; import * as QWorkers from './qworker'; import setupInputStream from './setupInputStream'; import CameraAccess from '../input/camera_access'; import { BarcodeInfo } from '../reader/barcode_reader'; import { moveLine, moveBox } from './transform'; import { QuaggaJSResultObject, QuaggaJSReaderConfig } from '../../type-definitions/quagga.d'; import Events from '../common/events'; export default class Quagga { context: QuaggaContext = new QuaggaContext(); initBuffers(imageWrapper?: ImageWrapper): void { if (!this.context.config) { return; } const { inputImageWrapper, boxSize } = _initBuffers( this.context.inputStream, imageWrapper, this.context.config.locator, ); this.context.inputImageWrapper = inputImageWrapper; this.context.boxSize = boxSize; } initializeData(imageWrapper?: ImageWrapper): void { if (!this.context.config) { return; } this.initBuffers(imageWrapper); this.context.decoder = BarcodeDecoder.create(this.context.config.decoder, this.context.inputImageWrapper); } getViewPort(): Element | null { if (!this.context.config || !this.context.config.inputStream) { return null; } const { target } = this.context.config.inputStream; return _getViewPort(target); } ready(callback: () => void): void { this.context.inputStream.play(); callback(); } initCanvas(): void { const container = _initCanvas(this.context); if (!container) { return; } const { ctx, dom } = container; this.context.canvasContainer.dom.image = dom.image; this.context.canvasContainer.dom.overlay = dom.overlay; this.context.canvasContainer.ctx.image = ctx.image; this.context.canvasContainer.ctx.overlay = ctx.overlay; } canRecord = (callback: () => void): void => { if (!this.context.config) { return; } BarcodeLocator.checkImageConstraints(this.context.inputStream, this.context.config?.locator); this.initCanvas(); this.context.framegrabber = FrameGrabber.create( this.context.inputStream, this.context.canvasContainer.dom.image, ); if (this.context.config.numOfWorkers === undefined) { this.context.config.numOfWorkers = 0; } QWorkers.adjustWorkerPool(this.context.config.numOfWorkers, this.context.config, this.context.inputStream, () => { if (this.context.config?.numOfWorkers === 0) { this.initializeData(); } this.ready(callback); }); }; initInputStream(callback: (err?: Error) => void): void { if (!this.context.config || !this.context.config.inputStream) { return; } const { type: inputType, constraints } = this.context.config.inputStream; const { video, inputStream } = setupInputStream(inputType, this.getViewPort(), InputStream); if (inputType === 'LiveStream' && video) { CameraAccess.request(video, constraints) .then(() => inputStream.trigger('canrecord')) .catch((err) => callback(err)); } inputStream.setAttribute('preload', 'auto'); inputStream.setInputStream(this.context.config.inputStream); inputStream.addEventListener('canrecord', this.canRecord.bind(undefined, callback)); this.context.inputStream = inputStream; } getBoundingBoxes(): Array<Array<number>> | null { return this.context.config?.locate ? BarcodeLocator.locate() : [[ clone(this.context.boxSize[0]), clone(this.context.boxSize[1]), clone(this.context.boxSize[2]), clone(this.context.boxSize[3]), ]]; } // TODO: need a typescript type for result here. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types transformResult(result: any): void { const topRight = this.context.inputStream.getTopRight(); const xOffset = topRight.x; const yOffset = topRight.y; if (xOffset === 0 && yOffset === 0) { return; } if (result.barcodes) { // TODO: BarcodeInfo may not be the right type here. result.barcodes.forEach((barcode: BarcodeInfo) => this.transformResult(barcode)); } if (result.line && result.line.length === 2) { moveLine(result.line, xOffset, yOffset); } if (result.box) { moveBox(result.box, xOffset, yOffset); } if (result.boxes && result.boxes.length > 0) { for (let i = 0; i < result.boxes.length; i++) { moveBox(result.boxes[i], xOffset, yOffset); } } } addResult(result: QuaggaJSResultObject, imageData: Array<number>): void { if (!imageData || !this.context.resultCollector) { return; } // TODO: Figure out what data structure holds a "barcodes" result, if any... if (result.barcodes) { result.barcodes.filter((barcode: QuaggaJSResultObject) => barcode.codeResult) .forEach((barcode: QuaggaJSResultObject) => this.addResult(barcode, imageData)); } else if (result.codeResult) { this.context.resultCollector.addResult( imageData, this.context.inputStream.getCanvasSize(), result.codeResult, ); } } // eslint-disable-next-line class-methods-use-this hasCodeResult(result: QuaggaJSResultObject): boolean { return !!(result && (result.barcodes ? result.barcodes.some((barcode) => barcode.codeResult) : result.codeResult)); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types publishResult(result: QuaggaJSResultObject | null = null, imageData?: any): void { let resultToPublish: Array<QuaggaJSResultObject> | QuaggaJSResultObject | null = result; if (result && this.context.onUIThread) { this.transformResult(result); this.addResult(result, imageData); resultToPublish = result.barcodes || result; } Events.publish('processed', resultToPublish as never); if (this.hasCodeResult(result as QuaggaJSResultObject)) { Events.publish('detected', resultToPublish as never); } } locateAndDecode(): void { const boxes = this.getBoundingBoxes(); if (boxes) { const decodeResult = this.context.decoder.decodeFromBoundingBoxes(boxes) || {}; decodeResult.boxes = boxes; this.publishResult(decodeResult, this.context.inputImageWrapper?.data); } else { const imageResult = this.context.decoder.decodeFromImage(this.context.inputImageWrapper); if (imageResult) { this.publishResult(imageResult, this.context.inputImageWrapper?.data); } else { this.publishResult(); } } } update = (): void => { if (this.context.onUIThread) { const workersUpdated = QWorkers.updateWorkers(this.context.framegrabber); if (!workersUpdated) { this.context.framegrabber.attachData(this.context.inputImageWrapper?.data); if (this.context.framegrabber.grab()) { if (!workersUpdated) { this.locateAndDecode(); } } } } else { this.context.framegrabber.attachData(this.context.inputImageWrapper?.data); this.context.framegrabber.grab(); this.locateAndDecode(); } }; startContinuousUpdate(): void { let next: number | null = null; const delay = 1000 / (this.context.config?.frequency || 60); this.context.stopped = false; const { context } = this; const newFrame = (timestamp: number) => { next = next || timestamp; if (!context.stopped) { if (timestamp >= next) { next += delay; this.update(); } window.requestAnimationFrame(newFrame); } }; newFrame(performance.now()); } start(): void { if (this.context.onUIThread && this.context.config?.inputStream?.type === 'LiveStream') { this.startContinuousUpdate(); } else { this.update(); } } async stop(): Promise<void> { this.context.stopped = true; QWorkers.adjustWorkerPool(0); if (this.context.config?.inputStream && this.context.config.inputStream.type === 'LiveStream') { await CameraAccess.release(); this.context.inputStream.clearEventHandlers(); } } setReaders(readers: Array<QuaggaJSReaderConfig>): void { if (this.context.decoder) { this.context.decoder.setReaders(readers); } QWorkers.setReaders(readers); } registerReader(name: string, reader: QuaggaJSReaderConfig): void { BarcodeDecoder.registerReader(name, reader); if (this.context.decoder) { this.context.decoder.registerReader(name, reader); } QWorkers.registerReader(name, reader); } }
the_stack
import { Primitive } from './aliases-and-guards'; /** * Credits to all the people who given inspiration and shared some very useful code snippets * in the following github issue: https://github.com/Microsoft/TypeScript/issues/12215 */ /** * SetIntersection (same as Extract) * @desc Set intersection of given union types `A` and `B` * @example * // Expect: "2" | "3" * SetIntersection<'1' | '2' | '3', '2' | '3' | '4'>; * * // Expect: () => void * SetIntersection<string | number | (() => void), Function>; */ export type SetIntersection<A, B> = A extends B ? A : never; /** * SetDifference (same as Exclude) * @desc Set difference of given union types `A` and `B` * @example * // Expect: "1" * SetDifference<'1' | '2' | '3', '2' | '3' | '4'>; * * // Expect: string | number * SetDifference<string | number | (() => void), Function>; */ export type SetDifference<A, B> = A extends B ? never : A; /** * SetComplement * @desc Set complement of given union types `A` and (it's subset) `A1` * @example * // Expect: "1" * SetComplement<'1' | '2' | '3', '2' | '3'>; */ export type SetComplement<A, A1 extends A> = SetDifference<A, A1>; /** * SymmetricDifference * @desc Set difference of union and intersection of given union types `A` and `B` * @example * // Expect: "1" | "4" * SymmetricDifference<'1' | '2' | '3', '2' | '3' | '4'>; */ export type SymmetricDifference<A, B> = SetDifference<A | B, A & B>; /** * NonUndefined * @desc Exclude undefined from set `A` * @example * // Expect: "string | null" * SymmetricDifference<string | null | undefined>; */ export type NonUndefined<A> = A extends undefined ? never : A; /** * NonNullable * @desc Exclude undefined and null from set `A` * @example * // Expect: "string" * SymmetricDifference<string | null | undefined>; */ // type NonNullable - built-in /** * FunctionKeys * @desc Get union type of keys that are functions in object type `T` * @example * type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;}; * * // Expect: "setName | someFn" * type Keys = FunctionKeys<MixedProps>; */ export type FunctionKeys<T extends object> = { [K in keyof T]-?: NonUndefined<T[K]> extends Function ? K : never; }[keyof T]; /** * NonFunctionKeys * @desc Get union type of keys that are non-functions in object type `T` * @example * type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;}; * * // Expect: "name | someKey" * type Keys = NonFunctionKeys<MixedProps>; */ export type NonFunctionKeys<T extends object> = { [K in keyof T]-?: NonUndefined<T[K]> extends Function ? never : K; }[keyof T]; /** * MutableKeys * @desc Get union type of keys that are mutable in object type `T` * Credit: Matt McCutchen * https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescript * @example * type Props = { readonly foo: string; bar: number }; * * // Expect: "bar" * type Keys = MutableKeys<Props>; */ export type MutableKeys<T extends object> = { [P in keyof T]-?: IfEquals< { [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P >; }[keyof T]; export type WritableKeys<T extends object> = MutableKeys<T>; /** * ReadonlyKeys * @desc Get union type of keys that are readonly in object type `T` * Credit: Matt McCutchen * https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescript * @example * type Props = { readonly foo: string; bar: number }; * * // Expect: "foo" * type Keys = ReadonlyKeys<Props>; */ export type ReadonlyKeys<T extends object> = { [P in keyof T]-?: IfEquals< { [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, never, P >; }[keyof T]; type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends < T >() => T extends Y ? 1 : 2 ? A : B; /** * RequiredKeys * @desc Get union type of keys that are required in object type `T` * @see https://stackoverflow.com/questions/52984808/is-there-a-way-to-get-all-required-properties-of-a-typescript-object * @example * type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; }; * * // Expect: "req" | "reqUndef" * type Keys = RequiredKeys<Props>; */ export type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K; }[keyof T]; /** * OptionalKeys * @desc Get union type of keys that are optional in object type `T` * @see https://stackoverflow.com/questions/52984808/is-there-a-way-to-get-all-required-properties-of-a-typescript-object * @example * type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; }; * * // Expect: "opt" | "optUndef" * type Keys = OptionalKeys<Props>; */ export type OptionalKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? K : never; }[keyof T]; /** * Pick (complements Omit) * @desc From `T` pick a set of properties by key `K` * @example * type Props = { name: string; age: number; visible: boolean }; * * // Expect: { age: number; } * type Props = Pick<Props, 'age'>; */ namespace Pick {} /** * PickByValue * @desc From `T` pick a set of properties by value matching `ValueType`. * Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c) * @example * type Props = { req: number; reqUndef: number | undefined; opt?: string; }; * * // Expect: { req: number } * type Props = PickByValue<Props, number>; * // Expect: { req: number; reqUndef: number | undefined; } * type Props = PickByValue<Props, number | undefined>; */ export type PickByValue<T, ValueType> = Pick< T, { [Key in keyof T]-?: T[Key] extends ValueType ? Key : never }[keyof T] >; /** * PickByValueExact * @desc From `T` pick a set of properties by value matching exact `ValueType`. * @example * type Props = { req: number; reqUndef: number | undefined; opt?: string; }; * * // Expect: { req: number } * type Props = PickByValueExact<Props, number>; * // Expect: { reqUndef: number | undefined; } * type Props = PickByValueExact<Props, number | undefined>; */ export type PickByValueExact<T, ValueType> = Pick< T, { [Key in keyof T]-?: [ValueType] extends [T[Key]] ? [T[Key]] extends [ValueType] ? Key : never : never; }[keyof T] >; /** * Omit (complements Pick) * @desc From `T` remove a set of properties by key `K` * @example * type Props = { name: string; age: number; visible: boolean }; * * // Expect: { name: string; visible: boolean; } * type Props = Omit<Props, 'age'>; */ export type Omit<T, K extends keyof any> = Pick<T, SetDifference<keyof T, K>>; /** * OmitByValue * @desc From `T` remove a set of properties by value matching `ValueType`. * Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c) * @example * type Props = { req: number; reqUndef: number | undefined; opt?: string; }; * * // Expect: { reqUndef: number | undefined; opt?: string; } * type Props = OmitByValue<Props, number>; * // Expect: { opt?: string; } * type Props = OmitByValue<Props, number | undefined>; */ export type OmitByValue<T, ValueType> = Pick< T, { [Key in keyof T]-?: T[Key] extends ValueType ? never : Key }[keyof T] >; /** * OmitByValueExact * @desc From `T` remove a set of properties by value matching exact `ValueType`. * @example * type Props = { req: number; reqUndef: number | undefined; opt?: string; }; * * // Expect: { reqUndef: number | undefined; opt?: string; } * type Props = OmitByValueExact<Props, number>; * // Expect: { req: number; opt?: string } * type Props = OmitByValueExact<Props, number | undefined>; */ export type OmitByValueExact<T, ValueType> = Pick< T, { [Key in keyof T]-?: [ValueType] extends [T[Key]] ? [T[Key]] extends [ValueType] ? never : Key : Key; }[keyof T] >; /** * Intersection * @desc From `T` pick properties that exist in `U` * @example * type Props = { name: string; age: number; visible: boolean }; * type DefaultProps = { age: number }; * * // Expect: { age: number; } * type DuplicateProps = Intersection<Props, DefaultProps>; */ export type Intersection<T extends object, U extends object> = Pick< T, Extract<keyof T, keyof U> & Extract<keyof U, keyof T> >; /** * Diff * @desc From `T` remove properties that exist in `U` * @example * type Props = { name: string; age: number; visible: boolean }; * type DefaultProps = { age: number }; * * // Expect: { name: string; visible: boolean; } * type DiffProps = Diff<Props, DefaultProps>; */ export type Diff<T extends object, U extends object> = Pick< T, SetDifference<keyof T, keyof U> >; /** * Subtract * @desc From `T` remove properties that exist in `T1` (`T1` has a subset of the properties of `T`) * @example * type Props = { name: string; age: number; visible: boolean }; * type DefaultProps = { age: number }; * * // Expect: { name: string; visible: boolean; } * type RestProps = Subtract<Props, DefaultProps>; */ export type Subtract<T extends T1, T1 extends object> = Pick< T, SetComplement<keyof T, keyof T1> >; /** * Overwrite * @desc From `U` overwrite properties to `T` * @example * type Props = { name: string; age: number; visible: boolean }; * type NewProps = { age: string; other: string }; * * // Expect: { name: string; age: string; visible: boolean; } * type ReplacedProps = Overwrite<Props, NewProps>; */ export type Overwrite< T extends object, U extends object, I = Diff<T, U> & Intersection<U, T> > = Pick<I, keyof I>; /** * Assign * @desc From `U` assign properties to `T` (just like object assign) * @example * type Props = { name: string; age: number; visible: boolean }; * type NewProps = { age: string; other: string }; * * // Expect: { name: string; age: number; visible: boolean; other: string; } * type ExtendedProps = Assign<Props, NewProps>; */ export type Assign< T extends object, U extends object, I = Diff<T, U> & Intersection<U, T> & Diff<U, T> > = Pick<I, keyof I>; /** * Exact * @desc Create branded object type for exact type matching */ export type Exact<A extends object> = A & { __brand: keyof A }; /** * Unionize * @desc Disjoin object to form union of objects, each with single property * @example * type Props = { name: string; age: number; visible: boolean }; * * // Expect: { name: string; } | { age: number; } | { visible: boolean; } * type UnionizedType = Unionize<Props>; */ export type Unionize<T extends object> = { [P in keyof T]: { [Q in P]: T[P] }; }[keyof T]; /** * PromiseType * @desc Obtain Promise resolve type * @example * // Expect: string; * type Response = PromiseType<Promise<string>>; */ export type PromiseType<T extends Promise<any>> = T extends Promise<infer U> ? U : never; // TODO: inline _DeepReadonlyArray with infer in DeepReadonly, same for all other deep types /** * DeepReadonly * @desc Readonly that works for deeply nested structure * @example * // Expect: { * // readonly first: { * // readonly second: { * // readonly name: string; * // }; * // }; * // } * type NestedProps = { * first: { * second: { * name: string; * }; * }; * }; * type ReadonlyNestedProps = DeepReadonly<NestedProps>; */ export type DeepReadonly<T> = T extends ((...args: any[]) => any) | Primitive ? T : T extends _DeepReadonlyArray<infer U> ? _DeepReadonlyArray<U> : T extends _DeepReadonlyObject<infer V> ? _DeepReadonlyObject<V> : T; /** @private */ // tslint:disable-next-line:class-name export interface _DeepReadonlyArray<T> extends ReadonlyArray<DeepReadonly<T>> {} /** @private */ export type _DeepReadonlyObject<T> = { readonly [P in keyof T]: DeepReadonly<T[P]>; }; /** * DeepRequired * @desc Required that works for deeply nested structure * @example * // Expect: { * // first: { * // second: { * // name: string; * // }; * // }; * // } * type NestedProps = { * first?: { * second?: { * name?: string; * }; * }; * }; * type RequiredNestedProps = DeepRequired<NestedProps>; */ export type DeepRequired<T> = T extends (...args: any[]) => any ? T : T extends any[] ? _DeepRequiredArray<T[number]> : T extends object ? _DeepRequiredObject<T> : T; /** @private */ // tslint:disable-next-line:class-name export interface _DeepRequiredArray<T> extends Array<DeepRequired<NonUndefined<T>>> {} /** @private */ export type _DeepRequiredObject<T> = { [P in keyof T]-?: DeepRequired<NonUndefined<T[P]>>; }; /** * DeepNonNullable * @desc NonNullable that works for deeply nested structure * @example * // Expect: { * // first: { * // second: { * // name: string; * // }; * // }; * // } * type NestedProps = { * first?: null | { * second?: null | { * name?: string | null | * undefined; * }; * }; * }; * type RequiredNestedProps = DeepNonNullable<NestedProps>; */ export type DeepNonNullable<T> = T extends (...args: any[]) => any ? T : T extends any[] ? _DeepNonNullableArray<T[number]> : T extends object ? _DeepNonNullableObject<T> : T; /** @private */ // tslint:disable-next-line:class-name export interface _DeepNonNullableArray<T> extends Array<DeepNonNullable<NonNullable<T>>> {} /** @private */ export type _DeepNonNullableObject<T> = { [P in keyof T]-?: DeepNonNullable<NonNullable<T[P]>>; }; /** * DeepPartial * @desc Partial that works for deeply nested structure * @example * // Expect: { * // first?: { * // second?: { * // name?: string; * // }; * // }; * // } * type NestedProps = { * first: { * second: { * name: string; * }; * }; * }; * type PartialNestedProps = DeepPartial<NestedProps>; */ export type DeepPartial<T> = T extends Function ? T : T extends Array<infer U> ? _DeepPartialArray<U> : T extends object ? _DeepPartialObject<T> : T | undefined; /** @private */ // tslint:disable-next-line:class-name export interface _DeepPartialArray<T> extends Array<DeepPartial<T>> {} /** @private */ export type _DeepPartialObject<T> = { [P in keyof T]?: DeepPartial<T[P]> }; /** * Brand * @desc Define nominal type of U based on type of T. Similar to Opaque types in Flow. * @example * type USD = Brand<number, "USD"> * type EUR = Brand<number, "EUR"> * * const tax = 5 as USD; * const usd = 10 as USD; * const eur = 10 as EUR; * * function gross(net: USD): USD { * return (net + tax) as USD; * } * * // Expect: No compile error * gross(usd); * // Expect: Compile error (Type '"EUR"' is not assignable to type '"USD"'.) * gross(eur); */ export type Brand<T, U> = T & { __brand: U }; /** * Optional * @desc From `T` make a set of properties by key `K` become optional * @example * type Props = { * name: string; * age: number; * visible: boolean; * }; * * // Expect: { name?: string; age?: number; visible?: boolean; } * type Props = Optional<Props>; * * // Expect: { name: string; age?: number; visible?: boolean; } * type Props = Optional<Props, 'age' | 'visible'>; */ export type Optional<T extends object, K extends keyof T = keyof T> = Omit< T, K > & Partial<Pick<T, K>>; /** * ValuesType * @desc Get the union type of all the values in an object, array or array-like type `T` * @example * type Props = { name: string; age: number; visible: boolean }; * // Expect: string | number | boolean * type PropsValues = ValuesType<Props>; * * type NumberArray = number[]; * // Expect: number * type NumberItems = ValuesType<NumberArray>; * * type ReadonlySymbolArray = readonly symbol[]; * // Expect: symbol * type SymbolItems = ValuesType<ReadonlySymbolArray>; * * type NumberTuple = [1, 2]; * // Expect: 1 | 2 * type NumberUnion = ValuesType<NumberTuple>; * * type ReadonlyNumberTuple = readonly [1, 2]; * // Expect: 1 | 2 * type AnotherNumberUnion = ValuesType<NumberTuple>; * * type BinaryArray = Uint8Array; * // Expect: number * type BinaryItems = ValuesType<BinaryArray>; */ export type ValuesType< T extends ReadonlyArray<any> | ArrayLike<any> | Record<any, any> > = T extends ReadonlyArray<any> ? T[number] : T extends ArrayLike<any> ? T[number] : T extends object ? T[keyof T] : never; /** * Required * @desc From `T` make a set of properties by key `K` become required * @example * type Props = { * name?: string; * age?: number; * visible?: boolean; * }; * * // Expect: { name: string; age: number; visible: boolean; } * type Props = Required<Props>; * * // Expect: { name?: string; age: number; visible: boolean; } * type Props = Required<Props, 'age' | 'visible'>; */ export type AugmentedRequired< T extends object, K extends keyof T = keyof T > = Omit<T, K> & Required<Pick<T, K>>; /** * UnionToIntersection * @desc Get intersection type given union type `U` * Credit: jcalz * @see https://stackoverflow.com/a/50375286/7381355 * @example * // Expect: { name: string } & { age: number } & { visible: boolean } * UnionToIntersection<{ name: string } | { age: number } | { visible: boolean }> */ export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; /** * Mutable * @desc From `T` make all properties become mutable * @example * type Props = { * readonly name: string; * readonly age: number; * readonly visible: boolean; * }; * * // Expect: { name: string; age: number; visible: boolean; } * Mutable<Props>; */ export type Mutable<T> = { -readonly [P in keyof T]: T[P] }; export type Writable<T> = Mutable<T>;
the_stack
import * as expect from 'expect'; import * as fc from 'fast-check'; import { Scanner } from '../../../cursor-doc/clojure-lexer'; import { toplevel, validPair } from '../../../cursor-doc/clojure-lexer' const MAX_LINE_LENGTH = 100; // fast-check Arbritraries // TODO: single quotes are valid in real Clojure, but Calva can't handle them in symbols yet const wsChars = [',', ' ', '\t', '\n', '\r', '\f', ...'\u000B\u001C\u001D\u001E\u001F\u2028\u2029\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2008\u2009\u200a\u205f\u3000']; const openChars = ['"', '(', '[', '{']; const closeChars = ['"', ')', ']', '}']; const formPrefixChars = ["'", '@', '~', '`', '^', ',']; const nonSymbolChars = [...wsChars, ...[';', '@', '~', '`', '^', '\\'], ...openChars, ...closeChars]; function symbolChar(): fc.Arbitrary<string> { // We need to filter away all kinds of whitespace, therefore the regex... return fc.unicode().filter(c => !(nonSymbolChars.includes(c) || c.match(/\s/))); } function formPrefixChar(): fc.Arbitrary<string> { return fc.constantFrom(...formPrefixChars); } function open(): fc.Arbitrary<string> { return fc.tuple(fc.stringOf(formPrefixChar(), 0, 3), fc.stringOf(fc.constantFrom(...[' ', '\t']), 0, 2), fc.constantFrom(...openChars)).map(([p, ws, o]) => `${p}${ws}${o}`); } function close(): fc.Arbitrary<string> { return fc.constantFrom(...closeChars); } function symbolStartIncludingDigit(): fc.Arbitrary<string> { return fc.tuple(symbolChar(), symbolChar(), symbolChar()) .map(([c1, c2, c3]) => `${c1}${c2}${c3}`) .filter(s => !!s.match(/^(?:[^#:]|#'[^'])/)); } function symbolStart(): fc.Arbitrary<string> { return symbolStartIncludingDigit().filter(s => !s.match(/^\d/)); } function symbol(): fc.Arbitrary<string> { return fc.tuple(symbolStart(), fc.stringOf(symbolChar(), 1, 5)).map(([c, s]) => `${c}${s}`); } function underscoreSymbol(): fc.Arbitrary<string> { return fc.tuple(fc.constant('_'), symbolStartIncludingDigit(), fc.stringOf(symbolChar(), 1, 5)).map(([c, s]) => `${c}${s}`); } function keyword(): fc.Arbitrary<string> { return fc.tuple(fc.constantFrom(":"), symbol()).map(([c, s]) => `${c}${s}`); } function wsChar(): fc.Arbitrary<string> { return fc.constantFrom(...wsChars); } function ws(): fc.Arbitrary<string> { return fc.stringOf(wsChar(), 1, 3); } function nonWsChar(): fc.Arbitrary<string> { return fc.unicode().filter(c => !(wsChars.includes(c) || c.match(/\s/))); } function nonWs(): fc.Arbitrary<string> { return fc.stringOf(nonWsChar(), 1, 3); } function quotedUnicode(): fc.Arbitrary<string> { return fc.tuple(fc.constantFrom('\\'), fc.unicode()).map(([c, s]) => `${c}${s}`); } function list(): fc.Arbitrary<string> { return fc.tuple(open(), symbol(), close()) .filter(([o, _s, c]) => { return validPair(o[o.length - 1], c) }) .map(([o, s, c]) => `${o}${s}${c}`); } function selectKeysTypeRaw(tokens: any[]) { return tokens.slice(0, tokens.length - 1) .map(t => { return { type: t.type, raw: t.raw } }); } function testTokens(data) { return data.map(d => { return { type: d[0], raw: d[1] } }); } describe('Scanner', () => { let scanner: Scanner; beforeEach(() => { scanner = new Scanner(MAX_LINE_LENGTH); }); describe('simple', () => { describe('symbols', () => { it('tokenizes any symbol', () => { fc.assert( fc.property(symbol(), data => { const tokens = scanner.processLine(data); expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe(data); }) ) }); it('tokenizes symbols starting with _', () => { fc.assert( fc.property(underscoreSymbol(), data => { const tokens = scanner.processLine(data); expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe(data); }) ) }); it('tokenizes _ as a symbol', () => { const tokens = scanner.processLine('_'); expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe('_'); }); it('does not tokenize something with leading digit as a symbol', () => { const tokens = scanner.processLine('1foo'); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe('1'); expect(tokens[1].type).toBe('id'); expect(tokens[1].raw).toBe('foo'); }); }); it('tokenizes whitespace', () => { fc.assert( fc.property(ws(), data => { // Remove extra eol put in there by the scanner const tokens = scanner.processLine(data).slice(0, -1); expect(tokens.map(t => t.raw).join("")).toBe(data); tokens.forEach(t => { expect(t.type).toBe('ws'); }); }) ) const tokens = scanner.processLine('foo bar'); expect(tokens[1].type).toBe('ws'); expect(tokens[1].raw).toBe(' '); }); describe('numbers', () => { it('tokenizes ints', () => { fc.assert( fc.property(fc.constantFrom(...["42", "0", "-007", "+42", "-0", "-42", "+3r11", "-25Rn", "00M" ]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text); }) ) }); it('tokenizes decimals', () => { fc.assert( fc.property(fc.constantFrom(...[ "4.2", "0.0", "+42.78", "-0.0", "42.0", "0042.0", "+18998.18998e+18998M", "-01.18e+18M", "-61E-19471M" ]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text); }) ) }); it('tokenizes hex', () => { fc.assert( fc.property(fc.constantFrom(...[ "0xf", "0xCafeBabe", "0x0", "+0X0", "-0xFAF", "0x3B85110", "0xfN", "0xCafeBabeN", "0x0N", "+0X0N", "-0xFAFN", "0x3B85110N" ]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text); }) ) }); it('tokenizes octal', () => { fc.assert( fc.property(fc.constantFrom(...[ "07", "007", "+01", "-01234567", "-0344310433453", "07N", "007N", "+01N", "-01234567N", "-0344310433453N" ]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text); }) ) }); it('tokenizes ratios', () => { fc.assert( fc.property(fc.constantFrom(...["1/2", "01/02", "-100/200", "+1/0"]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text); }) ) }); it('tokenizes symbolic values', () => { fc.assert( fc.property(fc.constantFrom(...["##Inf", "##-Inf", "##,, Inf", "## Inf", "## -Inf", "##NaN", "## NaN"]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text); }) ) }); it('tokenizes symbolic values with comments appended', () => { fc.assert( fc.property(fc.constantFrom(...[ "##Inf;", "##-Inf;comment", "## -Inf; comment", "##NaN;", "## NaN;comment" ]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text.substr(0, text.indexOf(';'))); expect(tokens[1].type).toBe('comment'); expect(tokens[1].raw).toBe(text.substr(text.indexOf(';'))); }) ) }); it('tokenizes symbolic values with backslash appended', () => { fc.assert( fc.property(fc.constantFrom(...[ "##Inf\\", "##-Inf\\comment", "## -Inf\\ comment", "##NaN\\", "## NaN\\comment" ]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text.substr(0, text.indexOf('\\'))); }) ) }); }); it('tokenizes keyword', () => { fc.assert( fc.property(keyword(), data => { const tokens = scanner.processLine(data); expect(tokens[0].type).toBe('kw'); expect(tokens[0].raw).toBe(data); }) ) }); describe('tokenizes literal characters', () => { it('tokenizes literal unicode characters', () => { fc.assert( fc.property(quotedUnicode(), data => { const tokens = scanner.processLine(data); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(data); }) ) }); it('tokenizes backslash', () => { fc.assert( fc.property(fc.constantFrom(...['\\']), data => { const tokens = scanner.processLine(data); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(data); }) ) }); it('tokenizes literal whitespace and control characters', () => { fc.assert( fc.property(fc.constantFrom(...[' ', '\b', '\t', '\r', '\n', '\f', '\0', '\\'].map(c => `\\${c}`)), data => { const tokens = scanner.processLine(data); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(data); }) ) const data = '\\\b' const tokens = scanner.processLine(data); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(data); }); it('tokenizes named literals', () => { fc.assert( fc.property(fc.constantFrom(...["\\space", "\\space,", "\\space;", "\\space ", "\\space\\newline"]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe('\\space'); }) ) }); it('tokenizes literals with comments appended', () => { fc.assert( fc.property(fc.constantFrom(...[ "\\newline;", "\\space;comment", "\\space; comment", "1;", "+1;" ]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe(text.substr(0, text.indexOf(';'))); expect(tokens[1].type).toBe('comment'); expect(tokens[1].raw).toBe(text.substr(text.indexOf(';'))); }) ) }); it('tokenizes numeric literals with ignores appended', () => { fc.assert( fc.property(fc.constantFrom(...["1#_", "+1#_", "-12#_", "4.2#_", "42.2#_"]), (text) => { const tokens = scanner.processLine(text); expect(selectKeysTypeRaw(tokens)).toEqual(testTokens([ ['lit', text.substr(0, text.indexOf('#_'))], ['ignore', '#_'] ])); }) ) }); }); it('tokenizes literal named character', () => { const tokens = scanner.processLine('\\space'); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe('\\space'); }); it('tokenizes line comments', () => { const tokens = scanner.processLine('; foo'); expect(tokens[0].type).toBe('comment'); expect(tokens[0].raw).toBe('; foo'); }); describe('tokenizes ignores', () => { it('sole, no ws', () => { const tokens = scanner.processLine('#_foo'); expect(tokens[0].type).toBe('ignore'); expect(tokens[0].raw).toBe('#_'); expect(tokens[1].type).toBe('id'); expect(tokens[1].raw).toBe('foo'); }); it('sole, trailing ws', () => { const tokens = scanner.processLine('#_ foo'); expect(tokens[0].type).toBe('ignore'); expect(tokens[0].raw).toBe('#_'); expect(tokens[1].type).toBe('ws'); expect(tokens[1].raw).toBe(' '); expect(tokens[2].type).toBe('id'); expect(tokens[2].raw).toBe('foo'); }); it('sole, leading symbol/id, no ws', () => { const tokens = scanner.processLine('foo#_bar'); expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe('foo#_bar'); }); it('sole, leading number, no ws', () => { const tokens = scanner.processLine('1.2#_foo'); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe('1.2'); expect(tokens[1].type).toBe('ignore'); expect(tokens[1].raw).toBe('#_'); expect(tokens[2].type).toBe('id'); expect(tokens[2].raw).toBe('foo'); }); it('many, no ws', () => { const tokens = scanner.processLine('#_#_#_foo'); expect(tokens[0].type).toBe('ignore'); expect(tokens[0].raw).toBe('#_'); expect(tokens[1].type).toBe('ignore'); expect(tokens[1].raw).toBe('#_'); expect(tokens[2].type).toBe('ignore'); expect(tokens[2].raw).toBe('#_'); expect(tokens[3].type).toBe('id'); expect(tokens[3].raw).toBe('foo'); }); it('adjacent after literals it is part of the token', () => { fc.assert( fc.property(fc.constantFrom(...["\\c#_"]), (text) => { const tokens = scanner.processLine(text); expect(tokens[0].raw).toBe(text); }) ) }); }); it('tokenizes the Calva repl prompt', () => { const tokens = scanner.processLine('foo꞉bar.baz꞉> ()'); expect(tokens[0].type).toBe('prompt'); expect(tokens[0].raw).toBe('foo꞉bar.baz꞉> '); expect(tokens[1].type).toBe('open'); expect(tokens[1].raw).toBe('('); expect(tokens[2].type).toBe('close'); expect(tokens[2].raw).toBe(')'); }); it('only tokenizes the Calva repl prompt if it is at the start of a line', () => { const tokens = scanner.processLine(' foo꞉bar.baz꞉> ()'); expect(tokens[0].type).toBe('ws'); expect(tokens[0].raw).toBe(' '); expect(tokens[1].type).toBe('id'); expect(tokens[1].raw).toBe('foo꞉bar.baz꞉>'); expect(tokens[2].type).toBe('junk'); expect(tokens[2].raw).toBe(' '); expect(tokens[3].type).toBe('open'); expect(tokens[3].raw).toBe('('); expect(tokens[4].type).toBe('close'); expect(tokens[4].raw).toBe(')'); }); it('only tokenizes the Calva repl prompt if it ends with a space', () => { const tokens = scanner.processLine('foo꞉bar.baz꞉>()'); expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe('foo꞉bar.baz꞉>'); expect(tokens[1].type).toBe('open'); expect(tokens[1].raw).toBe('('); expect(tokens[2].type).toBe('close'); expect(tokens[2].raw).toBe(')'); }); }); describe('lists', () => { it('tokenizes list/vector/map/string', () => { fc.assert( fc.property(list(), data => { const tokens = scanner.processLine(data); const numTokens = tokens.length; expect(tokens[numTokens - 4].type).toBe('open'); expect(tokens[numTokens - 2].type).toBe('close'); }) ); }); it('tokenizes list', () => { const tokens = scanner.processLine('(foo)'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('('); expect(tokens[1].type).toBe('id'); expect(tokens[1].raw).toBe('foo'); expect(tokens[2].type).toBe('close'); expect(tokens[2].raw).toBe(')'); }); it('tokenizes vector', () => { const tokens = scanner.processLine('[foo]'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('['); expect(tokens[1].type).toBe('id'); expect(tokens[1].raw).toBe('foo'); expect(tokens[2].type).toBe('close'); expect(tokens[2].raw).toBe(']'); }); it('tokenizes map', () => { const tokens = scanner.processLine('{:foo bar}'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('{'); expect(tokens[1].type).toBe('kw'); expect(tokens[1].raw).toBe(':foo'); expect(tokens[2].type).toBe('ws'); expect(tokens[2].raw).toBe(' '); expect(tokens[3].type).toBe('id'); expect(tokens[3].raw).toBe('bar'); expect(tokens[4].type).toBe('close'); expect(tokens[4].raw).toBe('}'); }); it('tokenizes set', () => { const tokens = scanner.processLine('#{:foo :bar}'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('#{'); expect(tokens[1].type).toBe('kw'); expect(tokens[1].raw).toBe(':foo'); expect(tokens[2].type).toBe('ws'); expect(tokens[2].raw).toBe(' '); expect(tokens[3].type).toBe('kw'); expect(tokens[3].raw).toBe(':bar'); expect(tokens[4].type).toBe('close'); expect(tokens[4].raw).toBe('}'); }); it('tokenizes string', () => { const tokens = scanner.processLine('"foo"'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('"'); expect(tokens[1].type).toBe('str-inside'); expect(tokens[1].raw).toBe('foo'); expect(tokens[2].type).toBe('close'); expect(tokens[2].raw).toBe('"'); }); it('tokenizes regex', () => { const tokens = scanner.processLine('#"foo"'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('#"'); expect(tokens[1].type).toBe('str-inside'); expect(tokens[1].raw).toBe('foo'); expect(tokens[2].type).toBe('close'); expect(tokens[2].raw).toBe('"'); }); }); describe('data reader tags', () => { it('tokenizes tag, separate line', () => { const tokens = scanner.processLine('#foo'); expect(tokens[0].type).toBe('reader'); expect(tokens[0].raw).toBe('#foo'); }); it('does not treat var quote plus open token as reader tag plus open token', () => { const tokens = scanner.processLine("#'foo []") expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe("#'foo"); expect(tokens[1].type).toBe('ws'); expect(tokens[1].raw).toBe(' '); expect(tokens[2].type).toBe('open'); expect(tokens[2].raw).toBe('['); expect(tokens[3].type).toBe('close'); expect(tokens[3].raw).toBe(']'); }); }); describe('strings', () => { it('tokenizes words in strings', () => { const tokens = scanner.processLine('"(foo :bar)"'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('"'); expect(tokens[1].type).toBe('str-inside'); expect(tokens[1].raw).toBe('(foo'); expect(tokens[2].type).toBe('ws'); expect(tokens[2].raw).toBe(' '); expect(tokens[3].type).toBe('str-inside'); expect(tokens[3].raw).toBe(':bar)'); expect(tokens[4].type).toBe('close'); expect(tokens[4].raw).toBe('"'); }); it('tokenizes newlines in strings', () => { const tokens = scanner.processLine('"foo\nbar"'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('"'); expect(tokens[1].type).toBe('str-inside'); expect(tokens[1].raw).toBe('foo'); expect(tokens[2].type).toBe('ws'); expect(tokens[2].raw).toBe('\n'); expect(tokens[3].type).toBe('str-inside'); expect(tokens[3].raw).toBe('bar'); expect(tokens[4].type).toBe('close'); expect(tokens[4].raw).toBe('"'); }); it('tokenizes quoted quotes in strings', () => { let tokens = scanner.processLine('"\\""'); expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('"'); expect(tokens[1].type).toBe('str-inside'); expect(tokens[1].raw).toBe('\\"'); tokens = scanner.processLine('"foo\\"bar"'); expect(tokens[1].type).toBe('str-inside'); expect(tokens[1].raw).toBe('foo\\"bar'); }); }); describe('Reported issues', () => { it('too long lines - #566', () => { // https://github.com/BetterThanTomorrow/calva/issues/556 const longLine = "foo ".repeat(26), tokens = scanner.processLine(longLine); expect(tokens[0].type).toBe('too-long-line'); expect(tokens[0].raw).toBe(longLine); }); it('handles literal quotes - #566', () => { // https://github.com/BetterThanTomorrow/calva/issues/566 const tokens = scanner.processLine("\\' foo"); expect(tokens[0].type).toBe('lit'); expect(tokens[0].raw).toBe("\\'"); expect(tokens[1].type).toBe('ws'); expect(tokens[1].raw).toBe(" "); expect(tokens[2].type).toBe('id'); expect(tokens[2].raw).toBe("foo"); }); it('handles symbols ending in =? - #566', () => { // https://github.com/BetterThanTomorrow/calva/issues/566 const tokens = scanner.processLine("foo=? foo"); expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe("foo=?"); expect(tokens[1].type).toBe('ws'); expect(tokens[1].raw).toBe(" "); expect(tokens[2].type).toBe('id'); expect(tokens[2].raw).toBe("foo"); }); it('does not treat var quoted symbols as reader tags - #584', () => { // https://github.com/BetterThanTomorrow/calva/issues/584 const tokens = scanner.processLine("#'foo"); expect(tokens[0].type).toBe('id'); expect(tokens[0].raw).toBe("#'foo"); }); it('does not croak on funny data in strings - #659', () => { // https://github.com/BetterThanTomorrow/calva/issues/659 const tokens = scanner.processLine('" "'); // <- That's not a regular space expect(tokens[0].type).toBe('open'); expect(tokens[0].raw).toBe('"'); expect(tokens[1].type).toBe('junk'); expect(tokens[1].raw).toBe(' '); expect(tokens[2].type).toBe('close'); expect(tokens[2].raw).toBe('"'); }); it('does not hang on matching token rule regexes against a string of hashes', () => { // https://github.com/BetterThanTomorrow/calva/issues/667 const text = '#################################################'; const rule = toplevel.rules.find(rule => rule.name === "open"); toplevel.rules.forEach(rule => { console.log(`Testing rule: ${rule.name}`) const x = rule.r.exec(text); console.log(`Tested rule: ${rule.name}`) if (!['reader', 'junk'].includes(rule.name)) { expect(x).toBeNull(); } else { expect(x.length).toBe(1); } }); }); it('does not croak on comments with hashes - #667', () => { // https://github.com/BetterThanTomorrow/calva/issues/659 const text = ';; ################################################# FRONTEND'; const tokens = scanner.processLine(text); expect(tokens.length).toBe(2); expect(tokens[0].type).toBe('comment'); expect(tokens[0].raw === text); }); }); });
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as uuid from 'uuid/v4'; import chalk from 'chalk'; import { IEntityConfig, IRelation, IQuery, IField, IApplyOptions, IFieldUpdate } from '@materia/interfaces'; import { App } from '../app'; import { MateriaError } from '../error'; import { MigrationType } from '../history'; import { Addon } from '../addons/addon'; import { Field } from './field'; import { Query, IQueryConstructor } from './query'; import { ConfigType } from '../config'; /** * @class Entity * @classdesc * An entity, in a database this correspond to a table. */ export abstract class Entity { relations_queue: Array<{relation: IRelation, options: IApplyOptions}>; queryObjects: any; id: string; name: string; x: number; y: number; isRelation: any; fields: Array<Field>; relations: Array<IRelation>; queries: Array<Query>; fromAddon: Addon; abstract model: any; abstract reservedQueries: string[]; constructor(public app: App, queryTypes) { this.relations_queue = []; this.queryObjects = {}; if (queryTypes) { this.defineQueryObjects(queryTypes); } } abstract generateDefaultQueries(); fixIsRelation(options?: IApplyOptions): Promise<void> { if ( ! this.isRelation) { return Promise.resolve(); } const entity1 = this.app.entities.get(this.isRelation[0].entity); const entity2 = this.app.entities.get(this.isRelation[1].entity); let p = Promise.resolve(); if ( ! entity1 || ! entity2) { // converts to / keep belongsTo relations const pk1 = entity1 && entity1.getPK()[0]; if (pk1) { const rel = { type: 'belongsTo', field: this.isRelation[0].field, reference: { entity: entity1.name, field: pk1.name } }; if (entity1.getRelationIndex(rel) == -1) { p = p.then(() => this.addRelation(rel, options)); } } const pk2 = entity2 && entity2.getPK()[0]; if (pk2) { const rel = { type: 'belongsTo', field: this.isRelation[1].field, reference: { entity: entity2.name, field: pk2.name } }; if (entity2.getRelationIndex(rel) == -1) { p = p.then(() => this.addRelation(rel, options)); } } delete this.isRelation; } else { // add missing belongsToMany relations in related entities const rel1 = { type: 'belongsToMany', through: this.name, as: this.isRelation[0].field, reference: { entity: entity2.name, as: this.isRelation[1].field } }; if (entity1.getRelationIndex(rel1) == -1) { p = p.then(() => entity1.addRelation(rel1, options)); } const rel2 = { type: 'belongsToMany', through: this.name, as: this.isRelation[1].field, reference: { entity: entity1.name, as: this.isRelation[0].field } }; if (entity2.getRelationIndex(rel2) == -1) { p = p.then(() => entity2.addRelation(rel2, options)); } } return p; } move(x, y): Promise<void> { this.x = x; this.y = y; return this.savePosition(); } create(entityobj, options) { options = options || {}; this.name = entityobj.name; this.id = entityobj.id || uuid(); if (entityobj.x && entityobj.y) { this.x = entityobj.x; this.y = entityobj.y; } else { this.app.config.reloadConfig(); const entityPosition = this.app.config.entitiesPosition[entityobj.name]; if (entityPosition) { this.x = entityPosition.x; this.y = entityPosition.y; } } this.fields = []; this.relations = []; this.queries = []; this.isRelation = entityobj.isRelation; this.fromAddon = options.fromAddon; const promises = []; if (entityobj.fields) { entityobj.fields.forEach((field) => { promises.push(this.addField(field, {history: false, save: false, db: false, generateQueries: false})); }); } if (entityobj.relations) { entityobj.relations.forEach((relation) => { if (options.wait_relations) { this.relations_queue.push({relation: relation, options: {history: false, save: false, db: false}}); } else { promises.push(this.addRelation(relation, {history: false, save: false, db: false})); } }); } return Promise.all(promises); } loadQueries(queries: Array<IQuery>): void { this.generateDefaultQueries(); if (queries) { queries.forEach((query) => { // fix: don't overload default query else it always overload after the first generation if (this.reservedQueries.indexOf(query.id) == -1) { try { this.app.logger.log(` │ │ └── ${chalk.bold(this.name)}.${chalk.bold(query.id)}`); this.addQuery(query, {history: false, save: false}); } catch (e) { const err = e.originalError || e instanceof MateriaError && e; if (err) { this.app.logger.warn(` │ │ │ (Warning) Skipped query "${query.id}" of entity "${this.name}"`); this.app.logger.warn(' │ │ │ due to error: ' + err.stack); } else { throw e; } } } }); } } applyRelations() { const promises = []; for (const relobj of this.relations_queue) { if (this.app.entities.get(relobj.relation.reference.entity)) { promises.push(this.addRelation(relobj.relation, relobj.options).catch((e) => { this.app.logger.warn(`In ${this.name}: ${e && e.message}. Skipped relation`); return Promise.resolve(); })); } } this.relations_queue = []; return Promise.all(promises).then(() => { this.refreshQueries(); }); } save(): Promise<void> { if (this.fromAddon) { return Promise.resolve(); } else { const relativePath = path.join('server', 'models', this.name + '.json'); const entityModel = Object.assign({}, this.toJson()); delete entityModel.x; delete entityModel.y; return new Promise((resolve, reject) => { fs.writeFile( path.join(this.app.path, relativePath), JSON.stringify(entityModel, null, '\t'), err => { if (err) { return reject(err); } else { return resolve(); } } ); }); } } savePosition() { const oldEntitiesPositionConfig = this.app.config.get(null, ConfigType.ENTITIES_POSITION); const newEntitiesPositionConfig = Object.assign({}, oldEntitiesPositionConfig, { [this.name]: { x: Math.round(this.x * 100) / 100, y: Math.round(this.y * 100) / 100 } }); this.app.config.set(newEntitiesPositionConfig, null, ConfigType.ENTITIES_POSITION); return this.app.config.save(); } /** Returns a list of the relations @returns {Array<Relation>} */ getRelations(): Array<IRelation> { return this.relations; } /** Returns all asociated entities @returns {Array<Relation>} */ getRelatedEntities(): Entity[] { const associatedEntity = {}; const entities = this.app.entities.entities; for (const name in entities) { if (entities[name]) { const entity = entities[name]; for (const entityRelation of entity.relations) { if (entityRelation.reference.entity === this.name) { associatedEntity[name] = entity; } } } } // To find associatedTable from belongsToMany relation for (const relation of this.relations) { if (relation.reference && relation.reference.entity) { associatedEntity[relation.reference.entity] = entities[relation.reference.entity]; } } // Object.values() const associatedEntityArray = []; for (const k in associatedEntity) { if (associatedEntity[k]) { associatedEntityArray.push(associatedEntity[k]); } } return associatedEntityArray; } /** Returns a relation determined by a field name @param {string} - Entity's field name @returns {Relation} - BelongsTo/HasMany/HasOne relationship */ getRelationByField(field: string): IRelation { for (const relation of this.relations) { if (relation.type === 'belongsTo') { if (field == relation.field) { return relation; } } else if (relation.type === 'hasMany' || relation.type === 'hasOne') { if (field === relation.reference.field) { return relation; } } } return null; } /** Returns a belongsToMany relation determined by a junction table entity name @param {string} - BelongsToMany junction table entity's name @returns {Relation} - BelongsToMany relationship */ getBelongsToManyRelation(entityThrough: string) { return this.relations.find(r => r.type === 'belongsToMany' && r.through === entityThrough); } /** Determines if a relation exists @param {Relation} - Relation to find in the relations array. @returns {integer} Index of the relation in the relations array, or -1 if non existant. */ getRelationIndex(relation: IRelation): number { let res = -1; this.relations.forEach((rel, i) => { if (res != -1) { return false; } if (relation && relation.field && relation.field == rel.field) { res = i; // type belongsTo } else if (relation && relation.as && relation.as == rel.as && relation.reference.entity == rel.reference.entity && relation.reference.as == rel.reference.as) { res = i; // type belongsToMany } else if (relation && relation.reference.field && relation.reference.entity == rel.reference.entity && relation.reference.field == rel.reference.field) { res = i; // type hasMany } }); return res; } getPK(): Array<Field> { return this.fields.filter(field => field.primary); } /** Add a relation to the entity @param {Relation} - Relation's description. @param {object} - Action's options @returns {Promise} */ addRelation(relation: IRelation, options?: IApplyOptions): Promise<any> { options = options || {}; if (relation.field && relation.reference.entity == relation.field) { return Promise.resolve(new MateriaError('The reference field cannot have the same name that its referenced entity')); } const entityDest = this.app.entities.get(relation.reference.entity); let p: Promise<any> = Promise.resolve(); if ( ! relation.type || relation.type == 'belongsTo') { relation.type = 'belongsTo'; if ( ! entityDest) { if (options.apply != false) { this.relations.push(relation); } return Promise.resolve(); // when loading entities } let keyReference = entityDest.getPK()[0]; if (relation.reference.field && relation.reference.field != keyReference.name) { const f = entityDest.getField(relation.reference.field); if ( ! f) { return Promise.reject( new MateriaError(`The relation's referenced field ${entityDest.name}.${relation.reference.field} does not exist`) ); } if ( ! f.unique) { return Promise.reject(new MateriaError(`${entityDest.name}.${f.name} cannot be referenced in relation (need to be unique/primary)`)); } keyReference = f; } if (options.apply != false) { this.relations.push(relation); } let uniqueField = false; if (relation.unique !== undefined) { uniqueField = relation.unique; } const newField: IField = { name: relation.field, type: keyReference.type, default: false, generateFrom: relation.reference.entity, required: true, read: true, write: true, primary: false, unique: uniqueField, isRelation: relation }; if (relation.reference.entity === this.name) { delete newField.generateFrom; } p = this.addField(newField, options); } else if (relation.type == 'hasMany' || relation.type == 'hasOne') { if (options.apply != false) { this.relations.push(relation); } } else if (relation.type == 'belongsToMany') { if (options.apply != false) { this.relations.push(relation); if ( ! entityDest) { return Promise.resolve(); // when loading entities } // TODO: Should be all PK of this and relation.reference.entity const field1 = this.getPK()[0]; const field2 = this.app.entities.get(relation.reference.entity).getPK()[0]; if ( ! relation.as) { relation.as = field1.name; } const isRelation = [{ field: relation.as, entity: this.name }, { field: relation.reference.as, entity: relation.reference.entity } ]; const implicitRelation = [ { type: 'belongsTo', reference: { entity: this.name, field: field1.name } }, { type: 'belongsTo', reference: { entity: relation.reference.entity, field: field2.name } } ]; const throughEntity = this.app.entities.get(relation.through); if (throughEntity) { const asField1 = throughEntity.getField(relation.as); const asField2 = throughEntity.getField(relation.reference.as); if (throughEntity.isRelation) { if (throughEntity.compareIsRelation(relation, this)) { return Promise.reject(new MateriaError('Table ' + relation.through + ' is already used for a different relation')); } p = Promise.resolve(); if ( ! asField1) { p = p.then(() => { return throughEntity.addField({ name: relation.as, type: field1.type, default: false, generateFrom: this.name, required: true, read: true, write: true, primary: true, unique: true, isRelation: implicitRelation[0] }, options); }); } else { asField1.isRelation = implicitRelation[0]; } if ( ! asField2) { p = p.then(() => { return throughEntity.addField({ name: relation.reference.as, type: field2.type, default: false, generateFrom: relation.reference.entity, required: true, read: true, write: true, primary: true, unique: true, isRelation: implicitRelation[1] }, options); }); } else { asField2.isRelation = implicitRelation[1]; } } else { if ( ! asField1 || ! asField2) { return Promise.reject(new MateriaError('Cannot use existing table ' + relation.through + ' for a many to many relation')); } throughEntity.isRelation = isRelation; if (asField1.isRelation) { asField1.isRelation.implicit = true; } else { if (asField1.name == relation.as) { asField1.references = isRelation[1]; asField1.isRelation = implicitRelation[0]; } else { asField1.references = isRelation[0]; asField1.isRelation = implicitRelation[1]; } p = p.then(() => { return throughEntity.updateField(asField1.name, asField1, options); }); } if (asField2.isRelation) { asField2.isRelation.implicit = true; } else { if (asField2.name == relation.as) { asField2.references = isRelation[1]; asField2.isRelation = implicitRelation[0]; } else { asField2.references = isRelation[0]; asField2.isRelation = implicitRelation[1]; } p = p.then(() => { return throughEntity.updateField(asField2.name, asField2, options); }); } p = p.then(() => { if (options.save) { return throughEntity.save(); } }); } } else { p = this.app.entities.add({ name: relation.through, overwritable: true, fields: [{ name: relation.as, type: field1.type, default: false, required: true, read: true, write: true, primary: true, unique: true, isRelation: implicitRelation[0] }, { name: relation.reference.as, type: field2.type, default: false, required: true, read: true, write: true, primary: true, unique: true, isRelation: implicitRelation[1] }], isRelation: isRelation }, options); } } } else { return Promise.reject(new Error('Unknown relation type.')); } if ( ! p) { p = Promise.resolve(); } return p.then((result) => { if (options.history != false) { this.app.history.push({ type: MigrationType.ADD_RELATION, table: this.name, value: relation }, { type: MigrationType.DELETE_RELATION, table: this.name, value: relation }); } if (options.apply != false) { this.generateDefaultQueries(); } if (options.save != false) { return this.save(); } }); } removeRelation(relation: IRelation, options?: IApplyOptions): Promise<any> { options = options || {}; const i = this.getRelationIndex(relation); if (i == -1 && options.apply != false) { return Promise.reject(new MateriaError('Could not find relation')); } let p = Promise.resolve(); if (options.apply != false) { const paired = relation.paired; relation = this.relations.splice(i, 1)[0]; if ( ! paired) { let inverseType; if (relation.type == 'belongsTo' || ! relation.type) { inverseType = 'hasMany'; } else { inverseType = relation.type; // only n-n for now } const inversedRelation = { type: inverseType, field: relation.reference.field, as: relation.reference.as, entity: relation.reference.entity, paired: true, reference: { field: relation.field, as: relation.as, entity: this.name } }; p = this.app.entities.get(relation.reference.entity).removeRelation(inversedRelation, options).catch((e) => { if (e.message != 'Could not find relation') { throw e; } }); } } if (relation.type == 'belongsToMany') { const entityThrough = this.app.entities.get(relation.through); if (entityThrough) { p = p.then(() => { const opts: IApplyOptions = Object.assign({}, options); opts.history = false; return this.app.entities.remove(relation.through, opts); }); } } else if ((relation.type == 'belongsTo' || ! relation.type) && !! this.fields.find(field => field.name == relation.field)) { p = p.then(() => { return this.removeField(relation.field, options); }); } return p.then(() => { this.generateDefaultQueries(); if (options.history != false) { this.app.history.push({ type: MigrationType.DELETE_RELATION, table: this.name, value: relation }, { type: MigrationType.ADD_RELATION, table: this.name, value: relation }); } if (options.save != false) { return this.save(); } }); } /** Get a field description by its name. @param {string} - Field's name. @returns {Field} */ getField(name: string): Field { return this.fields.find(field => field.name == name); } /** Return true if field exist @param {string} - Field's name @returns {Boolean} */ isField(name: string): boolean { return !! this.getField(name); } /** Get the entity's fields. @returns {Array<Field>} */ getFields(): Array<Field> { return this.fields; } /** Get the entity's writable fields. @returns {Array<Field>} */ getWritableFields(): Array<Field> { return this.fields.filter(field => field.write); } /** Get the entity's unique fields. @param {string|boolean} - unique group name, or true for independent uniques fields, or false for non unique fields. @returns {Array<Field>} */ getUniqueFields(group: string | boolean): Array<Field> { return this.fields.filter(field => field.unique == group); } /** Get the entity's readable fields. @returns {Array<Field>} */ getReadableFields(): Array<Field> { return this.fields.filter(field => field.read); } /** Update a field. @param {string} - Field's name to update @param {object} - New field description @param {object} - Action's options @returns {Promise<Field>} */ updateField(name: string, newfield: IFieldUpdate, options?): Promise<Field> { return new Promise((accept, reject) => { options = options || {}; if (! name) { return reject(); } let fieldobj; try { fieldobj = new Field(this, newfield); } catch (e) { return reject(e); } const done = () => { if (options.apply != false && fieldobj.name != name) { for (const relation of this.relations) { if (relation.field == name) { relation.field = fieldobj.name; } } } this.fields.forEach((field, k) => { if (field.name == name) { if (options.apply != false) { this.fields.splice(k, 1, fieldobj); } if (options.history != false) { this.app.history.push({ type: MigrationType.CHANGE_FIELD, table: this.name, name: field.name, value: fieldobj.toJson() }, { type: MigrationType.CHANGE_FIELD, table: this.name, name: fieldobj.name, value: field.toJson() }); } } }); let p = Promise.resolve(); if (options.save != false) { p = p.then(() => this.save()); } this.generateDefaultQueries(); return p; }; if (options.differ) { options.differ(done); accept(fieldobj); } else { done().then(() => accept(fieldobj)); } }); } /** Add a new field. @param {object} - New field description @param {integer} - Field position in list @param {object} - Action's options @returns {Promise<Field>} */ addFieldAt(field: IField, at: number, options?): Promise<Field> { options = options || {}; let fieldobj: Field; try { fieldobj = new Field(this, Object.assign({}, field, { read: true, write: field.autoIncrement ? false : true })); } catch (e) { return Promise.reject(e); } if (options.apply != false) { const oldfield = this.getField(field.name); if (oldfield) { if (field.isRelation) { oldfield.isRelation = field.isRelation; return Promise.resolve(oldfield); } if ( options.noErrors ) { return Promise.resolve(oldfield); } else { return Promise.reject(new MateriaError('A field of this name already exists')); } } this.fields.splice(at, 0, fieldobj); } if (options.history != false && ! field.isRelation) { this.app.history.push({ type: MigrationType.ADD_FIELD, table: this.name, value: fieldobj.toJson(), position: at }, { type: MigrationType.DELETE_FIELD, table: this.name, value: field.name }); } let p = Promise.resolve(); if (options.save != false) { p = p.then(() => this.save()); } if (options.generateQueries !== false) { this.generateDefaultQueries(); } return p.then(() => fieldobj); } /** Add a new field. Shortcut for addFieldAt(field, *fields count*, options) @param {object} - New field description @param {object} - Action's options @returns {Promise<Field>} */ addField(field: IField, options?): Promise<Field> { return this.addFieldAt(field, this.fields.length, options); } /** Add a new field. Shortcut for addFieldAt(field, 0, options) @param {object} - New field description @param {object} - Action's options @returns {Promise<Field>} */ addFieldFirst(field: IField, options?): Promise<Field> { return this.addFieldAt(field, 0, options); } /** Delete a field @param {string} - Field's name @param {object} - Action's options @returns {Promise} */ removeField(name: string, options?): Promise<void> { options = options || {}; if (! name) { return Promise.reject(new MateriaError('The name of the field is required')); } if (options.apply != false && ! this.getField(name)) { return Promise.reject(new MateriaError('This field does not exist')); } this.fields.forEach((field, k) => { if (field.name == name) { if (options.apply != false) { this.fields.splice(k, 1); } if (options.history != false) { this.app.history.push({ type: MigrationType.DELETE_FIELD, table: this.name, value: field.name }, { type: MigrationType.ADD_FIELD, table: this.name, value: field.toJson(), position: k }); } } }); this.generateDefaultQueries(); if (options.save != false) { return this.save(); } return Promise.resolve(); } /** Return the entity's description @returns {object} */ toJson(): IEntityConfig { const fieldsJson = []; if (this.fields) { for (const field of this.fields) { if ( ! field.isRelation || ! field.isDefaultRelationField()) { fieldsJson.push(field.toJson()); } } } const relJson = []; if (this.relations) { this.relations.forEach(relation => { if ( ! relation.implicit) { const relCopy = {} as any; for (const k in relation) { if (k != 'entity' && k != '$$hashKey') { relCopy[k] = relation[k]; } } if ( ! relCopy.type) { relCopy.type = 'belongsTo'; } relJson.push(relCopy); } }); } const queriesJson = []; if (this.queries) { this.queries.forEach(query => { queriesJson.push(query.toJson()); }); } const res: IEntityConfig = { id: this.id, x: this.x, y: this.y, fields: [], relations: [], queries: [] }; if (fieldsJson.length) { res.fields = fieldsJson; } if (this.isRelation) { res.isRelation = this.isRelation; } if (relJson.length) { res.relations = relJson; } if (queriesJson.length) { res.queries = queriesJson; } return res; } addDefaultQuery(id: string, type: string, params, opts) { return this.addQuery({ id: id, type: type, opts: opts }, {history: false, save: false}); } /** Add a query to the entity @param {string} - Query's name @param {object} - Query's data @param {object} - Action's options */ addQuery(query: IQuery, options?: IApplyOptions): Promise<Query> { options = options || {}; if ( ! this.queryObjects[query.type]) { return Promise.reject(new MateriaError('Query type `' + query.type + '` not defined')); } const QueryClass = this.queryObjects[query.type]; const queryobj: Query = new QueryClass(this, query.id, query.opts); if (options.apply != false) { // check that query with `id` = id does not exist. if it exists, remove the query const index = this.queries.indexOf(this.queries.find(q => q.id == query.id)); if (index != -1) { this.queries.splice(index, 1); } this.queries.push(queryobj); } if (options.history != false) { this.app.history.push({ type: MigrationType.ADD_QUERY, table: this.name, id: query.id, value: queryobj.toJson() }, { type: MigrationType.DELETE_QUERY, table: this.name, id: query.id }); } if (options.save != false) { return this.save().then(() => queryobj); } else { return Promise.resolve(queryobj); } } getNewQuery(id: string, type: string, opts): IQueryConstructor { if ( ! this.queryObjects[type]) { throw new MateriaError('Query type `' + type + '` not defined'); } const QueryClass = this.queryObjects[type]; const queryobj = <IQueryConstructor> new QueryClass(this, id, opts); return queryobj; } /** Delete a query @param {string} - Query's name @param {object} - Action's options */ removeQuery(id: string, options?: IApplyOptions): Promise<void> { options = options || {}; const queryobj = this.getQuery(id); if ( ! queryobj) { return Promise.reject(new MateriaError('Could not find query `' + id + '`')); } if (options.apply != false) { const index = this.queries.indexOf(this.queries.find(query => query.id == id)); if (index != -1) { this.queries.splice(index, 1); } } if (options.history != false) { this.app.history.push({ type: MigrationType.DELETE_QUERY, table: this.name, id: id }, { type: MigrationType.ADD_QUERY, table: this.name, id: id, value: queryobj.toJson() }); } if (options.save != false) { return this.save(); } else { return Promise.resolve(); } } /** Get a query object @param {string} - Query's name @returns {Query} */ getQuery(id): Query { for (const query of this.queries) { if (query.id == id) { return query; } } return null; } refreshQueries() { for (const query of this.queries) { try { query.refresh(); query.discoverParams(); } catch (e) { this.app.logger.error(e); } } } /** Get the entity's queries @returns {Array<Query>} */ getQueries() { return this.queries; } compareIsRelation(relation, entity): boolean { if ( ! this.isRelation) { return true; } if (this.isRelation[0].field == relation.as) { if (this.isRelation[0].entity == entity.name && this.isRelation[1].field == relation.reference.as && this.isRelation[1].entity == relation.reference.entity) { return false; } } else if (this.isRelation[1].field == relation.as) { if (this.isRelation[1].entity == entity.name && this.isRelation[0].field == relation.reference.as && this.isRelation[0].entity == relation.reference.entity) { return false; } } return true; } defineQueryObjects(data) { this.queryObjects = data; } getQueryTypes() { return Object.keys(this.queryObjects); } abstract loadModel(): Promise<any>; loadRelationsInModel() { } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * An HttpsHealthCheck resource. This resource defines a template for how * individual VMs should be checked for health, via HTTPS. * * > **Note:** gcp.compute.HttpsHealthCheck is a legacy health check. * The newer [gcp.compute.HealthCheck](https://www.terraform.io/docs/providers/google/r/compute_health_check.html) * should be preferred for all uses except * [Network Load Balancers](https://cloud.google.com/compute/docs/load-balancing/network/) * which still require the legacy version. * * To get more information about HttpsHealthCheck, see: * * * [API documentation](https://cloud.google.com/compute/docs/reference/v1/httpsHealthChecks) * * How-to Guides * * [Adding Health Checks](https://cloud.google.com/compute/docs/load-balancing/health-checks#legacy_health_checks) * * ## Example Usage * ### Https Health Check Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const defaultHttpsHealthCheck = new gcp.compute.HttpsHealthCheck("default", { * checkIntervalSec: 1, * requestPath: "/health_check", * timeoutSec: 1, * }); * ``` * * ## Import * * HttpsHealthCheck can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:compute/httpsHealthCheck:HttpsHealthCheck default projects/{{project}}/global/httpsHealthChecks/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/httpsHealthCheck:HttpsHealthCheck default {{project}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/httpsHealthCheck:HttpsHealthCheck default {{name}} * ``` */ export class HttpsHealthCheck extends pulumi.CustomResource { /** * Get an existing HttpsHealthCheck 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?: HttpsHealthCheckState, opts?: pulumi.CustomResourceOptions): HttpsHealthCheck { return new HttpsHealthCheck(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:compute/httpsHealthCheck:HttpsHealthCheck'; /** * Returns true if the given object is an instance of HttpsHealthCheck. 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 HttpsHealthCheck { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === HttpsHealthCheck.__pulumiType; } /** * How often (in seconds) to send a health check. The default value is 5 * seconds. */ public readonly checkIntervalSec!: pulumi.Output<number | undefined>; /** * Creation timestamp in RFC3339 text format. */ public /*out*/ readonly creationTimestamp!: pulumi.Output<string>; /** * An optional description of this resource. Provide this property when * you create the resource. */ public readonly description!: pulumi.Output<string | undefined>; /** * A so-far unhealthy instance will be marked healthy after this many * consecutive successes. The default value is 2. */ public readonly healthyThreshold!: pulumi.Output<number | undefined>; /** * The value of the host header in the HTTPS health check request. If * left empty (default value), the public IP on behalf of which this * health check is performed will be used. */ public readonly host!: pulumi.Output<string | undefined>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and * match the regular expression `a-z?` which means * the first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the * last character, which cannot be a dash. */ public readonly name!: pulumi.Output<string>; /** * The TCP port number for the HTTPS health check request. * The default value is 443. */ public readonly port!: pulumi.Output<number | 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 request path of the HTTPS health check request. * The default value is /. */ public readonly requestPath!: pulumi.Output<string | undefined>; /** * The URI of the created resource. */ public /*out*/ readonly selfLink!: pulumi.Output<string>; /** * How long (in seconds) to wait before claiming failure. * The default value is 5 seconds. It is invalid for timeoutSec to have * greater value than checkIntervalSec. */ public readonly timeoutSec!: pulumi.Output<number | undefined>; /** * A so-far healthy instance will be marked unhealthy after this many * consecutive failures. The default value is 2. */ public readonly unhealthyThreshold!: pulumi.Output<number | undefined>; /** * Create a HttpsHealthCheck 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?: HttpsHealthCheckArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: HttpsHealthCheckArgs | HttpsHealthCheckState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as HttpsHealthCheckState | undefined; inputs["checkIntervalSec"] = state ? state.checkIntervalSec : undefined; inputs["creationTimestamp"] = state ? state.creationTimestamp : undefined; inputs["description"] = state ? state.description : undefined; inputs["healthyThreshold"] = state ? state.healthyThreshold : undefined; inputs["host"] = state ? state.host : undefined; inputs["name"] = state ? state.name : undefined; inputs["port"] = state ? state.port : undefined; inputs["project"] = state ? state.project : undefined; inputs["requestPath"] = state ? state.requestPath : undefined; inputs["selfLink"] = state ? state.selfLink : undefined; inputs["timeoutSec"] = state ? state.timeoutSec : undefined; inputs["unhealthyThreshold"] = state ? state.unhealthyThreshold : undefined; } else { const args = argsOrState as HttpsHealthCheckArgs | undefined; inputs["checkIntervalSec"] = args ? args.checkIntervalSec : undefined; inputs["description"] = args ? args.description : undefined; inputs["healthyThreshold"] = args ? args.healthyThreshold : undefined; inputs["host"] = args ? args.host : undefined; inputs["name"] = args ? args.name : undefined; inputs["port"] = args ? args.port : undefined; inputs["project"] = args ? args.project : undefined; inputs["requestPath"] = args ? args.requestPath : undefined; inputs["timeoutSec"] = args ? args.timeoutSec : undefined; inputs["unhealthyThreshold"] = args ? args.unhealthyThreshold : undefined; inputs["creationTimestamp"] = undefined /*out*/; inputs["selfLink"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(HttpsHealthCheck.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering HttpsHealthCheck resources. */ export interface HttpsHealthCheckState { /** * How often (in seconds) to send a health check. The default value is 5 * seconds. */ checkIntervalSec?: pulumi.Input<number>; /** * Creation timestamp in RFC3339 text format. */ creationTimestamp?: pulumi.Input<string>; /** * An optional description of this resource. Provide this property when * you create the resource. */ description?: pulumi.Input<string>; /** * A so-far unhealthy instance will be marked healthy after this many * consecutive successes. The default value is 2. */ healthyThreshold?: pulumi.Input<number>; /** * The value of the host header in the HTTPS health check request. If * left empty (default value), the public IP on behalf of which this * health check is performed will be used. */ host?: pulumi.Input<string>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and * match the regular expression `a-z?` which means * the first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the * last character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The TCP port number for the HTTPS health check request. * The default value is 443. */ port?: pulumi.Input<number>; /** * 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 request path of the HTTPS health check request. * The default value is /. */ requestPath?: pulumi.Input<string>; /** * The URI of the created resource. */ selfLink?: pulumi.Input<string>; /** * How long (in seconds) to wait before claiming failure. * The default value is 5 seconds. It is invalid for timeoutSec to have * greater value than checkIntervalSec. */ timeoutSec?: pulumi.Input<number>; /** * A so-far healthy instance will be marked unhealthy after this many * consecutive failures. The default value is 2. */ unhealthyThreshold?: pulumi.Input<number>; } /** * The set of arguments for constructing a HttpsHealthCheck resource. */ export interface HttpsHealthCheckArgs { /** * How often (in seconds) to send a health check. The default value is 5 * seconds. */ checkIntervalSec?: pulumi.Input<number>; /** * An optional description of this resource. Provide this property when * you create the resource. */ description?: pulumi.Input<string>; /** * A so-far unhealthy instance will be marked healthy after this many * consecutive successes. The default value is 2. */ healthyThreshold?: pulumi.Input<number>; /** * The value of the host header in the HTTPS health check request. If * left empty (default value), the public IP on behalf of which this * health check is performed will be used. */ host?: pulumi.Input<string>; /** * Name of the resource. Provided by the client when the resource is * created. The name must be 1-63 characters long, and comply with * RFC1035. Specifically, the name must be 1-63 characters long and * match the regular expression `a-z?` which means * the first character must be a lowercase letter, and all following * characters must be a dash, lowercase letter, or digit, except the * last character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The TCP port number for the HTTPS health check request. * The default value is 443. */ port?: pulumi.Input<number>; /** * 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 request path of the HTTPS health check request. * The default value is /. */ requestPath?: pulumi.Input<string>; /** * How long (in seconds) to wait before claiming failure. * The default value is 5 seconds. It is invalid for timeoutSec to have * greater value than checkIntervalSec. */ timeoutSec?: pulumi.Input<number>; /** * A so-far healthy instance will be marked unhealthy after this many * consecutive failures. The default value is 2. */ unhealthyThreshold?: pulumi.Input<number>; }
the_stack
import { DiffSelection, DiffSelectionType } from './diff' /** * The status entry code as reported by Git. */ export enum GitStatusEntry { Modified = 'M', Added = 'A', Deleted = 'D', Renamed = 'R', Copied = 'C', Unchanged = '.', Untracked = '?', Ignored = '!', UpdatedButUnmerged = 'U', } /** The enum representation of a Git file change in GitHub Desktop. */ export enum AppFileStatusKind { New = 'New', Modified = 'Modified', Deleted = 'Deleted', Copied = 'Copied', Renamed = 'Renamed', Conflicted = 'Conflicted', Untracked = 'Untracked', } /** * Normal changes to a repository detected by GitHub Desktop */ export type PlainFileStatus = { kind: | AppFileStatusKind.New | AppFileStatusKind.Modified | AppFileStatusKind.Deleted } /** * Copied or renamed files are change staged in the index that have a source * as well as a destination. * * The `oldPath` of a copied file also exists in the working directory, but the * `oldPath` of a renamed file will be missing from the working directory. */ export type CopiedOrRenamedFileStatus = { kind: AppFileStatusKind.Copied | AppFileStatusKind.Renamed oldPath: string } /** * Details about a file marked as conflicted in the index which may have * conflict markers to inspect. */ export type ConflictsWithMarkers = { kind: AppFileStatusKind.Conflicted entry: TextConflictEntry conflictMarkerCount: number } /** * Details about a file marked as conflicted in the index which needs to be * resolved manually by the user. */ export type ManualConflict = { kind: AppFileStatusKind.Conflicted entry: ManualConflictEntry } /** Union of potential conflict scenarios the application should handle */ export type ConflictedFileStatus = ConflictsWithMarkers | ManualConflict /** Custom typeguard to differentiate Conflict files from other types */ export function isConflictedFileStatus( appFileStatus: AppFileStatus ): appFileStatus is ConflictedFileStatus { return appFileStatus.kind === AppFileStatusKind.Conflicted } /** Custom typeguard to differentiate ConflictsWithMarkers from other Conflict types */ export function isConflictWithMarkers( conflictedFileStatus: ConflictedFileStatus ): conflictedFileStatus is ConflictsWithMarkers { return conflictedFileStatus.hasOwnProperty('conflictMarkerCount') } /** Custom typeguard to differentiate ManualConflict from other Conflict types */ export function isManualConflict( conflictedFileStatus: ConflictedFileStatus ): conflictedFileStatus is ManualConflict { return !conflictedFileStatus.hasOwnProperty('conflictMarkerCount') } /** Denotes an untracked file in the working directory) */ export type UntrackedFileStatus = { kind: AppFileStatusKind.Untracked } /** The union of potential states associated with a file change in Desktop */ export type AppFileStatus = | PlainFileStatus | CopiedOrRenamedFileStatus | ConflictedFileStatus | UntrackedFileStatus /** The porcelain status for an ordinary changed entry */ type OrdinaryEntry = { readonly kind: 'ordinary' /** how we should represent the file in the application */ readonly type: 'added' | 'modified' | 'deleted' /** the status of the index for this entry (if known) */ readonly index?: GitStatusEntry /** the status of the working tree for this entry (if known) */ readonly workingTree?: GitStatusEntry } /** The porcelain status for a renamed or copied entry */ type RenamedOrCopiedEntry = { readonly kind: 'renamed' | 'copied' /** the status of the index for this entry (if known) */ readonly index?: GitStatusEntry /** the status of the working tree for this entry (if known) */ readonly workingTree?: GitStatusEntry } export enum UnmergedEntrySummary { AddedByUs = 'added-by-us', DeletedByUs = 'deleted-by-us', AddedByThem = 'added-by-them', DeletedByThem = 'deleted-by-them', BothDeleted = 'both-deleted', BothAdded = 'both-added', BothModified = 'both-modified', } /** * Valid Git index states that the application should detect text conflict * markers */ type TextConflictDetails = | { readonly action: UnmergedEntrySummary.BothAdded readonly us: GitStatusEntry.Added readonly them: GitStatusEntry.Added } | { readonly action: UnmergedEntrySummary.BothModified readonly us: GitStatusEntry.UpdatedButUnmerged readonly them: GitStatusEntry.UpdatedButUnmerged } type TextConflictEntry = { readonly kind: 'conflicted' } & TextConflictDetails /** * Valid Git index states where the user needs to choose one of `us` or `them` * in the app. */ type ManualConflictDetails = | { readonly action: UnmergedEntrySummary.BothAdded readonly us: GitStatusEntry.Added readonly them: GitStatusEntry.Added } | { readonly action: UnmergedEntrySummary.BothModified readonly us: GitStatusEntry.UpdatedButUnmerged readonly them: GitStatusEntry.UpdatedButUnmerged } | { readonly action: UnmergedEntrySummary.AddedByUs readonly us: GitStatusEntry.Added readonly them: GitStatusEntry.UpdatedButUnmerged } | { readonly action: UnmergedEntrySummary.DeletedByThem readonly us: GitStatusEntry.UpdatedButUnmerged readonly them: GitStatusEntry.Deleted } | { readonly action: UnmergedEntrySummary.AddedByThem readonly us: GitStatusEntry.UpdatedButUnmerged readonly them: GitStatusEntry.Added } | { readonly action: UnmergedEntrySummary.DeletedByUs readonly us: GitStatusEntry.Deleted readonly them: GitStatusEntry.UpdatedButUnmerged } | { readonly action: UnmergedEntrySummary.BothDeleted readonly us: GitStatusEntry.Deleted readonly them: GitStatusEntry.Deleted } type ManualConflictEntry = { readonly kind: 'conflicted' } & ManualConflictDetails /** The porcelain status for an unmerged entry */ export type UnmergedEntry = TextConflictEntry | ManualConflictEntry /** The porcelain status for an unmerged entry */ type UntrackedEntry = { readonly kind: 'untracked' } /** The union of possible entries from the git status */ export type FileEntry = | OrdinaryEntry | RenamedOrCopiedEntry | UnmergedEntry | UntrackedEntry /** encapsulate changes to a file associated with a commit */ export class FileChange { /** An ID for the file change. */ public readonly id: string /** * @param path The relative path to the file in the repository. * @param status The status of the change to the file. */ public constructor( public readonly path: string, public readonly status: AppFileStatus ) { if ( status.kind === AppFileStatusKind.Renamed || status.kind === AppFileStatusKind.Copied ) { this.id = `${status.kind}+${path}+${status.oldPath}` } else { this.id = `${status.kind}+${path}` } } } /** encapsulate the changes to a file in the working directory */ export class WorkingDirectoryFileChange extends FileChange { /** * @param path The relative path to the file in the repository. * @param status The status of the change to the file. * @param selection Contains the selection details for this file - all, nothing or partial. * @param oldPath The original path in the case of a renamed file. */ public constructor( path: string, status: AppFileStatus, public readonly selection: DiffSelection ) { super(path, status) } /** Create a new WorkingDirectoryFileChange with the given includedness. */ public withIncludeAll(include: boolean): WorkingDirectoryFileChange { const newSelection = include ? this.selection.withSelectAll() : this.selection.withSelectNone() return this.withSelection(newSelection) } /** Create a new WorkingDirectoryFileChange with the given diff selection. */ public withSelection(selection: DiffSelection): WorkingDirectoryFileChange { return new WorkingDirectoryFileChange(this.path, this.status, selection) } } /** * An object encapsulating the changes to a committed file. * * @param status A commit SHA or some other identifier that ultimately * dereferences to a commit. This is the pointer to the * 'after' version of this change. I.e. the parent of this * commit will contain the 'before' (or nothing, if the * file change represents a new file). */ export class CommittedFileChange extends FileChange { public constructor( path: string, status: AppFileStatus, public readonly commitish: string ) { super(path, status) this.commitish = commitish } } /** the state of the working directory for a repository */ export class WorkingDirectoryStatus { /** Create a new status with the given files. */ public static fromFiles( files: ReadonlyArray<WorkingDirectoryFileChange> ): WorkingDirectoryStatus { return new WorkingDirectoryStatus(files, getIncludeAllState(files)) } private readonly fileIxById = new Map<string, number>() /** * @param files The list of changes in the repository's working directory. * @param includeAll Update the include checkbox state of the form. * NOTE: we need to track this separately to the file list selection * and perform two-way binding manually when this changes. */ private constructor( public readonly files: ReadonlyArray<WorkingDirectoryFileChange>, public readonly includeAll: boolean | null = true ) { files.forEach((f, ix) => this.fileIxById.set(f.id, ix)) } /** * Update the include state of all files in the working directory */ public withIncludeAllFiles(includeAll: boolean): WorkingDirectoryStatus { const newFiles = this.files.map(f => f.withIncludeAll(includeAll)) return new WorkingDirectoryStatus(newFiles, includeAll) } /** Find the file with the given ID. */ public findFileWithID(id: string): WorkingDirectoryFileChange | null { const ix = this.fileIxById.get(id) return ix !== undefined ? this.files[ix] || null : null } /** Find the index of the file with the given ID. Returns -1 if not found */ public findFileIndexByID(id: string): number { const ix = this.fileIxById.get(id) return ix !== undefined ? ix : -1 } } function getIncludeAllState( files: ReadonlyArray<WorkingDirectoryFileChange> ): boolean | null { if (!files.length) { return true } const allSelected = files.every( f => f.selection.getSelectionType() === DiffSelectionType.All ) const noneSelected = files.every( f => f.selection.getSelectionType() === DiffSelectionType.None ) let includeAll: boolean | null = null if (allSelected) { includeAll = true } else if (noneSelected) { includeAll = false } return includeAll }
the_stack
import azureCore = require("@azure/core-http"); import CorrelationIdManager = require("./CorrelationIdManager"); import ConnectionStringParser = require("./ConnectionStringParser"); import Logging = require("./Logging"); import Constants = require("../Declarations/Constants"); import http = require("http"); import https = require("https"); import url = require("url"); import { JsonConfig } from "./JsonConfig"; import { IConfig } from "../Declarations/Interfaces"; import { DistributedTracingModes } from "../applicationinsights"; import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance"; class Config implements IConfig { public static ENV_azurePrefix = "APPSETTING_"; // Azure adds this prefix to all environment variables public static ENV_iKey = "APPINSIGHTS_INSTRUMENTATIONKEY"; // This key is provided in the readme public static legacy_ENV_iKey = "APPINSIGHTS_INSTRUMENTATION_KEY"; public static ENV_profileQueryEndpoint = "APPINSIGHTS_PROFILE_QUERY_ENDPOINT"; public static ENV_quickPulseHost = "APPINSIGHTS_QUICKPULSE_HOST"; // IConfig properties public endpointUrl: string; public maxBatchSize: number; public maxBatchIntervalMs: number; public disableAppInsights: boolean; public samplingPercentage: number; public correlationIdRetryIntervalMs: number; public correlationHeaderExcludedDomains: string[]; public proxyHttpUrl: string; public proxyHttpsUrl: string; public httpAgent: http.Agent; public httpsAgent: https.Agent; public ignoreLegacyHeaders: boolean; public aadTokenCredential?: azureCore.TokenCredential; public enableAutoCollectConsole: boolean; public enableAutoCollectExceptions: boolean; public enableAutoCollectPerformance: boolean; public enableAutoCollectExternalLoggers: boolean; public enableAutoCollectPreAggregatedMetrics: boolean; public enableAutoCollectHeartbeat: boolean; public enableAutoCollectRequests: boolean; public enableAutoCollectDependencies: boolean; public enableAutoDependencyCorrelation: boolean; public enableSendLiveMetrics: boolean; public enableUseDiskRetryCaching: boolean; public enableUseAsyncHooks: boolean; public distributedTracingMode: DistributedTracingModes; public enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics; public enableResendInterval: number; public enableMaxBytesOnDisk: number; public enableInternalDebugLogging: boolean; public enableInternalWarningLogging: boolean; public disableAllExtendedMetrics: boolean; public disableStatsbeat: boolean; public extendedMetricDisablers: string; public quickPulseHost: string; public enableAutoWebSnippetInjection: boolean; public correlationId: string; // TODO: Should be private private _connectionString: string; private _endpointBase: string = Constants.DEFAULT_BREEZE_ENDPOINT; private _setCorrelationId: (v: string) => void; private _profileQueryEndpoint: string; private _instrumentationKey: string; private _webSnippetConnectionString: string; constructor(setupString?: string) { // Load config values from env variables and JSON if available this._mergeConfig(); const connectionStringEnv: string | undefined = this._connectionString; const csCode = ConnectionStringParser.parse(setupString); const csEnv = ConnectionStringParser.parse(connectionStringEnv); const iKeyCode = !csCode.instrumentationkey && Object.keys(csCode).length > 0 ? null // CS was valid but instrumentation key was not provided, null and grab from env var : setupString; // CS was invalid, so it must be an ikey const instrumentationKeyEnv: string | undefined = this._instrumentationKey; this.instrumentationKey = csCode.instrumentationkey || iKeyCode /* === instrumentationKey */ || csEnv.instrumentationkey || instrumentationKeyEnv; if (!this.instrumentationKey || this.instrumentationKey == "") { throw new Error("Instrumentation key not found, please provide a connection string before starting the server"); } let endpoint = `${this.endpointUrl || csCode.ingestionendpoint || csEnv.ingestionendpoint || this._endpointBase}`; if (endpoint.endsWith("/")) { // Remove extra '/' if present endpoint = endpoint.slice(0, -1); } this.endpointUrl = `${endpoint}/v2.1/track`; this.maxBatchSize = this.maxBatchSize || 250; this.maxBatchIntervalMs = this.maxBatchIntervalMs || 15000; this.disableAppInsights = this.disableAppInsights || false; this.samplingPercentage = this.samplingPercentage || 100; this.correlationIdRetryIntervalMs = this.correlationIdRetryIntervalMs || 30 * 1000; this.enableAutoWebSnippetInjection = this.enableAutoWebSnippetInjection || false; this.correlationHeaderExcludedDomains = this.correlationHeaderExcludedDomains || [ "*.core.windows.net", "*.core.chinacloudapi.cn", "*.core.cloudapi.de", "*.core.usgovcloudapi.net", "*.core.microsoft.scloud", "*.core.eaglex.ic.gov" ]; this._setCorrelationId = (correlationId) => this.correlationId = correlationId; this.ignoreLegacyHeaders = this.ignoreLegacyHeaders || false; this.profileQueryEndpoint = csCode.ingestionendpoint || csEnv.ingestionendpoint || process.env[Config.ENV_profileQueryEndpoint] || this._endpointBase; this.quickPulseHost = this.quickPulseHost || csCode.liveendpoint || csEnv.liveendpoint || process.env[Config.ENV_quickPulseHost] || Constants.DEFAULT_LIVEMETRICS_HOST; this.webSnippetConnectionString = this.webSnippetConnectionString || this._webSnippetConnectionString || ""; // Parse quickPulseHost if it starts with http(s):// if (this.quickPulseHost.match(/^https?:\/\//)) { this.quickPulseHost = new url.URL(this.quickPulseHost).host; } } public set profileQueryEndpoint(endpoint: string) { CorrelationIdManager.cancelCorrelationIdQuery(this, this._setCorrelationId); this._profileQueryEndpoint = endpoint; this.correlationId = CorrelationIdManager.correlationIdPrefix; // Reset the correlationId while we wait for the new query CorrelationIdManager.queryCorrelationId(this, this._setCorrelationId); } public get profileQueryEndpoint() { return this._profileQueryEndpoint; } public set instrumentationKey(iKey: string) { if (!Config._validateInstrumentationKey(iKey)) { Logging.warn("An invalid instrumentation key was provided. There may be resulting telemetry loss", this.instrumentationKey); } this._instrumentationKey = iKey; } public get instrumentationKey(): string { return this._instrumentationKey; } public set webSnippetConnectionString(connectionString: string) { this._webSnippetConnectionString = connectionString; } public get webSnippetConnectionString(): string { return this._webSnippetConnectionString; } private _mergeConfig() { let jsonConfig = JsonConfig.getInstance(); this._connectionString = jsonConfig.connectionString; this._instrumentationKey = jsonConfig.instrumentationKey; this.correlationHeaderExcludedDomains = jsonConfig.correlationHeaderExcludedDomains; this.correlationIdRetryIntervalMs = jsonConfig.correlationIdRetryIntervalMs; this.disableAllExtendedMetrics = jsonConfig.disableAllExtendedMetrics; this.disableAppInsights = jsonConfig.disableAppInsights; this.disableStatsbeat = jsonConfig.disableStatsbeat; this.distributedTracingMode = jsonConfig.distributedTracingMode; this.enableAutoCollectConsole = jsonConfig.enableAutoCollectConsole; this.enableAutoCollectDependencies = jsonConfig.enableAutoCollectDependencies; this.enableAutoCollectExceptions = jsonConfig.enableAutoCollectExceptions; this.enableAutoCollectExtendedMetrics = jsonConfig.enableAutoCollectExtendedMetrics; this.enableAutoCollectExternalLoggers = jsonConfig.enableAutoCollectExternalLoggers; this.enableAutoCollectHeartbeat = jsonConfig.enableAutoCollectHeartbeat; this.enableAutoCollectPerformance = jsonConfig.enableAutoCollectPerformance; this.enableAutoCollectPreAggregatedMetrics = jsonConfig.enableAutoCollectPreAggregatedMetrics; this.enableAutoCollectRequests = jsonConfig.enableAutoCollectRequests; this.enableAutoDependencyCorrelation = jsonConfig.enableAutoDependencyCorrelation; this.enableInternalDebugLogging = jsonConfig.enableInternalDebugLogging; this.enableInternalWarningLogging = jsonConfig.enableInternalWarningLogging; this.enableResendInterval = jsonConfig.enableResendInterval; this.enableMaxBytesOnDisk = jsonConfig.enableMaxBytesOnDisk; this.enableSendLiveMetrics = jsonConfig.enableSendLiveMetrics; this.enableUseAsyncHooks = jsonConfig.enableUseAsyncHooks; this.enableUseDiskRetryCaching = jsonConfig.enableUseDiskRetryCaching; this.endpointUrl = jsonConfig.endpointUrl; this.extendedMetricDisablers = jsonConfig.extendedMetricDisablers; this.ignoreLegacyHeaders = jsonConfig.ignoreLegacyHeaders; this.maxBatchIntervalMs = jsonConfig.maxBatchIntervalMs; this.maxBatchSize = jsonConfig.maxBatchSize; this.proxyHttpUrl = jsonConfig.proxyHttpUrl; this.proxyHttpsUrl = jsonConfig.proxyHttpsUrl; this.quickPulseHost = jsonConfig.quickPulseHost; this.samplingPercentage = jsonConfig.samplingPercentage; this.enableAutoWebSnippetInjection = jsonConfig.enableAutoWebSnippetInjection; this.webSnippetConnectionString = jsonConfig.webSnippetConnectionString; } /** * Validate UUID Format * Specs taken from breeze repo * The definition of a VALID instrumentation key is as follows: * Not none * Not empty * Every character is a hex character [0-9a-f] * 32 characters are separated into 5 sections via 4 dashes * First section has 8 characters * Second section has 4 characters * Third section has 4 characters * Fourth section has 4 characters * Fifth section has 12 characters */ private static _validateInstrumentationKey(iKey: string): boolean { const UUID_Regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; const regexp = new RegExp(UUID_Regex); return regexp.test(iKey); } } export = Config;
the_stack
import { getFromId, InvalidTypeError, parseAndValidate, parseParameter } from '#lib/customCommands'; import { CustomCommand, GuildSettings, readSettings, writeSettings } from '#lib/database'; import { LanguageKeys } from '#lib/i18n/languageKeys'; import { SkyraCommand, SkyraPaginatedMessage } from '#lib/structures'; import type { GuildMessage } from '#lib/types'; import { PermissionLevels } from '#lib/types/Enums'; import { parse as parseColour } from '#utils/Color'; import { RequiresLevel } from '#utils/decorators'; import { sendLoadingMessage } from '#utils/util'; import { ApplyOptions, RequiresClientPermissions } from '@sapphire/decorators'; import { CommandOptionsRunTypeEnum } from '@sapphire/framework'; import { send } from '@sapphire/plugin-editable-commands'; import { chunk, codeBlock, cutText } from '@sapphire/utilities'; import { Identifiers, ParserUnexpectedTokenError, PartType, UserError } from '@skyra/tags'; import { PermissionFlagsBits } from 'discord-api-types/v9'; import { MessageEmbed, MessageOptions } from 'discord.js'; @ApplyOptions<SkyraCommand.Options>({ aliases: ['tags', 'custom-command', 'copy-pasta'], description: LanguageKeys.Commands.Tags.TagDescription, detailedDescription: LanguageKeys.Commands.Tags.TagExtended, flags: ['embed'], options: ['color', 'colour'], requiredClientPermissions: [PermissionFlagsBits.ManageMessages], runIn: [CommandOptionsRunTypeEnum.GuildAny], subCommands: ['add', 'alias', 'remove', 'edit', 'rename', 'source', 'list', 'reset', { input: 'show', default: true }] }) export class UserCommand extends SkyraCommand { // Based on HEX regex from #utils/Color // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility #kHexLessRegex = /^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/i; @RequiresLevel(PermissionLevels.Moderator, LanguageKeys.Commands.Tags.TagPermissionLevel) public async add(message: GuildMessage, args: SkyraCommand.Args) { const id = (await args.pick('string')).toLowerCase(); const commandContent = await args.rest('string'); await writeSettings(message.guild, (settings) => { const tags = settings[GuildSettings.CustomCommands]; if (tags.some((command) => command.id === id)) this.error(LanguageKeys.Commands.Tags.TagExists, { tag: id }); tags.push(this.createTag(args, id, commandContent)); }); const content = args.t(LanguageKeys.Commands.Tags.TagAdded, { name: id, content: cutText(commandContent, 500) }); return send(message, { content, allowedMentions: { users: [], roles: [] } }); } @RequiresLevel(PermissionLevels.Moderator, LanguageKeys.Commands.Tags.TagPermissionLevel) public async remove(message: GuildMessage, args: SkyraCommand.Args) { const id = (await args.pick('string')).toLowerCase(); await writeSettings(message.guild, (settings) => { const tags = settings[GuildSettings.CustomCommands]; const tagIndex = tags.findIndex((command) => command.id === id); if (tagIndex === -1) this.error(LanguageKeys.Commands.Tags.TagNotExists, { tag: id }); settings[GuildSettings.CustomCommands].splice(tagIndex, 1); }); const content = args.t(LanguageKeys.Commands.Tags.TagRemoved, { name: id }); return send(message, { content, allowedMentions: { users: [], roles: [] } }); } @RequiresLevel(PermissionLevels.Moderator, LanguageKeys.Commands.Tags.TagPermissionLevel) public async alias(message: GuildMessage, args: SkyraCommand.Args) { const input = (await args.pick('string')).toLowerCase(); let output = (await args.pick('string')).toLowerCase(); await writeSettings(message.guild, (settings) => { const tags = settings[GuildSettings.CustomCommands]; // Get destination tag: const destinationTag = getFromId(output, tags); if (destinationTag === null) this.error(LanguageKeys.Commands.Tags.TagNotExists, { tag: output }); output = destinationTag.id; // Get source tag, if any exists: const sourceTag = getFromId(input, tags); if (sourceTag === null) { destinationTag.aliases.push(input); return; } // If the input is a tag source, it cannot be aliased: if (sourceTag.id === input) { this.error(LanguageKeys.Commands.Tags.TagCannotAlias, { tag: sourceTag.id }); } // Remove previous alias: const index = sourceTag.aliases.indexOf(input); if (index !== -1) sourceTag.aliases.splice(index, 1); // Add new alias: destinationTag.aliases.push(input); }); const content = args.t(LanguageKeys.Commands.Tags.TagAlias, { input, output }); return send(message, { content, allowedMentions: { users: [], roles: [] } }); } @RequiresLevel(PermissionLevels.Moderator, LanguageKeys.Commands.Tags.TagPermissionLevel) public async rename(message: GuildMessage, args: SkyraCommand.Args) { const previous = (await args.pick('string')).toLowerCase(); const next = (await args.pick('string')).toLowerCase(); await writeSettings(message.guild, (settings) => { const tags = settings[GuildSettings.CustomCommands]; // Get previous tag: const tag = tags.find((tag) => tag.id === previous); if (tag === undefined) this.error(LanguageKeys.Commands.Tags.TagNotExists, { tag: previous }); // Check if a tag with the name exists: if (getFromId(next, tags) !== null) this.error(LanguageKeys.Commands.Tags.TagExists, { tag: next }); // Rename tag: tag.id = next; }); const content = args.t(LanguageKeys.Commands.Tags.TagRenamed, { name: next, previous }); return send(message, { content, allowedMentions: { users: [], roles: [] } }); } @RequiresLevel(PermissionLevels.Moderator, LanguageKeys.Commands.Tags.TagPermissionLevel) public async reset(message: GuildMessage, args: SkyraCommand.Args) { await writeSettings(message.guild, (settings) => { settings[GuildSettings.CustomCommands].length = 0; }); const content = args.t(LanguageKeys.Commands.Tags.TagReset); return send(message, content); } @RequiresLevel(PermissionLevels.Moderator, LanguageKeys.Commands.Tags.TagPermissionLevel) public async edit(message: GuildMessage, args: SkyraCommand.Args) { const id = (await args.pick('string')).toLowerCase(); const commandContent = await args.rest('string'); await writeSettings(message.guild, (settings) => { const tags = settings[GuildSettings.CustomCommands]; const tagIndex = tags.findIndex((command) => command.id === id); if (tagIndex === -1) this.error(LanguageKeys.Commands.Tags.TagNotExists, { tag: id }); tags[tagIndex] = this.createTag(args, id, commandContent, tags[tagIndex].aliases); }); const content = args.t(LanguageKeys.Commands.Tags.TagEdited, { name: id, content: cutText(commandContent, 500) }); return send(message, { content, allowedMentions: { users: [], roles: [] } }); } @RequiresClientPermissions(['ADD_REACTIONS', 'EMBED_LINKS', 'MANAGE_MESSAGES', 'READ_MESSAGE_HISTORY']) public async list(message: GuildMessage, args: SkyraCommand.Args) { // Get tags, prefix, and language const [tags, prefix] = await readSettings(message.guild, [GuildSettings.CustomCommands, GuildSettings.Prefix]); if (!tags.length) this.error(LanguageKeys.Commands.Tags.TagListEmpty); const response = await sendLoadingMessage(message, args.t); // Get prefix and display all tags const display = new SkyraPaginatedMessage({ template: new MessageEmbed().setColor(await this.container.db.fetchColor(message)) }); // Add all pages, containing 30 tags each for (const page of chunk(tags, 30)) { const description = `\`${page.map((command) => `${prefix}${command.id}`).join('`, `')}\``; display.addPageEmbed((embed) => embed.setDescription(description)); } // Run the display await display.run(response, message.author); return response; } @RequiresClientPermissions(['EMBED_LINKS']) public async show(message: GuildMessage, args: SkyraCommand.Args) { const id = (await args.pick('string')).toLowerCase(); const tags = await readSettings(message.guild, GuildSettings.CustomCommands); const tag = getFromId(id, tags); if (tag === null) return null; return send(message, await this.getShowOptions(args, tag)); } public async source(message: GuildMessage, args: SkyraCommand.Args) { const id = (await args.pick('string')).toLowerCase(); const tags = await readSettings(message.guild, GuildSettings.CustomCommands); const tag = getFromId(id, tags); if (tag === null) return null; const content = codeBlock('md', tag.content.toString()); return send(message, { content, allowedMentions: { users: [], roles: [] } }); } private createTag(args: SkyraCommand.Args, id: string, content: string, aliases: string[] = []): CustomCommand { // Create the tag data: const embed = args.getFlags('embed'); return { id, content: this.parseContent(args, content), embed, aliases, color: embed ? this.parseColour(args) : 0 }; } private parseContent(args: SkyraCommand.Args, content: string) { try { return parseAndValidate(content); } catch (error) { if (!(error instanceof UserError)) throw error; switch (error.identifier) { case Identifiers.MismatchingNamedArgumentTypeValidation: this.error(LanguageKeys.Commands.Tags.ParseMismatchingNamedArgumentTypeValidation, error); case Identifiers.ParserEmptyStringTag: this.error(LanguageKeys.Commands.Tags.ParseParserEmptyStringTag, error); case Identifiers.ParserMissingToken: this.error(LanguageKeys.Commands.Tags.ParseParserMissingToken, error); case Identifiers.ParserPickMissingOptions: this.error(LanguageKeys.Commands.Tags.ParseParserPickMissingOptions, error); case Identifiers.ParserRandomDuplicatedOptions: this.error(LanguageKeys.Commands.Tags.ParseParserRandomDuplicatedOptions, error); case Identifiers.ParserRandomMissingOptions: this.error(LanguageKeys.Commands.Tags.ParseParserRandomMissingOptions, error); case Identifiers.ParserUnexpectedToken: { const typedError = error as ParserUnexpectedTokenError; this.error(LanguageKeys.Commands.Tags.ParseParserUnexpectedToken, { expected: this.parseContentGetPartTypeName(args, typedError.expected), received: this.parseContentGetPartTypeName(args, typedError.received) }); } case Identifiers.PickInvalidOption: this.error(LanguageKeys.Commands.Tags.ParsePickInvalidOption, error); case Identifiers.SentenceMissingArgument: this.error(LanguageKeys.Commands.Tags.ParseSentenceMissingArgument, error); case Identifiers.TransformerInvalidFormatter: this.error(LanguageKeys.Commands.Tags.ParseTransformerInvalidFormatter, error); } } } private parseContentGetPartTypeName(args: SkyraCommand.Args, type: PartType | readonly PartType[]): string { if (Array.isArray(type)) { return args.t(LanguageKeys.Globals.OrListValue, { value: type.map((v) => this.inlineCode(this.parseContentGetPartTypeName(args, v))) }); } switch (type as PartType) { case PartType.Space: return this.inlineCode(args.t(LanguageKeys.Commands.Tags.ParseTokenSpace)); case PartType.TagStart: return this.inlineCode(args.t(LanguageKeys.Commands.Tags.ParseTokenTagStart)); case PartType.TagEnd: return this.inlineCode(args.t(LanguageKeys.Commands.Tags.ParseTokenTagEnd)); case PartType.Equals: return this.inlineCode(args.t(LanguageKeys.Commands.Tags.ParseTokenEquals)); case PartType.Colon: return this.inlineCode(args.t(LanguageKeys.Commands.Tags.ParseTokenColon)); case PartType.Pipe: return this.inlineCode(args.t(LanguageKeys.Commands.Tags.ParseTokenPipe)); case PartType.Literal: return this.inlineCode(args.t(LanguageKeys.Commands.Tags.ParseTokenLiteral)); } } private inlineCode(content: string) { return `\`${content}\``; } private parseColour(args: SkyraCommand.Args) { let color = args.getOption('color', 'colour'); if (color === null) return 0; const number = Number(color); if (Number.isSafeInteger(number)) return Math.max(Math.min(number, 0xffffff), 0x000000); if (this.#kHexLessRegex.test(color)) color = `#${color}`; return parseColour(color)?.b10.value ?? 0; } private async getShowOptions(args: SkyraCommand.Args, tag: CustomCommand): Promise<MessageOptions> { const allowedMentions = new Set<string>(); const iterator = tag.content.run(); let result = iterator.next(); while (!result.done) result = iterator.next(await parseParameter(args, result.value.type as InvalidTypeError.Type, allowedMentions)); const content = result.value.trim(); if (tag.embed) { const embed = new MessageEmbed().setDescription(content).setColor(tag.color); return { embeds: [embed] }; } return { content, allowedMentions: { users: [...allowedMentions], roles: [] } }; } }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type MyCollectionArtworkArtistAuctionResultsTestsQueryVariables = {}; export type MyCollectionArtworkArtistAuctionResultsTestsQueryResponse = { readonly artwork: { readonly " $fragmentRefs": FragmentRefs<"MyCollectionArtworkArtistAuctionResults_artwork">; } | null; }; export type MyCollectionArtworkArtistAuctionResultsTestsQuery = { readonly response: MyCollectionArtworkArtistAuctionResultsTestsQueryResponse; readonly variables: MyCollectionArtworkArtistAuctionResultsTestsQueryVariables; }; /* query MyCollectionArtworkArtistAuctionResultsTestsQuery { artwork(id: "some-slug") { ...MyCollectionArtworkArtistAuctionResults_artwork id } } fragment AuctionResultListItem_auctionResult on AuctionResult { currency dateText id internalID artist { name id } images { thumbnail { url(version: "square140") height width aspectRatio } } estimate { low } mediumText organization boughtIn performance { mid } priceRealized { cents display displayUSD } saleDate title } fragment MyCollectionArtworkArtistAuctionResults_artwork on Artwork { internalID slug artist { slug name auctionResultsConnection(first: 3, sort: DATE_DESC) { edges { node { id internalID ...AuctionResultListItem_auctionResult } } } id } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "some-slug" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v5 = { "enumValues": null, "nullable": true, "plural": false, "type": "Artist" }, v6 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v7 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v8 = { "enumValues": null, "nullable": true, "plural": false, "type": "Float" }, v9 = { "enumValues": null, "nullable": true, "plural": false, "type": "Int" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "MyCollectionArtworkArtistAuctionResultsTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "MyCollectionArtworkArtistAuctionResults_artwork" } ], "storageKey": "artwork(id:\"some-slug\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "MyCollectionArtworkArtistAuctionResultsTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ (v1/*: any*/), (v2/*: any*/), { "alias": null, "args": null, "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ (v2/*: any*/), (v3/*: any*/), { "alias": null, "args": [ { "kind": "Literal", "name": "first", "value": 3 }, { "kind": "Literal", "name": "sort", "value": "DATE_DESC" } ], "concreteType": "AuctionResultConnection", "kind": "LinkedField", "name": "auctionResultsConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "AuctionResultEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "AuctionResult", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v4/*: any*/), (v1/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "currency", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "dateText", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ (v3/*: any*/), (v4/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotImages", "kind": "LinkedField", "name": "images", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "thumbnail", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "square140" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"square140\")" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotEstimate", "kind": "LinkedField", "name": "estimate", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "low", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "mediumText", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "organization", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "boughtIn", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotPerformance", "kind": "LinkedField", "name": "performance", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "mid", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionResultPriceRealized", "kind": "LinkedField", "name": "priceRealized", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "cents", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "displayUSD", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "saleDate", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": "auctionResultsConnection(first:3,sort:\"DATE_DESC\")" }, (v4/*: any*/) ], "storageKey": null }, (v4/*: any*/) ], "storageKey": "artwork(id:\"some-slug\")" } ] }, "params": { "id": "6aeacf2bb7bdfac8a516a17343e709c2", "metadata": { "relayTestingSelectionTypeInfo": { "artwork": { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, "artwork.artist": (v5/*: any*/), "artwork.artist.auctionResultsConnection": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionResultConnection" }, "artwork.artist.auctionResultsConnection.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "AuctionResultEdge" }, "artwork.artist.auctionResultsConnection.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionResult" }, "artwork.artist.auctionResultsConnection.edges.node.artist": (v5/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.artist.id": (v6/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.artist.name": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.boughtIn": { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }, "artwork.artist.auctionResultsConnection.edges.node.currency": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.dateText": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.estimate": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionLotEstimate" }, "artwork.artist.auctionResultsConnection.edges.node.estimate.low": (v8/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.id": (v6/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.images": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionLotImages" }, "artwork.artist.auctionResultsConnection.edges.node.images.thumbnail": { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, "artwork.artist.auctionResultsConnection.edges.node.images.thumbnail.aspectRatio": { "enumValues": null, "nullable": false, "plural": false, "type": "Float" }, "artwork.artist.auctionResultsConnection.edges.node.images.thumbnail.height": (v9/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.images.thumbnail.url": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.images.thumbnail.width": (v9/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.internalID": (v6/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.mediumText": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.organization": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.performance": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionLotPerformance" }, "artwork.artist.auctionResultsConnection.edges.node.performance.mid": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.priceRealized": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionResultPriceRealized" }, "artwork.artist.auctionResultsConnection.edges.node.priceRealized.cents": (v8/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.priceRealized.display": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.priceRealized.displayUSD": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.saleDate": (v7/*: any*/), "artwork.artist.auctionResultsConnection.edges.node.title": (v7/*: any*/), "artwork.artist.id": (v6/*: any*/), "artwork.artist.name": (v7/*: any*/), "artwork.artist.slug": (v6/*: any*/), "artwork.id": (v6/*: any*/), "artwork.internalID": (v6/*: any*/), "artwork.slug": (v6/*: any*/) } }, "name": "MyCollectionArtworkArtistAuctionResultsTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = 'c16e41c028e78ada6aad675e538b4182'; export default node;
the_stack
import { $enum, EnumValueVisitor, EnumValueVisitorWithNull, EnumValueVisitorWithUndefined, EnumValueVisitorWithNullAndUndefined } from "../src"; enum RGB { R = "r", G = "g", B = "b" } describe("visitValue (string)", () => { const handlerMockR = jest.fn((value: RGB.R) => { return "Red!"; }); const handlerMockG = jest.fn((value: RGB.G) => { return "Green!"; }); const handlerMockB = jest.fn((value: RGB.B) => { return "Blue!"; }); const handlerMockNull = jest.fn((value: null) => { return "Null!"; }); const handlerMockUndefined = jest.fn((value: undefined) => { return "Undefined!"; }); const handlerMockUnexpected = jest.fn( (value: string | null | undefined) => { return `Unexpected! (${value})`; } ); const ALL_HANDLER_MOCKS = [ handlerMockR, handlerMockG, handlerMockB, handlerMockNull, handlerMockUndefined, handlerMockUnexpected ]; beforeEach(() => { // Clear all handler mocks for a fresh start before each test for (const handlerMock of ALL_HANDLER_MOCKS) { handlerMock.mockClear(); } }); describe("Without null/undefined", () => { interface TestEntry { isUnexpected?: boolean; value: RGB; handlerMock: jest.Mock<string>; result: string; } const TEST_ENTRIES: TestEntry[] = [ { value: RGB.R, handlerMock: handlerMockR, result: "Red!" }, { value: RGB.G, handlerMock: handlerMockG, result: "Green!" }, { value: RGB.B, handlerMock: handlerMockB, result: "Blue!" }, { isUnexpected: true, value: (null as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (null)" }, { isUnexpected: true, value: (undefined as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (undefined)" }, { isUnexpected: true, value: ("unexpected!" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (unexpected!)" }, { isUnexpected: true, // matches a standard property name on Object.prototype value: ("toString" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (toString)" } ]; const visitors: EnumValueVisitor<RGB, string>[] = [ { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB }, { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB, [$enum.handleUnexpected]: handlerMockUnexpected }, { [RGB.R]: $enum.unhandledEntry, [RGB.G]: $enum.unhandledEntry, [RGB.B]: $enum.unhandledEntry, [$enum.handleUnexpected]: $enum.unhandledEntry } ]; for (const visitor of visitors) { for (const testEntry of TEST_ENTRIES) { if (visitor[RGB.R] === $enum.unhandledEntry) { test(`Unhandled entry throws error (${testEntry.value}`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unhandled value: ${testEntry.value}`); }); } else if ( visitor[$enum.handleUnexpected] || !testEntry.isUnexpected ) { test(`Correct visitor method is called (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); for (const handlerMock of ALL_HANDLER_MOCKS) { if (handlerMock === testEntry.handlerMock) { expect(handlerMock.mock.calls.length).toBe(1); } else { expect(handlerMock.mock.calls.length).toBe(0); } } }); test(`Value is passed to handler (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); expect(testEntry.handlerMock.mock.calls.length).toBe(1); const args = testEntry.handlerMock.mock.calls[0]; expect(args.length).toBe(1); expect(args[0]).toBe(testEntry.value); }); test(`Handler result is returned (${testEntry.value})`, () => { const result = $enum .visitValue(testEntry.value) .with(visitor); expect(result).toBe(testEntry.result); }); } else { test(`Unhandled unexpected value throws error (${testEntry.value})`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unexpected value: ${testEntry.value}`); }); test(`No visitor method is called for unhandled unexpected value(${testEntry.value})`, () => { try { $enum.visitValue(testEntry.value).with(visitor); } catch (error) { // ignore error } for (const handlerMock of ALL_HANDLER_MOCKS) { expect(handlerMock.mock.calls.length).toBe(0); } }); } } } }); describe("With null", () => { interface TestEntry { isUnexpected?: boolean; value: RGB | null; handlerMock: jest.Mock<string>; result: string; } const TEST_ENTRIES: TestEntry[] = [ { value: RGB.R, handlerMock: handlerMockR, result: "Red!" }, { value: RGB.G, handlerMock: handlerMockG, result: "Green!" }, { value: RGB.B, handlerMock: handlerMockB, result: "Blue!" }, { value: null, handlerMock: handlerMockNull, result: "Null!" }, { isUnexpected: true, value: (undefined as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (undefined)" }, { isUnexpected: true, value: ("unexpected!" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (unexpected!)" }, { isUnexpected: true, // matches a standard property name on Object.prototype value: ("toString" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (toString)" } ]; const visitors: EnumValueVisitorWithNull<RGB, string>[] = [ { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB, [$enum.handleNull]: handlerMockNull }, { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB, [$enum.handleNull]: handlerMockNull, [$enum.handleUnexpected]: handlerMockUnexpected }, { [RGB.R]: $enum.unhandledEntry, [RGB.G]: $enum.unhandledEntry, [RGB.B]: $enum.unhandledEntry, [$enum.handleNull]: $enum.unhandledEntry, [$enum.handleUnexpected]: $enum.unhandledEntry } ]; for (const visitor of visitors) { for (const testEntry of TEST_ENTRIES) { if (visitor[RGB.R] === $enum.unhandledEntry) { test(`Unhandled entry throws error (${testEntry.value}`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unhandled value: ${testEntry.value}`); }); } else if ( visitor[$enum.handleUnexpected] || !testEntry.isUnexpected ) { test(`Correct visitor method is called (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); for (const handlerMock of ALL_HANDLER_MOCKS) { if (handlerMock === testEntry.handlerMock) { expect(handlerMock.mock.calls.length).toBe(1); } else { expect(handlerMock.mock.calls.length).toBe(0); } } }); test(`Value is passed to handler (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); expect(testEntry.handlerMock.mock.calls.length).toBe(1); const args = testEntry.handlerMock.mock.calls[0]; expect(args.length).toBe(1); expect(args[0]).toBe(testEntry.value); }); test(`Handler result is returned (${testEntry.value})`, () => { const result = $enum .visitValue(testEntry.value) .with(visitor); expect(result).toBe(testEntry.result); }); } else { test(`unhandled unexpected value throws error (${testEntry.value})`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unexpected value: ${testEntry.value}`); }); test(`No visitor method is called for unhandled unexpected value(${testEntry.value})`, () => { try { $enum.visitValue(testEntry.value).with(visitor); } catch (error) { // ignore error } for (const handlerMock of ALL_HANDLER_MOCKS) { expect(handlerMock.mock.calls.length).toBe(0); } }); } } } }); describe("With undefined", () => { interface TestEntry { isUnexpected?: boolean; value: RGB | undefined; handlerMock: jest.Mock<string>; result: string; } const TEST_ENTRIES: TestEntry[] = [ { value: RGB.R, handlerMock: handlerMockR, result: "Red!" }, { value: RGB.G, handlerMock: handlerMockG, result: "Green!" }, { value: RGB.B, handlerMock: handlerMockB, result: "Blue!" }, { value: undefined, handlerMock: handlerMockUndefined, result: "Undefined!" }, { isUnexpected: true, value: (null as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (null)" }, { isUnexpected: true, value: ("unexpected!" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (unexpected!)" }, { isUnexpected: true, // matches a standard property name on Object.prototype value: ("toString" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (toString)" } ]; const visitors: EnumValueVisitorWithUndefined<RGB, string>[] = [ { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB, [$enum.handleUndefined]: handlerMockUndefined }, { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB, [$enum.handleUndefined]: handlerMockUndefined, [$enum.handleUnexpected]: handlerMockUnexpected }, { [RGB.R]: $enum.unhandledEntry, [RGB.G]: $enum.unhandledEntry, [RGB.B]: $enum.unhandledEntry, [$enum.handleUndefined]: $enum.unhandledEntry, [$enum.handleUnexpected]: $enum.unhandledEntry } ]; for (const visitor of visitors) { for (const testEntry of TEST_ENTRIES) { if (visitor[RGB.R] === $enum.unhandledEntry) { test(`Unhandled entry throws error (${testEntry.value}`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unhandled value: ${testEntry.value}`); }); } else if ( visitor[$enum.handleUnexpected] || !testEntry.isUnexpected ) { test(`Correct visitor method is called (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); for (const handlerMock of ALL_HANDLER_MOCKS) { if (handlerMock === testEntry.handlerMock) { expect(handlerMock.mock.calls.length).toBe(1); } else { expect(handlerMock.mock.calls.length).toBe(0); } } }); test(`Value is passed to handler (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); expect(testEntry.handlerMock.mock.calls.length).toBe(1); const args = testEntry.handlerMock.mock.calls[0]; expect(args.length).toBe(1); expect(args[0]).toBe(testEntry.value); }); test(`Handler result is returned (${testEntry.value})`, () => { const result = $enum .visitValue(testEntry.value) .with(visitor); expect(result).toBe(testEntry.result); }); } else { test(`Unhandled unexpected value throws error (${testEntry.value})`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unexpected value: ${testEntry.value}`); }); test(`No visitor method is called for unhandled unexpected value(${testEntry.value})`, () => { try { $enum.visitValue(testEntry.value).with(visitor); } catch (error) { // ignore error } for (const handlerMock of ALL_HANDLER_MOCKS) { expect(handlerMock.mock.calls.length).toBe(0); } }); } } } }); describe("With null and undefined", () => { interface TestEntry { isUnexpected?: boolean; value: RGB | null | undefined; handlerMock: jest.Mock<string>; result: string; } const TEST_ENTRIES: TestEntry[] = [ { value: RGB.R, handlerMock: handlerMockR, result: "Red!" }, { value: RGB.G, handlerMock: handlerMockG, result: "Green!" }, { value: RGB.B, handlerMock: handlerMockB, result: "Blue!" }, { value: null, handlerMock: handlerMockNull, result: "Null!" }, { value: undefined, handlerMock: handlerMockUndefined, result: "Undefined!" }, { isUnexpected: true, value: ("unexpected!" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (unexpected!)" }, { isUnexpected: true, // matches a standard property name on Object.prototype value: ("toString" as any) as RGB, handlerMock: handlerMockUnexpected, result: "Unexpected! (toString)" } ]; const visitors: EnumValueVisitorWithNullAndUndefined<RGB, string>[] = [ { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB, [$enum.handleNull]: handlerMockNull, [$enum.handleUndefined]: handlerMockUndefined }, { [RGB.R]: handlerMockR, [RGB.G]: handlerMockG, [RGB.B]: handlerMockB, [$enum.handleNull]: handlerMockNull, [$enum.handleUndefined]: handlerMockUndefined, [$enum.handleUnexpected]: handlerMockUnexpected }, { [RGB.R]: $enum.unhandledEntry, [RGB.G]: $enum.unhandledEntry, [RGB.B]: $enum.unhandledEntry, [$enum.handleNull]: $enum.unhandledEntry, [$enum.handleUndefined]: $enum.unhandledEntry, [$enum.handleUnexpected]: $enum.unhandledEntry } ]; for (const visitor of visitors) { for (const testEntry of TEST_ENTRIES) { if (visitor[RGB.R] === $enum.unhandledEntry) { test(`Unhandled entry throws error (${testEntry.value}`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unhandled value: ${testEntry.value}`); }); } else if ( visitor[$enum.handleUnexpected] || !testEntry.isUnexpected ) { test(`Correct visitor method is called (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); for (const handlerMock of ALL_HANDLER_MOCKS) { if (handlerMock === testEntry.handlerMock) { expect(handlerMock.mock.calls.length).toBe(1); } else { expect(handlerMock.mock.calls.length).toBe(0); } } }); test(`Value is passed to handler (${testEntry.value})`, () => { $enum.visitValue(testEntry.value).with(visitor); expect(testEntry.handlerMock.mock.calls.length).toBe(1); const args = testEntry.handlerMock.mock.calls[0]; expect(args.length).toBe(1); expect(args[0]).toBe(testEntry.value); }); test(`Handler result is returned (${testEntry.value})`, () => { const result = $enum .visitValue(testEntry.value) .with(visitor); expect(result).toBe(testEntry.result); }); } else { test(`Unhandled unexpected value throws error (${testEntry.value})`, () => { expect(() => { $enum.visitValue(testEntry.value).with(visitor); }).toThrowError(`Unexpected value: ${testEntry.value}`); }); test(`No visitor method is called for unhandled unexpected value(${testEntry.value})`, () => { try { $enum.visitValue(testEntry.value).with(visitor); } catch (error) { // ignore error } for (const handlerMock of ALL_HANDLER_MOCKS) { expect(handlerMock.mock.calls.length).toBe(0); } }); } } } }); });
the_stack
import { Component, EventEmitter, OnInit } from '@angular/core'; import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { ExternalSourceEntry } from '../../../../../../../core/shared/external-source-entry.model'; import { MetadataValue } from '../../../../../../../core/shared/metadata.models'; import { Metadata } from '../../../../../../../core/shared/metadata.utils'; import { Observable } from 'rxjs'; import { RemoteData } from '../../../../../../../core/data/remote-data'; import { PaginatedList } from '../../../../../../../core/data/paginated-list.model'; import { SearchResult } from '../../../../../../search/search-result.model'; import { Item } from '../../../../../../../core/shared/item.model'; import { RelationshipOptions } from '../../../../models/relationship-options.model'; import { LookupRelationService } from '../../../../../../../core/data/lookup-relation.service'; import { PaginatedSearchOptions } from '../../../../../../search/paginated-search-options.model'; import { CollectionElementLinkType } from '../../../../../../object-collection/collection-element-link.type'; import { Context } from '../../../../../../../core/shared/context.model'; import { SelectableListService } from '../../../../../../object-list/selectable-list/selectable-list.service'; import { ListableObject } from '../../../../../../object-collection/shared/listable-object.model'; import { ItemDataService } from '../../../../../../../core/data/item-data.service'; import { PaginationComponentOptions } from '../../../../../../pagination/pagination-component-options.model'; import { getFirstSucceededRemoteData, getRemoteDataPayload } from '../../../../../../../core/shared/operators'; import { switchMap, take } from 'rxjs/operators'; import { ItemSearchResult } from '../../../../../../object-collection/shared/item-search-result.model'; import { NotificationsService } from '../../../../../../notifications/notifications.service'; import { TranslateService } from '@ngx-translate/core'; import { ItemType } from '../../../../../../../core/shared/item-relationships/item-type.model'; import { SubmissionImportExternalCollectionComponent } from '../../../../../../../submission/import-external/import-external-collection/submission-import-external-collection.component'; import { CollectionListEntry } from '../../../../../../collection-dropdown/collection-dropdown.component'; /** * The possible types of import for the external entry */ export enum ImportType { None = 'None', LocalEntity = 'LocalEntity', LocalAuthority = 'LocalAuthority', NewEntity = 'NewEntity', NewAuthority = 'NewAuthority' } @Component({ selector: 'ds-external-source-entry-import-modal', styleUrls: ['./external-source-entry-import-modal.component.scss'], templateUrl: './external-source-entry-import-modal.component.html' }) /** * Component to display a modal window for importing an external source entry * Shows information about the selected entry and a selectable list of local entities and authorities with similar names * and the ability to add one of those results to the selection instead of the external entry. * The other option is to import the external entry as a new entity or authority into the repository. */ export class ExternalSourceEntryImportModalComponent implements OnInit { /** * The prefix for every i18n key within this modal */ labelPrefix = 'submission.sections.describe.relationship-lookup.external-source.import-modal.'; /** * The label to use for all messages (added to the end of relevant i18n keys) */ label: string; /** * The external source entry */ externalSourceEntry: ExternalSourceEntry; /** * The item in submission */ item: Item; /** * The current relationship-options used for filtering results */ relationship: RelationshipOptions; /** * The metadata value for the entry's uri */ uri: MetadataValue; /** * Local entities with a similar name */ localEntitiesRD$: Observable<RemoteData<PaginatedList<SearchResult<Item>>>>; /** * Search options to use for fetching similar results */ searchOptions: PaginatedSearchOptions; /** * The type of link to render in listable elements */ linkTypes = CollectionElementLinkType; /** * The context we're currently in (submission) */ context = Context.EntitySearchModalWithNameVariants; /** * List ID for selecting local entities */ entityListId = 'external-source-import-entity'; /** * List ID for selecting local authorities */ authorityListId = 'external-source-import-authority'; /** * ImportType enum */ importType = ImportType; /** * The type of import the user currently has selected */ selectedImportType = ImportType.None; /** * The selected local entity */ selectedEntity: ListableObject; /** * The selected local authority */ selectedAuthority: ListableObject; /** * An object has been imported, send it to the parent component */ importedObject: EventEmitter<ListableObject> = new EventEmitter<ListableObject>(); /** * Should it display the ability to import the entry as an authority? */ authorityEnabled = false; /** * The entity types compatible with the given external source */ relatedEntityType: ItemType; /** * The modal for the collection selection */ modalRef: NgbModalRef; constructor(public modal: NgbActiveModal, public lookupRelationService: LookupRelationService, private modalService: NgbModal, private selectService: SelectableListService, private itemService: ItemDataService, private notificationsService: NotificationsService, private translateService: TranslateService) { } ngOnInit(): void { this.uri = Metadata.first(this.externalSourceEntry.metadata, 'dc.identifier.uri'); const pagination = Object.assign(new PaginationComponentOptions(), { id: 'external-entry-import', pageSize: 5 }); this.searchOptions = Object.assign(new PaginatedSearchOptions({ query: this.externalSourceEntry.value, pagination: pagination })); this.localEntitiesRD$ = this.lookupRelationService.getLocalResults(this.relationship, this.searchOptions); } /** * Close the window */ close() { this.modal.close(); } /** * Perform the import of the external entry */ import() { switch (this.selectedImportType) { case ImportType.LocalEntity : { this.importLocalEntity(); break; } case ImportType.NewEntity : { this.importNewEntity(); break; } case ImportType.LocalAuthority : { this.importLocalAuthority(); break; } case ImportType.NewAuthority : { this.importNewAuthority(); break; } } this.selectedImportType = ImportType.None; this.deselectAllLists(); this.close(); } /** * Import the selected local entity */ importLocalEntity() { if (this.selectedEntity !== undefined) { this.notificationsService.success(this.translateService.get(this.labelPrefix + this.label + '.added.local-entity')); this.importedObject.emit(this.selectedEntity); } } /** * Create and import a new entity from the external entry */ importNewEntity() { this.modalRef = this.modalService.open(SubmissionImportExternalCollectionComponent, { size: 'lg', }); this.modalRef.componentInstance.entityType = this.relatedEntityType.label; this.modalRef.componentInstance.selectedEvent.pipe( switchMap((collectionListEntry: CollectionListEntry) => { return this.itemService.importExternalSourceEntry(this.externalSourceEntry, collectionListEntry.collection.id).pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), take(1) ); }) ).subscribe((item: Item) => { this.lookupRelationService.removeLocalResultsCache(); const searchResult = Object.assign(new ItemSearchResult(), { indexableObject: item }); this.notificationsService.success(this.translateService.get(this.labelPrefix + this.label + '.added.new-entity')); this.modalRef.close(); this.importedObject.emit(searchResult); }); } /** * Import the selected local authority */ importLocalAuthority() { // TODO: Implement ability to import local authorities } /** * Create and import a new authority from the external entry */ importNewAuthority() { // TODO: Implement ability to import new authorities } /** * Deselected a local entity */ deselectEntity() { this.selectedEntity = undefined; if (this.selectedImportType === ImportType.LocalEntity) { this.selectedImportType = ImportType.None; } } /** * Selected a local entity * @param entity */ selectEntity(entity) { this.selectedEntity = entity; this.selectedImportType = ImportType.LocalEntity; } /** * Selected/deselected the new entity option */ selectNewEntity() { if (this.selectedImportType === ImportType.NewEntity) { this.selectedImportType = ImportType.None; } else { this.selectedImportType = ImportType.NewEntity; this.deselectAllLists(); } } /** * Deselected a local authority */ deselectAuthority() { this.selectedAuthority = undefined; if (this.selectedImportType === ImportType.LocalAuthority) { this.selectedImportType = ImportType.None; } } /** * Selected a local authority * @param authority */ selectAuthority(authority) { this.selectedAuthority = authority; this.selectedImportType = ImportType.LocalAuthority; } /** * Selected/deselected the new authority option */ selectNewAuthority() { if (this.selectedImportType === ImportType.NewAuthority) { this.selectedImportType = ImportType.None; } else { this.selectedImportType = ImportType.NewAuthority; this.deselectAllLists(); } } /** * Deselect every element from both entity and authority lists */ deselectAllLists() { this.selectService.deselectAll(this.entityListId); this.selectService.deselectAll(this.authorityListId); } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { EmptyOperationCommand, EmptyOperationCommandInput, EmptyOperationCommandOutput, } from "./commands/EmptyOperationCommand"; import { EndpointOperationCommand, EndpointOperationCommandInput, EndpointOperationCommandOutput, } from "./commands/EndpointOperationCommand"; import { EndpointWithHostLabelOperationCommand, EndpointWithHostLabelOperationCommandInput, EndpointWithHostLabelOperationCommandOutput, } from "./commands/EndpointWithHostLabelOperationCommand"; import { GreetingWithErrorsCommand, GreetingWithErrorsCommandInput, GreetingWithErrorsCommandOutput, } from "./commands/GreetingWithErrorsCommand"; import { HostWithPathOperationCommand, HostWithPathOperationCommandInput, HostWithPathOperationCommandOutput, } from "./commands/HostWithPathOperationCommand"; import { JsonEnumsCommand, JsonEnumsCommandInput, JsonEnumsCommandOutput } from "./commands/JsonEnumsCommand"; import { JsonUnionsCommand, JsonUnionsCommandInput, JsonUnionsCommandOutput } from "./commands/JsonUnionsCommand"; import { KitchenSinkOperationCommand, KitchenSinkOperationCommandInput, KitchenSinkOperationCommandOutput, } from "./commands/KitchenSinkOperationCommand"; import { NullOperationCommand, NullOperationCommandInput, NullOperationCommandOutput, } from "./commands/NullOperationCommand"; import { OperationWithOptionalInputOutputCommand, OperationWithOptionalInputOutputCommandInput, OperationWithOptionalInputOutputCommandOutput, } from "./commands/OperationWithOptionalInputOutputCommand"; import { PutAndGetInlineDocumentsCommand, PutAndGetInlineDocumentsCommandInput, PutAndGetInlineDocumentsCommandOutput, } from "./commands/PutAndGetInlineDocumentsCommand"; import { SimpleScalarPropertiesCommand, SimpleScalarPropertiesCommandInput, SimpleScalarPropertiesCommandOutput, } from "./commands/SimpleScalarPropertiesCommand"; import { JsonProtocolClient } from "./JsonProtocolClient"; export class JsonProtocol extends JsonProtocolClient { public emptyOperation( args: EmptyOperationCommandInput, options?: __HttpHandlerOptions ): Promise<EmptyOperationCommandOutput>; public emptyOperation( args: EmptyOperationCommandInput, cb: (err: any, data?: EmptyOperationCommandOutput) => void ): void; public emptyOperation( args: EmptyOperationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EmptyOperationCommandOutput) => void ): void; public emptyOperation( args: EmptyOperationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EmptyOperationCommandOutput) => void), cb?: (err: any, data?: EmptyOperationCommandOutput) => void ): Promise<EmptyOperationCommandOutput> | void { const command = new EmptyOperationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } public endpointOperation( args: EndpointOperationCommandInput, options?: __HttpHandlerOptions ): Promise<EndpointOperationCommandOutput>; public endpointOperation( args: EndpointOperationCommandInput, cb: (err: any, data?: EndpointOperationCommandOutput) => void ): void; public endpointOperation( args: EndpointOperationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EndpointOperationCommandOutput) => void ): void; public endpointOperation( args: EndpointOperationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EndpointOperationCommandOutput) => void), cb?: (err: any, data?: EndpointOperationCommandOutput) => void ): Promise<EndpointOperationCommandOutput> | void { const command = new EndpointOperationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } public endpointWithHostLabelOperation( args: EndpointWithHostLabelOperationCommandInput, options?: __HttpHandlerOptions ): Promise<EndpointWithHostLabelOperationCommandOutput>; public endpointWithHostLabelOperation( args: EndpointWithHostLabelOperationCommandInput, cb: (err: any, data?: EndpointWithHostLabelOperationCommandOutput) => void ): void; public endpointWithHostLabelOperation( args: EndpointWithHostLabelOperationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EndpointWithHostLabelOperationCommandOutput) => void ): void; public endpointWithHostLabelOperation( args: EndpointWithHostLabelOperationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EndpointWithHostLabelOperationCommandOutput) => void), cb?: (err: any, data?: EndpointWithHostLabelOperationCommandOutput) => void ): Promise<EndpointWithHostLabelOperationCommandOutput> | void { const command = new EndpointWithHostLabelOperationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * This operation has three possible return values: * * 1. A successful response in the form of GreetingWithErrorsOutput * 2. An InvalidGreeting error. * 3. A ComplexError error. * * Implementations must be able to successfully take a response and * properly deserialize successful and error responses. */ public greetingWithErrors( args: GreetingWithErrorsCommandInput, options?: __HttpHandlerOptions ): Promise<GreetingWithErrorsCommandOutput>; public greetingWithErrors( args: GreetingWithErrorsCommandInput, cb: (err: any, data?: GreetingWithErrorsCommandOutput) => void ): void; public greetingWithErrors( args: GreetingWithErrorsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GreetingWithErrorsCommandOutput) => void ): void; public greetingWithErrors( args: GreetingWithErrorsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GreetingWithErrorsCommandOutput) => void), cb?: (err: any, data?: GreetingWithErrorsCommandOutput) => void ): Promise<GreetingWithErrorsCommandOutput> | void { const command = new GreetingWithErrorsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } public hostWithPathOperation( args: HostWithPathOperationCommandInput, options?: __HttpHandlerOptions ): Promise<HostWithPathOperationCommandOutput>; public hostWithPathOperation( args: HostWithPathOperationCommandInput, cb: (err: any, data?: HostWithPathOperationCommandOutput) => void ): void; public hostWithPathOperation( args: HostWithPathOperationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: HostWithPathOperationCommandOutput) => void ): void; public hostWithPathOperation( args: HostWithPathOperationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: HostWithPathOperationCommandOutput) => void), cb?: (err: any, data?: HostWithPathOperationCommandOutput) => void ): Promise<HostWithPathOperationCommandOutput> | void { const command = new HostWithPathOperationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * This example serializes enums as top level properties, in lists, sets, and maps. */ public jsonEnums(args: JsonEnumsCommandInput, options?: __HttpHandlerOptions): Promise<JsonEnumsCommandOutput>; public jsonEnums(args: JsonEnumsCommandInput, cb: (err: any, data?: JsonEnumsCommandOutput) => void): void; public jsonEnums( args: JsonEnumsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: JsonEnumsCommandOutput) => void ): void; public jsonEnums( args: JsonEnumsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: JsonEnumsCommandOutput) => void), cb?: (err: any, data?: JsonEnumsCommandOutput) => void ): Promise<JsonEnumsCommandOutput> | void { const command = new JsonEnumsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * This operation uses unions for inputs and outputs. */ public jsonUnions(args: JsonUnionsCommandInput, options?: __HttpHandlerOptions): Promise<JsonUnionsCommandOutput>; public jsonUnions(args: JsonUnionsCommandInput, cb: (err: any, data?: JsonUnionsCommandOutput) => void): void; public jsonUnions( args: JsonUnionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: JsonUnionsCommandOutput) => void ): void; public jsonUnions( args: JsonUnionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: JsonUnionsCommandOutput) => void), cb?: (err: any, data?: JsonUnionsCommandOutput) => void ): Promise<JsonUnionsCommandOutput> | void { const command = new JsonUnionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } public kitchenSinkOperation( args: KitchenSinkOperationCommandInput, options?: __HttpHandlerOptions ): Promise<KitchenSinkOperationCommandOutput>; public kitchenSinkOperation( args: KitchenSinkOperationCommandInput, cb: (err: any, data?: KitchenSinkOperationCommandOutput) => void ): void; public kitchenSinkOperation( args: KitchenSinkOperationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: KitchenSinkOperationCommandOutput) => void ): void; public kitchenSinkOperation( args: KitchenSinkOperationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: KitchenSinkOperationCommandOutput) => void), cb?: (err: any, data?: KitchenSinkOperationCommandOutput) => void ): Promise<KitchenSinkOperationCommandOutput> | void { const command = new KitchenSinkOperationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } public nullOperation( args: NullOperationCommandInput, options?: __HttpHandlerOptions ): Promise<NullOperationCommandOutput>; public nullOperation( args: NullOperationCommandInput, cb: (err: any, data?: NullOperationCommandOutput) => void ): void; public nullOperation( args: NullOperationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: NullOperationCommandOutput) => void ): void; public nullOperation( args: NullOperationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: NullOperationCommandOutput) => void), cb?: (err: any, data?: NullOperationCommandOutput) => void ): Promise<NullOperationCommandOutput> | void { const command = new NullOperationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } public operationWithOptionalInputOutput( args: OperationWithOptionalInputOutputCommandInput, options?: __HttpHandlerOptions ): Promise<OperationWithOptionalInputOutputCommandOutput>; public operationWithOptionalInputOutput( args: OperationWithOptionalInputOutputCommandInput, cb: (err: any, data?: OperationWithOptionalInputOutputCommandOutput) => void ): void; public operationWithOptionalInputOutput( args: OperationWithOptionalInputOutputCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: OperationWithOptionalInputOutputCommandOutput) => void ): void; public operationWithOptionalInputOutput( args: OperationWithOptionalInputOutputCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: OperationWithOptionalInputOutputCommandOutput) => void), cb?: (err: any, data?: OperationWithOptionalInputOutputCommandOutput) => void ): Promise<OperationWithOptionalInputOutputCommandOutput> | void { const command = new OperationWithOptionalInputOutputCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * This example serializes an inline document as part of the payload. */ public putAndGetInlineDocuments( args: PutAndGetInlineDocumentsCommandInput, options?: __HttpHandlerOptions ): Promise<PutAndGetInlineDocumentsCommandOutput>; public putAndGetInlineDocuments( args: PutAndGetInlineDocumentsCommandInput, cb: (err: any, data?: PutAndGetInlineDocumentsCommandOutput) => void ): void; public putAndGetInlineDocuments( args: PutAndGetInlineDocumentsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutAndGetInlineDocumentsCommandOutput) => void ): void; public putAndGetInlineDocuments( args: PutAndGetInlineDocumentsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutAndGetInlineDocumentsCommandOutput) => void), cb?: (err: any, data?: PutAndGetInlineDocumentsCommandOutput) => void ): Promise<PutAndGetInlineDocumentsCommandOutput> | void { const command = new PutAndGetInlineDocumentsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } public simpleScalarProperties( args: SimpleScalarPropertiesCommandInput, options?: __HttpHandlerOptions ): Promise<SimpleScalarPropertiesCommandOutput>; public simpleScalarProperties( args: SimpleScalarPropertiesCommandInput, cb: (err: any, data?: SimpleScalarPropertiesCommandOutput) => void ): void; public simpleScalarProperties( args: SimpleScalarPropertiesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: SimpleScalarPropertiesCommandOutput) => void ): void; public simpleScalarProperties( args: SimpleScalarPropertiesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SimpleScalarPropertiesCommandOutput) => void), cb?: (err: any, data?: SimpleScalarPropertiesCommandOutput) => void ): Promise<SimpleScalarPropertiesCommandOutput> | void { const command = new SimpleScalarPropertiesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
* marked - a markdown parser * Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked */ import React from "react" import users from "../../pages/users" import Prism from "../Prism/index" import Header from "./Header" import MiniGraphiQL from "./MiniGraphiQL" import { StarWarsSchema } from "./swapiSchema" import { UsersSchema } from './usersSchema'; export default function Marked(props: { children: string }) { return <div>{props.children && marked(props.children, props)}</div> } /** * Block-Level Grammar */ var block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: noop, hr: /^( *[-*_]){3,} *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, nptable: noop, lheading: /^([^\n]+)\n *(=|-){3,} *\n*/, blockquote: /^( *>[^\n]+(\n[^\n]+)*\n*)+/, list: /^( *)(bull) [\s\S]+?(?:hr|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/, def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, table: noop, paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, text: /^[^\n]+/, } block.bullet = /(?:[*+-]|\d+\.)/ block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/ block.item = replace(block.item, "gm")(/bull/g, block.bullet)() block.list = replace(block.list)(/bull/g, block.bullet)( "hr", /\n+(?=(?: *[-*_]){3,} *(?:\n+|$))/ )() block._tag = "(?!(?:" + "a|em|strong|small|s|cite|q|dfn|abbr|data|time|code" + "|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo" + "|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|@)\\b" block.html = replace(block.html)("comment", /<!--[\s\S]*?-->/)( "closed", /<(tag)[\s\S]+?<\/\1>/ )("closing", /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g, block._tag)() block.paragraph = replace(block.paragraph)("hr", block.hr)( "heading", block.heading )("lheading", block.lheading)("blockquote", block.blockquote)( "tag", "<" + block._tag )("def", block.def)() /** * Normal Block Grammar */ block.normal = merge({}, block) /** * GFM Block Grammar */ block.gfm = merge({}, block.normal, { //fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, fences: /^ *(`{3,}|~{3,}) *([^\s{]+)?(?: *\{ *((?:\d+(?: *- *\d+)?(?: *, *\d+(?: *- *\d+)?)*) *)?\})? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, paragraph: /^/, }) block.gfm.paragraph = replace(block.paragraph)( "(?!", "(?!" + block.gfm.fences.source.replace("\\1", "\\2") + "|" )() /** * GFM + Tables Block Grammar */ block.tables = merge({}, block.gfm, { nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/, }) /** * Block Lexer */ function Lexer(options) { this.tokens = [] this.tokens.links = {} this.options = options || marked.defaults this.rules = block.normal if (this.options.gfm) { if (this.options.tables) { this.rules = block.tables } else { this.rules = block.gfm } } } /** * Expose Block Rules */ Lexer.rules = block /** * Static Lex Method */ Lexer.lex = function (src, options) { var lexer = new Lexer(options) return lexer.lex(src) } /** * Preprocessing */ Lexer.prototype.lex = function (src) { src = src .replace(/\r\n|\r/g, "\n") .replace(/\t/g, " ") .replace(/\u00a0/g, " ") .replace(/\u2424/g, "\n") return this.token(src, true) } /** * Lexing */ Lexer.prototype.token = function (src, top) { var src = src.replace(/^ +$/gm, ""), next, loose, cap, bull, b, item, space, i, l while (src) { // newline if ((cap = this.rules.newline.exec(src))) { src = src.substring(cap[0].length) if (cap[0].length > 1) { this.tokens.push({ type: "space", }) } } // code if ((cap = this.rules.code.exec(src))) { src = src.substring(cap[0].length) cap = cap[0].replace(/^ {4}/gm, "") this.tokens.push({ type: "code", text: !this.options.pedantic ? cap.replace(/\n+$/, "") : cap, }) continue } // fences (gfm) if ((cap = this.rules.fences.exec(src))) { src = src.substring(cap[0].length) this.tokens.push({ type: "code", lang: cap[2], line: cap[3], text: cap[4], }) continue } // heading if ((cap = this.rules.heading.exec(src))) { src = src.substring(cap[0].length) this.tokens.push({ type: "heading", depth: cap[1].length, text: cap[2], }) continue } // table no leading pipe (gfm) if (top && (cap = this.rules.nptable.exec(src))) { src = src.substring(cap[0].length) item = { type: "table", header: cap[1].replace(/^ *| *\| *$/g, "").split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: cap[3].replace(/\n$/, "").split("\n"), } for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = "right" } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = "center" } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = "left" } else { item.align[i] = null } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i].split(/ *\| */) } this.tokens.push(item) continue } // lheading if ((cap = this.rules.lheading.exec(src))) { src = src.substring(cap[0].length) this.tokens.push({ type: "heading", depth: cap[2] === "=" ? 1 : 2, text: cap[1], }) continue } // hr if ((cap = this.rules.hr.exec(src))) { src = src.substring(cap[0].length) this.tokens.push({ type: "hr", }) continue } // blockquote if ((cap = this.rules.blockquote.exec(src))) { src = src.substring(cap[0].length) this.tokens.push({ type: "blockquote_start", }) cap = cap[0].replace(/^ *> ?/gm, "") // Pass `top` to keep the current // "toplevel" state. This is exactly // how markdown.pl works. this.token(cap, top) this.tokens.push({ type: "blockquote_end", }) continue } // list if ((cap = this.rules.list.exec(src))) { src = src.substring(cap[0].length) bull = cap[2] this.tokens.push({ type: "list_start", ordered: bull.length > 1, }) // Get each top-level item. cap = cap[0].match(this.rules.item) next = false l = cap.length i = 0 for (; i < l; i++) { item = cap[i] // Remove the list item's bullet // so it is seen as the next token. space = item.length item = item.replace(/^ *([*+-]|\d+\.) +/, "") // Outdent whatever the // list item contains. Hacky. if (~item.indexOf("\n ")) { space -= item.length item = !this.options.pedantic ? item.replace(new RegExp("^ {1," + space + "}", "gm"), "") : item.replace(/^ {1,4}/gm, "") } // Determine whether the next list item belongs here. // Backpedal if it does not belong in this list. if (this.options.smartLists && i !== l - 1) { b = block.bullet.exec(cap[i + 1])[0] if (bull !== b && !(bull.length > 1 && b.length > 1)) { src = cap.slice(i + 1).join("\n") + src i = l - 1 } } // Determine whether item is loose or not. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ // for discount behavior. loose = next || /\n\n(?!\s*$)/.test(item) if (i !== l - 1) { next = item[item.length - 1] === "\n" if (!loose) loose = next } this.tokens.push({ type: loose ? "loose_item_start" : "list_item_start", }) // Recurse. this.token(item, false) this.tokens.push({ type: "list_item_end", }) } this.tokens.push({ type: "list_end", }) continue } // html if ((cap = this.rules.html.exec(src))) { src = src.substring(cap[0].length) this.tokens.push({ type: this.options.sanitize ? "paragraph" : "html", pre: cap[1] === "pre" || cap[1] === "script", text: cap[0], }) continue } // def if (top && (cap = this.rules.def.exec(src))) { src = src.substring(cap[0].length) this.tokens.links[cap[1].toLowerCase()] = { href: cap[2], title: cap[3], } continue } // table (gfm) if (top && (cap = this.rules.table.exec(src))) { src = src.substring(cap[0].length) item = { type: "table", header: cap[1].replace(/^ *| *\| *$/g, "").split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: cap[3].replace(/(?: *\| *)?\n$/, "").split("\n"), } for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = "right" } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = "center" } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = "left" } else { item.align[i] = null } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i] .replace(/^ *\| *| *\| *$/g, "") .split(/ *\| */) } this.tokens.push(item) continue } // top-level paragraph if (top && (cap = this.rules.paragraph.exec(src))) { src = src.substring(cap[0].length) this.tokens.push({ type: "paragraph", text: cap[1][cap[1].length - 1] === "\n" ? cap[1].slice(0, -1) : cap[1], }) continue } // text if ((cap = this.rules.text.exec(src))) { // Top-level should never reach here. src = src.substring(cap[0].length) this.tokens.push({ type: "text", text: cap[0], }) continue } if (src) { throw new Error("Infinite loop on byte: " + src.charCodeAt(0)) } } return this.tokens } /** * Inline-Level Grammar */ var inline = { escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, url: noop, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, del: noop, text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/, } inline._inside = /(?:\[[^\]]*\]|[^\]]|\](?=[^\[]*\]))*/ inline._href = /\s*<?([^\s]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/ inline.link = replace(inline.link)("inside", inline._inside)( "href", inline._href )() inline.reflink = replace(inline.reflink)("inside", inline._inside)() /** * Normal Inline Grammar */ inline.normal = merge({}, inline) /** * Pedantic Inline Grammar */ inline.pedantic = merge({}, inline.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/, }) /** * GFM Inline Grammar */ inline.gfm = merge({}, inline.normal, { escape: replace(inline.escape)("])", "~|])")(), url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text: replace(inline.text)("]|", "~]|")("|", "|https?://|")(), }) /** * GFM + Line Breaks Inline Grammar */ inline.breaks = merge({}, inline.gfm, { br: replace(inline.br)("{2,}", "*")(), text: replace(inline.gfm.text)("{2,}", "*")(), }) /** * Inline Lexer & Compiler */ function InlineLexer(links, options) { this.options = options || marked.defaults this.links = links this.rules = inline.normal if (!this.links) { throw new Error("Tokens array requires a `links` property.") } if (this.options.gfm) { if (this.options.breaks) { this.rules = inline.breaks } else { this.rules = inline.gfm } } else if (this.options.pedantic) { this.rules = inline.pedantic } } /** * Expose Inline Rules */ InlineLexer.rules = inline /** * Static Lexing/Compiling Method */ InlineLexer.output = function (src, links, options) { var inline = new InlineLexer(links, options) return inline.output(src) } /** * Lexing/Compiling */ InlineLexer.prototype.output = function (src) { var out = [], link, text, href, cap while (src) { // escape if ((cap = this.rules.escape.exec(src))) { src = src.substring(cap[0].length) out.push(cap[1]) continue } // autolink if ((cap = this.rules.autolink.exec(src))) { src = src.substring(cap[0].length) if (cap[2] === "@") { text = cap[1][6] === ":" ? cap[1].substring(7) : cap[1] href = "mailto:" + text } else { text = cap[1] href = text } out.push(React.createElement("a", { href: this.sanitizeUrl(href), key:href }, text)) continue } // url (gfm) if ((cap = this.rules.url.exec(src))) { src = src.substring(cap[0].length) text = cap[1] href = text out.push(React.createElement("a", { href: this.sanitizeUrl(href), key:href }, text)) continue } // tag if ((cap = this.rules.tag.exec(src))) { src = src.substring(cap[0].length) // TODO(alpert): Don't escape if sanitize is false out.push(cap[0]) continue } // link if ((cap = this.rules.link.exec(src))) { src = src.substring(cap[0].length) out.push( this.outputLink(cap, { href: cap[2], title: cap[3], }) ) continue } // reflink, nolink if ( (cap = this.rules.reflink.exec(src)) || (cap = this.rules.nolink.exec(src)) ) { src = src.substring(cap[0].length) link = (cap[2] || cap[1]).replace(/\s+/g, " ") link = this.links[link.toLowerCase()] if (!link || !link.href) { out.push.apply(out, this.output(cap[0][0])) src = cap[0].substring(1) + src continue } out.push(this.outputLink(cap, link)) continue } // strong if ((cap = this.rules.strong.exec(src))) { src = src.substring(cap[0].length) out.push( React.createElement( "strong", { key: src.length }, this.output(cap[2] || cap[1]) ) ) continue } // em if ((cap = this.rules.em.exec(src))) { src = src.substring(cap[0].length) out.push( React.createElement( "em", { key: src.length }, this.output(cap[2] || cap[1]) ) ) continue } // code if ((cap = this.rules.code.exec(src))) { src = src.substring(cap[0].length) out.push(React.createElement("code", { key: src.length }, cap[2])) continue } // br if ((cap = this.rules.br.exec(src))) { src = src.substring(cap[0].length) out.push(React.createElement("br", { key: src.length }, null)) continue } // del (gfm) if ((cap = this.rules.del.exec(src))) { src = src.substring(cap[0].length) out.push( React.createElement("del", { key: src.length }, this.output(cap[1])) ) continue } // text if ((cap = this.rules.text.exec(src))) { src = src.substring(cap[0].length) out.push(this.smartypants(cap[0])) continue } if (src) { throw new Error("Infinite loop on byte: " + src.charCodeAt(0)) } } return out } /** * Sanitize a URL for a link or image */ InlineLexer.prototype.sanitizeUrl = function (url) { if (this.options.sanitize) { try { var prot = decodeURIComponent(url) .replace(/[^A-Za-z0-9:]/g, "") .toLowerCase() if (prot.indexOf("javascript:") === 0) { return "#" } } catch (e) { return "#" } } return url } /** * Compile Link */ InlineLexer.prototype.outputLink = function (cap, link) { if (cap[0][0] !== "!") { var shouldOpenInNewWindow = link.href.charAt(0) !== "/" && link.href.charAt(0) !== "#" return React.createElement( "a", { href: this.sanitizeUrl(link.href), title: link.title, target: shouldOpenInNewWindow ? "_blank" : null, rel: shouldOpenInNewWindow ? "nofollow noopener noreferrer" : null, key: link.href, }, this.output(cap[1]) ) } else { return React.createElement( "img", { src: this.sanitizeUrl(link.href), alt: cap[1], title: link.title, key: link.href, }, null ) } } /** * Smartypants Transformations */ InlineLexer.prototype.smartypants = function (text) { if (!this.options.smartypants) return text return text .replace(/--/g, "\u2014") .replace(/'([^']*)'/g, "\u2018$1\u2019") .replace(/"([^"]*)"/g, "\u201C$1\u201D") .replace(/\.{3}/g, "\u2026") } /** * Parsing & Compiling */ function Parser(options) { this.tokens = [] this.token = null this.options = options || marked.defaults this.usedSlugs = {} } /** * Static Parse Method */ Parser.parse = function (src, options) { var parser = new Parser(options) return parser.parse(src) } /** * Parse Loop */ Parser.prototype.parse = function (src) { this.inline = new InlineLexer(src.links, this.options) this.tokens = src.reverse() var out = [] while (this.next()) { out.push(this.tok()) } return out } /** * Next Token */ Parser.prototype.next = function () { return (this.token = this.tokens.pop()) } /** * Preview Next Token */ Parser.prototype.peek = function () { return this.tokens[this.tokens.length - 1] || 0 } /** * Parse Text Tokens */ Parser.prototype.parseText = function () { var body = this.token.text while (this.peek().type === "text") { body += "\n" + this.next().text } return this.inline.output(body) } /** * Parse Current Token */ Parser.prototype.tok = function () { switch (this.token.type) { case "space": { return [] } case "hr": { return React.createElement("hr", { key: this.tokens.length }, null) } case "heading": { return ( <Header url={this.options.url} level={this.token.depth} toSlug={this.token.text} usedSlugs={this.usedSlugs} key={this.tokens.length} > {this.inline.output(this.token.text)} </Header> ) } case "code": { if (this.token.lang === "graphql") { var lines = this.token.text.split("\n") var firstLine = lines.shift().match(/^\s*#\s*({.*})$/) if (firstLine) { var metaData try { metaData = JSON.parse(firstLine[1]) } catch (e) { console.error("Invalid Metadata JSON:", firstLine[1]) } if (metaData) { var query = lines.join("\n") var variables = metaData.variables ? JSON.stringify(metaData.variables, null, 2) : "" const schemaMap = { StarWars: StarWarsSchema, Users: UsersSchema, } const schema = schemaMap[metaData.schema || 'StarWars']; return ( <MiniGraphiQL schema={schema} query={query} variables={variables} key={this.tokens.length} /> ) } } } return ( <Prism language={this.token.lang} code={this.token.text} key={this.tokens.length} /> ) } case "table": { var table = [], body = [], row = [], heading, i, cells, j // header for (i = 0; i < this.token.header.length; i++) { heading = this.inline.output(this.token.header[i]) row.push( React.createElement( "th", this.token.align[i] ? { style: { textAlign: this.token.align[i] },key:i } : {key:i}, heading ) ) } table.push( React.createElement("thead", { key: this.tokens.length }, React.createElement("tr", null, row)) ) // body for (i = 0; i < this.token.cells.length; i++) { row = [] cells = this.token.cells[i] for (j = 0; j < cells.length; j++) { row.push( React.createElement( "td", this.token.align[j] ? { style: { textAlign: this.token.align[j],key:i } } : {key:i}, this.inline.output(cells[j]) ) ) } body.push(React.createElement("tr", {key:i}, row)) } table.push(React.createElement("thead", {key:i}, body)) return React.createElement("table", null, table) } case "blockquote_start": { var body = [] while (this.next().type !== "blockquote_end") { body.push(this.tok()) } return React.createElement( "blockquote", { key: this.tokens.length }, body ) } case "list_start": { var type = this.token.ordered ? "ol" : "ul", body = [] while (this.next().type !== "list_end") { body.push(this.tok()) } return React.createElement(type, { key: this.tokens.length }, body) } case "list_item_start": { var body = [] while (this.next().type !== "list_item_end") { body.push(this.token.type === "text" ? this.parseText() : this.tok()) } return React.createElement("li", { key: this.tokens.length }, body) } case "loose_item_start": { var body = [] while (this.next().type !== "list_item_end") { body.push(this.tok()) } return React.createElement("li", { key: this.tokens.length }, body) } case "html": { return React.createElement("div", { dangerouslySetInnerHTML: { __html: this.token.text, }, key: this.tokens.length, }) } case "paragraph": { return this.options.paragraphFn ? this.options.paragraphFn.call( null, this.inline.output(this.token.text) ) : React.createElement( "p", { key: this.tokens.length }, this.inline.output(this.token.text) ) } case "text": { return this.options.paragraphFn ? this.options.paragraphFn.call(null, this.parseText()) : React.createElement( "p", { key: this.tokens.length }, this.parseText() ) } } } /** * Helpers */ function escape(html, encode) { return html .replace(!encode ? /&(?!#?\w+;)/g : /&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#39;") } function replace(regex, opt) { regex = regex.source opt = opt || "" return function self(name, val) { if (!name) return new RegExp(regex, opt) val = val.source || val val = val.replace(/(^|[^\[])\^/g, "$1") regex = regex.replace(name, val) return self } } function noop() {} noop.exec = noop function merge(obj) { var i = 1, target, key for (; i < arguments.length; i++) { target = arguments[i] for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key] } } } return obj } /** * Marked */ function marked(src, opt, callback) { if (callback || typeof opt === "function") { if (!callback) { callback = opt opt = null } if (opt) opt = merge({}, marked.defaults, opt) var highlight = opt.highlight, tokens, pending, i = 0 try { tokens = Lexer.lex(src, opt) } catch (e) { return callback(e) } pending = tokens.length var done = function (hi) { var out, err if (hi !== true) { delete opt.highlight } try { out = Parser.parse(tokens, opt) } catch (e) { err = e } opt.highlight = highlight return err ? callback(err) : callback(null, out) } if (!highlight || highlight.length < 3) { return done(true) } if (!pending) return done() for (; i < tokens.length; i++) { ;(function (token) { if (token.type !== "code") { return --pending || done() } return highlight(token.text, token.lang, function (err, code) { if (code == null || code === token.text) { return --pending || done() } token.text = code token.escaped = true --pending || done() }) })(tokens[i]) } return } try { if (opt) opt = merge({}, marked.defaults, opt) return Parser.parse(Lexer.lex(src, opt), opt) } catch (e) { e.message += "\nPlease report this to https://github.com/chjj/marked." if ((opt || marked.defaults).silent) { return [ React.createElement("p", null, "An error occurred:"), React.createElement("pre", null, e.message), ] } throw e } } /** * Options */ marked.options = marked.setOptions = function (opt) { merge(marked.defaults, opt) return marked } marked.defaults = { gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: false, silent: false, highlight: null, langPrefix: "lang-", smartypants: false, paragraphFn: null, } /** * Expose */ marked.Parser = Parser marked.parser = Parser.parse marked.Lexer = Lexer marked.lexer = Lexer.lex marked.InlineLexer = InlineLexer marked.inlineLexer = InlineLexer.output marked.parse = marked
the_stack
import '../test/setup'; import { expect } from 'chai'; import { spy, stub } from 'sinon'; import { setTokenAutoRefreshEnabled, initializeAppCheck, getToken, onTokenChanged } from './api'; import { FAKE_SITE_KEY, getFullApp, getFakeApp, getFakeGreCAPTCHA, getFakeAppCheck, removegreCAPTCHAScriptsOnPage } from '../test/util'; import { clearState, getState } from './state'; import * as reCAPTCHA from './recaptcha'; import * as util from './util'; import * as logger from './logger'; import * as client from './client'; import * as storage from './storage'; import * as internalApi from './internal-api'; import * as indexeddb from './indexeddb'; import * as debug from './debug'; import { deleteApp, FirebaseApp } from '@firebase/app'; import { CustomProvider, ReCaptchaV3Provider } from './providers'; import { AppCheckService } from './factory'; import { AppCheckToken } from './public-types'; import { getDebugToken } from './debug'; describe('api', () => { let app: FirebaseApp; beforeEach(() => { app = getFullApp(); stub(util, 'getRecaptcha').returns(getFakeGreCAPTCHA()); }); afterEach(() => { clearState(); removegreCAPTCHAScriptsOnPage(); return deleteApp(app); }); describe('initializeAppCheck()', () => { it('can only be called once (if given different provider classes)', () => { initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); expect(() => initializeAppCheck(app, { provider: new CustomProvider({ getToken: () => Promise.resolve({ token: 'mm' } as AppCheckToken) }) }) ).to.throw(/appCheck\/already-initialized/); }); it('can only be called once (if given different ReCaptchaV3Providers)', () => { initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); expect(() => initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY + 'X') }) ).to.throw(/appCheck\/already-initialized/); }); it('can only be called once (if given different CustomProviders)', () => { initializeAppCheck(app, { provider: new CustomProvider({ getToken: () => Promise.resolve({ token: 'ff' } as AppCheckToken) }) }); expect(() => initializeAppCheck(app, { provider: new CustomProvider({ getToken: () => Promise.resolve({ token: 'gg' } as AppCheckToken) }) }) ).to.throw(/appCheck\/already-initialized/); }); it('can be called multiple times (if given equivalent ReCaptchaV3Providers)', () => { const appCheckInstance = initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); expect( initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }) ).to.equal(appCheckInstance); }); it('can be called multiple times (if given equivalent CustomProviders)', () => { const appCheckInstance = initializeAppCheck(app, { provider: new CustomProvider({ getToken: () => Promise.resolve({ token: 'ff' } as AppCheckToken) }) }); expect( initializeAppCheck(app, { provider: new CustomProvider({ getToken: () => Promise.resolve({ token: 'ff' } as AppCheckToken) }) }) ).to.equal(appCheckInstance); }); it('starts debug mode on first call', async () => { let token: string = ''; const fakeWrite = (tokenToWrite: string): Promise<void> => { token = tokenToWrite; return Promise.resolve(); }; stub(indexeddb, 'writeDebugTokenToIndexedDB').callsFake(fakeWrite); stub(indexeddb, 'readDebugTokenFromIndexedDB').resolves(token); const consoleStub = stub(console, 'log'); self.FIREBASE_APPCHECK_DEBUG_TOKEN = true; initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); // Ensure getDebugToken() call inside `initializeAppCheck()` // has time to resolve, and double check its value matches that // written to indexedDB. expect(await getDebugToken()).to.equal(token); expect(consoleStub.args[0][0]).to.include(token); self.FIREBASE_APPCHECK_DEBUG_TOKEN = undefined; }); it('does not call initializeDebugMode on second call', async () => { self.FIREBASE_APPCHECK_DEBUG_TOKEN = 'abcdefg'; const consoleStub = stub(console, 'log'); const initializeDebugModeSpy = spy(debug, 'initializeDebugMode'); // First call, should call initializeDebugMode() initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); expect(initializeDebugModeSpy).to.be.called; initializeDebugModeSpy.resetHistory(); // Second call, should not call initializeDebugMode() initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); const token = await getDebugToken(); expect(token).to.equal('abcdefg'); // Two console logs of the token, for each initializeAppCheck call. expect(consoleStub.args[0][0]).to.include(token); expect(consoleStub.args[1][0]).to.include(token); expect(consoleStub.args[1][0]).to.equal(consoleStub.args[0][0]); expect(initializeDebugModeSpy).to.not.be.called; self.FIREBASE_APPCHECK_DEBUG_TOKEN = undefined; }); it('initialize reCAPTCHA when a ReCaptchaV3Provider is provided', () => { const initReCAPTCHAStub = stub(reCAPTCHA, 'initialize').returns( Promise.resolve({} as any) ); initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); expect(initReCAPTCHAStub).to.have.been.calledWithExactly( app, FAKE_SITE_KEY ); }); it('sets activated to true', () => { expect(getState(app).activated).to.equal(false); initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); expect(getState(app).activated).to.equal(true); }); it('isTokenAutoRefreshEnabled value defaults to global setting', () => { app.automaticDataCollectionEnabled = false; initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY) }); expect(getState(app).isTokenAutoRefreshEnabled).to.equal(false); }); it('sets isTokenAutoRefreshEnabled correctly, overriding global setting', () => { app.automaticDataCollectionEnabled = false; initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY), isTokenAutoRefreshEnabled: true }); expect(getState(app).isTokenAutoRefreshEnabled).to.equal(true); }); }); describe('setTokenAutoRefreshEnabled()', () => { it('sets isTokenAutoRefreshEnabled correctly', () => { const app = getFakeApp({ automaticDataCollectionEnabled: false }); const appCheck = getFakeAppCheck(app); setTokenAutoRefreshEnabled(appCheck, true); expect(getState(app).isTokenAutoRefreshEnabled).to.equal(true); }); }); describe('getToken()', () => { it('getToken() calls the internal getToken() function', async () => { const app = getFakeApp({ automaticDataCollectionEnabled: true }); const appCheck = getFakeAppCheck(app); const internalGetToken = stub(internalApi, 'getToken').resolves({ token: 'a-token-string' }); await getToken(appCheck, true); expect(internalGetToken).to.be.calledWith(appCheck, true); }); it('getToken() throws errors returned with token', async () => { const app = getFakeApp({ automaticDataCollectionEnabled: true }); const appCheck = getFakeAppCheck(app); // If getToken() errors, it returns a dummy token with an error field // instead of throwing. stub(internalApi, 'getToken').resolves({ token: 'a-dummy-token', error: Error('there was an error') }); await expect(getToken(appCheck, true)).to.be.rejectedWith( 'there was an error' ); }); }); describe('onTokenChanged()', () => { it('Listeners work when using top-level parameters pattern', async () => { const appCheck = initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY), isTokenAutoRefreshEnabled: true }); const fakeRecaptchaToken = 'fake-recaptcha-token'; const fakeRecaptchaAppCheckToken = { token: 'fake-recaptcha-app-check-token', expireTimeMillis: 123, issuedAtTimeMillis: 0 }; stub(reCAPTCHA, 'getToken').returns(Promise.resolve(fakeRecaptchaToken)); stub(client, 'exchangeToken').returns( Promise.resolve(fakeRecaptchaAppCheckToken) ); stub(storage, 'writeTokenToStorage').returns(Promise.resolve(undefined)); const listener1 = stub().throws(new Error()); const listener2 = spy(); const errorFn1 = spy(); const errorFn2 = spy(); const unsubscribe1 = onTokenChanged(appCheck, listener1, errorFn1); const unsubscribe2 = onTokenChanged(appCheck, listener2, errorFn2); expect(getState(app).tokenObservers.length).to.equal(2); await internalApi.getToken(appCheck as AppCheckService); expect(listener1).to.be.called; expect(listener2).to.be.calledWith({ token: fakeRecaptchaAppCheckToken.token }); // onError should not be called on listener errors. expect(errorFn1).to.not.be.called; expect(errorFn2).to.not.be.called; unsubscribe1(); unsubscribe2(); expect(getState(app).tokenObservers.length).to.equal(0); }); it('Listeners work when using Observer pattern', async () => { const appCheck = initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY), isTokenAutoRefreshEnabled: true }); const fakeRecaptchaToken = 'fake-recaptcha-token'; const fakeRecaptchaAppCheckToken = { token: 'fake-recaptcha-app-check-token', expireTimeMillis: 123, issuedAtTimeMillis: 0 }; stub(reCAPTCHA, 'getToken').returns(Promise.resolve(fakeRecaptchaToken)); stub(client, 'exchangeToken').returns( Promise.resolve(fakeRecaptchaAppCheckToken) ); stub(storage, 'writeTokenToStorage').returns(Promise.resolve(undefined)); const listener1 = stub().throws(new Error()); const listener2 = spy(); const errorFn1 = spy(); const errorFn2 = spy(); /** * Reverse the order of adding the failed and successful handler, for extra * testing. */ const unsubscribe2 = onTokenChanged(appCheck, { next: listener2, error: errorFn2 }); const unsubscribe1 = onTokenChanged(appCheck, { next: listener1, error: errorFn1 }); expect(getState(app).tokenObservers.length).to.equal(2); await internalApi.getToken(appCheck as AppCheckService); expect(listener1).to.be.called; expect(listener2).to.be.calledWith({ token: fakeRecaptchaAppCheckToken.token }); // onError should not be called on listener errors. expect(errorFn1).to.not.be.called; expect(errorFn2).to.not.be.called; unsubscribe1(); unsubscribe2(); expect(getState(app).tokenObservers.length).to.equal(0); }); it('onError() catches token errors', async () => { stub(logger.logger, 'error'); const appCheck = initializeAppCheck(app, { provider: new ReCaptchaV3Provider(FAKE_SITE_KEY), isTokenAutoRefreshEnabled: false }); const fakeRecaptchaToken = 'fake-recaptcha-token'; stub(reCAPTCHA, 'getToken').returns(Promise.resolve(fakeRecaptchaToken)); stub(client, 'exchangeToken').rejects('exchange error'); stub(storage, 'writeTokenToStorage').returns(Promise.resolve(undefined)); const listener1 = spy(); const errorFn1 = spy(); const unsubscribe1 = onTokenChanged(appCheck, listener1, errorFn1); await internalApi.getToken(appCheck as AppCheckService); expect(getState(app).tokenObservers.length).to.equal(1); expect(errorFn1).to.be.calledOnce; expect(errorFn1.args[0][0].name).to.include('exchange error'); unsubscribe1(); expect(getState(app).tokenObservers.length).to.equal(0); }); }); });
the_stack
import classNames from 'classnames' import qsa from 'dom-helpers/querySelectorAll' import PropTypes from 'prop-types' import React, { useCallback, useRef, useState } from 'react' import { useUncontrolled } from 'uncontrollable' import Button from './Button' import DateTimePartInput from './DateTimePartInput' import { times } from './Icon' import Widget, { WidgetProps } from './Widget' import dates from './dates' import useFocusManager from './useFocusManager' type Meridiem = 'AM' | 'PM' interface DateParts { era: Meridiem hours?: number minutes?: number seconds?: number milliseconds?: number } interface TimeParts { meridiem: Meridiem hours?: number minutes?: number seconds?: number milliseconds?: number } type TimePart = keyof TimeParts const selectTextRange = (el: HTMLInputElement | HTMLDivElement) => { if (el instanceof HTMLInputElement) return el.select() const range = document.createRange() range.selectNodeContents(el) const selection = window.getSelection() if (selection) { selection.removeAllRanges() selection.addRange(range) } } // prettier-ignore const isEmptyValue = (p: TimeParts, precision: TimePart) => p.hours == null && p.minutes == null && ((precision != 'seconds' && precision !== 'milliseconds') || p.seconds == null) && (precision !== 'milliseconds' || p.milliseconds == null); // prettier-ignore const isPartialValue = (p: TimeParts, precision: TimePart) => p.hours == null || p.minutes == null || ((precision === 'seconds' || precision === 'milliseconds') && p.seconds == null) || (precision === 'milliseconds' && p.milliseconds == null); const getValueParts = ( value?: Date | null, use12HourClock?: boolean, ): TimeParts => { let hours, minutes, seconds, milliseconds let meridiem: Meridiem = 'AM' if (value) { hours = value.getHours() if (use12HourClock) { meridiem = hours < 12 ? 'AM' : 'PM' hours = hours % 12 || 12 } minutes = value.getMinutes() seconds = value.getSeconds() milliseconds = value.getMilliseconds() } return { hours, minutes, seconds, milliseconds, meridiem } } const TEST_VALID = { hours: /^([1]?[0-9]|2[0-3])$/, hours12: /^(1[0-2]|0?[1-9])$/, minutes: /^([0-5]?\d)$/, seconds: /^([0-5]?\d)$/, milliseconds: /^(\d{1,3})$/, } const TEST_COMPLETE = { hours: /^([3-9]|\d{2})$/, hours12: /^(\d{2}|[2-9])$/, minutes: /^(d{2}|[6-9])$/, seconds: /^(d{2}|[6-9])$/, milliseconds: /^(\d{3})$/, } function testPart( value: string, part: TimePart, use12HourClock: boolean, tests: Record<keyof typeof TEST_VALID, RegExp>, ) { const key = part === 'hours' && use12HourClock ? 'hours12' : (part as keyof typeof tests) return tests[key].test(value) } const isValid = (value: string, part: TimePart, use12HourClock: boolean) => testPart(value, part, use12HourClock, TEST_VALID) const isComplete = (value: string, part: TimePart, use12HourClock: boolean) => testPart(value, part, use12HourClock, TEST_COMPLETE) export interface TimeInputProps extends Omit<WidgetProps, 'value' | 'onChange'> { value?: Date | null onChange?: (date: Date | null, ctx?: any) => void datePart?: Date use12HourClock?: boolean padValues?: boolean emptyCharacter?: string noClearButton?: boolean disabled?: boolean readOnly?: boolean precision: 'minutes' | 'seconds' | 'milliseconds' hoursAddon?: React.ReactNode minutesAddon?: React.ReactNode secondsAddon?: React.ReactNode millisecondsAddon?: React.ReactNode } const propTypes = { /** * @example ['valuePicker', [ ['new Date()'] ]] */ value: PropTypes.instanceOf(Date), /** * @example ['onChangePicker', [ ['new Date()'] ]] */ onChange: PropTypes.func, /** * The default date used to construct a new time when the `value` is empty * * @default new Date() **/ datePart: PropTypes.instanceOf(Date), /** * Use a 12 hour clock (with AM/PM) instead of 24 hour one. * The configured localizer may provide a default value . **/ use12HourClock: PropTypes.bool, /** Time part values will be padded by `0` */ padValues: PropTypes.bool, /** The string character used to pad empty, or cleared values */ emptyCharacter: PropTypes.string, /** Hide the input clear button */ noClearButton: PropTypes.bool, /** * @example ['disabled', ['new Date()']] */ disabled: PropTypes.bool, /** * @example ['readOnly', ['new Date()']] */ readOnly: PropTypes.bool, /** Controls how precise of a time can be input **/ precision: PropTypes.oneOf(['minutes', 'seconds', 'milliseconds']).isRequired, /** * The seperator between hours and minutes * @default ':' */ hoursAddon: PropTypes.node, /** * The seperator between hours and minutes * @default ':' */ minutesAddon: PropTypes.node, /** * The seperator between hours and minutes * @default ':' */ secondsAddon: PropTypes.node, /** * The seperator between hours and minutes * @default '.' */ millisecondsAddon: PropTypes.node, } const defaultProps = { hoursAddon: ':', padValues: true, precision: 'minutes', emptyCharacter: '-', } interface TimePartState { value: Date | null use12HourClock: boolean timeParts: TimeParts } // let count = 0 function useTimePartState(value: Date | null, use12HourClock: boolean) { const [state, setState] = useState<TimePartState>(() => ({ value, use12HourClock, timeParts: getValueParts(value, use12HourClock), })) const setTimeParts = useCallback( (timeParts: TimeParts) => setState((s) => ({ ...s, timeParts })), [setState], ) if (state.value !== value || state.use12HourClock !== use12HourClock) { // count++ // if (count < 100) setState({ value, use12HourClock, timeParts: getValueParts(value, use12HourClock), }) } return [state.timeParts, setTimeParts] as const } function TimeInput(uncontrolledProps: TimeInputProps) { const { value, use12HourClock, padValues: pad, emptyCharacter, precision, noClearButton, hoursAddon, minutesAddon, secondsAddon, millisecondsAddon, className, disabled, readOnly, datePart, onChange, onBlur, onFocus, ...props } = useUncontrolled(uncontrolledProps, { value: 'onChange' }) let minsAddon = minutesAddon !== undefined ? minutesAddon : precision === 'seconds' || precision === 'milliseconds' ? ':' : '' let secsAddon = secondsAddon !== undefined ? secondsAddon : precision === 'milliseconds' ? ':' : '' const ref = useRef<HTMLDivElement>(null) const hourRef = useRef<HTMLInputElement>(null) const [focusEvents, focused] = useFocusManager( ref, { disabled, onBlur, onFocus }, { didHandle: (focused, e: React.FocusEvent<HTMLElement>) => { if (!focused) return if (!e.target.dataset.focusable) hourRef.current?.focus() else select(e.target as HTMLInputElement) }, }, ) const [timeParts, setTimeParts] = useTimePartState( value ?? null, use12HourClock ?? false, ) function getDatePart() { return dates.startOf(datePart || new Date(), 'day') } const getMin = (part: TimePart) => (part === 'hours' ? 1 : 0) const getMax = (part: TimePart) => { if (part === 'hours') return use12HourClock ? 12 : 23 if (part === 'milliseconds') return 999 return 59 } function select( target: HTMLInputElement = document.activeElement as HTMLInputElement, ) { window.Promise.resolve().then(() => { if (focused) selectTextRange(target) }) } /** * Handlers */ const handleClear = () => { hourRef.current?.focus() if (value) onChange!(null) else setTimeParts(getValueParts(null)) } const handleChange = ( part: TimePart, event: React.ChangeEvent<HTMLInputElement>, ) => { const currentValue = timeParts[part] const { target } = event const rawValue = target.value let strValue = `${currentValue || ''}${rawValue}` let numValue = +strValue if ( isNaN(numValue) || (strValue && !isValid(strValue, part, use12HourClock ?? false)) ) { // the combined value is now past the max or invalid so try the single // digit and "start over" filling the value if ( isValid(rawValue, part, use12HourClock ?? false) && !isNaN(+rawValue) ) { // change the effective current value strValue = rawValue numValue = +rawValue } else { return event.preventDefault() } } const nextValue = target.value ? numValue : null notifyChange({ [part]: nextValue }) if ( nextValue != null && isComplete(strValue, part, use12HourClock ?? false) ) { focusNext(event.currentTarget, +1) } else { select(target) } } const handleSelect = ({ target, }: | React.SyntheticEvent<HTMLInputElement | HTMLDivElement> | React.FocusEvent<HTMLInputElement | HTMLDivElement>) => { select(target as HTMLInputElement) } const handleKeyDown = ( part: TimePart, event: React.KeyboardEvent<HTMLInputElement | HTMLDivElement>, ) => { const { key } = event const input = event.currentTarget as HTMLInputElement const { selectionStart: start, selectionEnd: end } = input const isRTL = getComputedStyle(input).getPropertyValue('direction') === 'rtl' const isMeridiem = part === 'meridiem' const isNext = key === (isRTL ? 'ArrowLeft' : 'ArrowRight') const isPrev = key === (isRTL ? 'ArrowRight' : 'ArrowLeft') if (key === 'ArrowUp') { event.preventDefault() increment(part, 1) } if (key === 'ArrowDown') { event.preventDefault() increment(part, -1) } if (isPrev && (isMeridiem || start! - 1 < 0)) { event.preventDefault() focusNext(input, -1) } if (isNext && (isMeridiem || input.value.length <= end! + 1)) { event.preventDefault() focusNext(input, +1) } if (readOnly && key !== 'Tab') { event.preventDefault() } if (isMeridiem) { if (key === 'a' || key === 'A') notifyChange({ meridiem: 'AM' }) if (key === 'p' || key === 'P') notifyChange({ meridiem: 'PM' }) } } const increment = (part: TimePart, inc: number) => { let nextPart = timeParts[part] if (part === 'meridiem') { nextPart = nextPart === 'AM' ? 'PM' : 'AM' } else { nextPart = ((nextPart as number) || 0) + inc if (!isValid(String(nextPart), part, use12HourClock ?? false)) return } notifyChange({ [part]: nextPart }) select() } function notifyChange(updates: Partial<TimeParts>) { const nextTimeParts: TimeParts = { ...timeParts, ...updates } if (value && isEmptyValue(nextTimeParts, precision)) { return onChange!(null) } if (isPartialValue(nextTimeParts, precision)) return setTimeParts(nextTimeParts) let { hours, minutes, seconds, milliseconds, meridiem } = nextTimeParts let nextDate = new Date(value || getDatePart()) if (use12HourClock) { if (hours === 12) hours = 0 hours! += meridiem === 'PM' ? 12 : 0 } nextDate.setHours(hours!) nextDate.setMinutes(minutes!) if (seconds != null) nextDate.setSeconds(seconds) if (milliseconds != null) nextDate.setMilliseconds(milliseconds) onChange!(nextDate, { lastValue: value, timeParts, }) } function focusNext(input: HTMLInputElement, delta: number) { let nodes = qsa(ref.current!, '* [data-focusable]') let next = nodes[nodes.indexOf(input) + delta] next?.focus() select(next as HTMLInputElement) } const { hours, minutes, seconds, milliseconds, meridiem } = timeParts const showClear = !isEmptyValue(timeParts, precision) return ( <Widget {...props} role="group" ref={ref} {...focusEvents} focused={focused} disabled={disabled} readOnly={readOnly} className={classNames(className, 'rw-time-input rw-widget-input')} > <DateTimePartInput size={2} pad={pad ? 2 : undefined} value={hours} disabled={disabled} readOnly={readOnly} aria-label="hours" min={getMin('hours')} max={getMax('hours')} ref={hourRef} emptyChar={emptyCharacter} onSelect={handleSelect} onChange={(e) => handleChange('hours', e)} onKeyDown={(e) => handleKeyDown('hours', e)} /> {hoursAddon && <span>{hoursAddon}</span>} <DateTimePartInput size={2} pad={pad ? 2 : undefined} value={minutes} disabled={disabled} readOnly={readOnly} aria-label="minutes" min={getMin('minutes')} max={getMax('minutes')} emptyChar={emptyCharacter} onSelect={handleSelect} onChange={(e) => handleChange('minutes', e)} onKeyDown={(e) => handleKeyDown('minutes', e)} /> {minsAddon && <span>{minsAddon}</span>} {(precision === 'seconds' || precision === 'milliseconds') && ( <> <DateTimePartInput size={2} pad={pad ? 2 : undefined} value={seconds} disabled={disabled} readOnly={readOnly} aria-label="seconds" min={getMin('seconds')} max={getMax('seconds')} emptyChar={emptyCharacter} onSelect={handleSelect} onChange={(e) => handleChange('seconds', e)} onKeyDown={(e) => handleKeyDown('seconds', e)} /> {secsAddon && <span>{secsAddon}</span>} </> )} {precision === 'milliseconds' && ( <> <DateTimePartInput size={3} pad={pad ? 3 : undefined} value={milliseconds} disabled={disabled} readOnly={readOnly} aria-label="milliseconds" min={getMin('milliseconds')} max={getMax('milliseconds')} emptyChar={emptyCharacter} onSelect={handleSelect} onChange={(e) => handleChange('milliseconds', e)} onKeyDown={(e) => handleKeyDown('milliseconds', e)} /> {millisecondsAddon && <span>{millisecondsAddon}</span>} </> )} {use12HourClock && ( <div role="listbox" aria-label="AM/PM" aria-disabled={disabled} aria-readonly={readOnly} className="rw-time-part-meridiem" > <div data-focusable role="option" aria-atomic aria-selected aria-setsize={2} aria-live="assertive" aria-disabled={disabled} aria-readonly={readOnly} aria-posinset={meridiem === 'AM' ? 1 : 2} tabIndex={!disabled ? 0 : void 0} onFocus={handleSelect} onSelect={handleSelect} onKeyDown={(e) => handleKeyDown('meridiem', e)} > <abbr>{meridiem}</abbr> </div> </div> )} {!noClearButton && ( <Button label={'clear input'} onClick={handleClear} disabled={disabled || readOnly} className={classNames('rw-time-input-clear', showClear && 'rw-show')} > {times} </Button> )} </Widget> ) } TimeInput.propTypes = propTypes TimeInput.defaultProps = defaultProps export default TimeInput
the_stack
import "./helpers/dotenv_helper"; import { envkeyFetch } from "./helpers/fetch_helper"; import { getTestId, resetTestId, getState, dispatch, hostUrl, } from "./helpers/test_helper"; import { getUserEncryptedKeys } from "@api_shared/blob"; import { query, getDb } from "@api_shared/db"; import * as R from "ramda"; import { getAuth, getEnvWithMeta } from "@core/lib/client"; import { registerWithEmail, loadAccount } from "./helpers/auth_helper"; import { acceptInvite, inviteAdminUser } from "./helpers/invites_helper"; import { Client, Api, Model, Rbac } from "@core/types"; import { connectBlocks, createBlock } from "./helpers/blocks_helper"; import { updateEnvs, updateLocals, fetchEnvsWithChangesets, getEnvironments, } from "./helpers/envs_helper"; import { createApp } from "./helpers/apps_helper"; import { graphTypes, getEnvironmentName } from "@core/lib/graph"; import { getOrg } from "@api_shared/models/orgs"; import { getOrgGraph } from "@api_shared/graph"; import { acceptDeviceGrant } from "./helpers/device_grants_helper"; import { testRemoveUser } from "./helpers/org_helper"; import { getRootPubkeyReplacements } from "./helpers/crypto_helper"; import { log } from "@core/lib/utils/logger"; import { wait } from "@core/lib/utils/wait"; import fs from "fs"; describe("orgs", () => { let email: string, orgId: string, deviceId: string, ownerId: string; beforeEach(async () => { email = `success+${getTestId()}@simulator.amazonses.com`; ({ orgId, deviceId, userId: ownerId } = await registerWithEmail(email)); }); test("rename", async () => { const promise = dispatch( { type: Api.ActionType.RENAME_ORG, payload: { name: "Renamed-Org", }, }, ownerId ); let state = getState(ownerId); expect(state.isRenaming[orgId]).toBeTrue(); const res = await promise; expect(res.success).toBeTrue(); state = getState(ownerId); expect(state.isRenaming[orgId]).toBeUndefined(); expect(state.graph[orgId]).toEqual( expect.objectContaining({ name: "Renamed-Org", }) ); }); test("update settings", async () => { let state = getState(ownerId); const org = state.graph[orgId] as Api.Db.Org; const promise = dispatch( { type: Api.ActionType.UPDATE_ORG_SETTINGS, payload: R.mergeDeepRight(org.settings, { crypto: { requiresLockout: true, lockoutMs: 1000 * 60, }, auth: { tokenExpirationMs: 1000 * 60, }, }), }, ownerId ); state = getState(ownerId); expect(state.isUpdatingSettings[orgId]).toBeTrue(); const res = await promise; expect(res.success).toBeTrue(); state = getState(ownerId); expect(state.isUpdatingSettings[orgId]).toBeUndefined(); expect(state.graph[orgId]).toEqual( expect.objectContaining({ settings: { crypto: { requiresPassphrase: false, requiresLockout: true, lockoutMs: 1000 * 60, }, auth: { inviteExpirationMs: expect.toBeNumber(), deviceGrantExpirationMs: expect.toBeNumber(), tokenExpirationMs: 1000 * 60, }, envs: expect.toBeObject(), }, }) ); }); test("delete org", async () => { const { id: appId } = await createApp(ownerId); const { id: blockId } = await createBlock(ownerId); await updateEnvs(ownerId, appId); await updateLocals(ownerId, appId); await updateEnvs(ownerId, blockId); await updateLocals(ownerId, blockId); let state = getState(ownerId), { orgRoles } = graphTypes(state.graph); const basicRole = R.indexBy(R.prop("name"), orgRoles)["Basic User"]; await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-1${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-2${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-2${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const [invite1Params, invite2Params] = state.generatedInvites, invitee1Id = invite1Params.user.id, approveDeviceParams = [{ granteeId: ownerId }]; await dispatch( { type: Client.ActionType.APPROVE_DEVICES, payload: approveDeviceParams, }, ownerId ); state = getState(ownerId); const generatedDeviceGrant = state.generatedDeviceGrants[0]; await dispatch( { type: Client.ActionType.CREATE_RECOVERY_KEY, }, ownerId ); state = getState(ownerId); const recoveryEncryptionKey = state.generatedRecoveryKey!.encryptionKey; const [appDevelopment] = getEnvironments(ownerId, appId); await dispatch( { type: Client.ActionType.CREATE_LOCAL_KEY, payload: { appId, name: "Development Key", environmentId: appDevelopment.id, }, }, ownerId ); state = getState(ownerId); const byType = graphTypes(state.graph), [{ id: localKeyId }] = byType.localKeys, [{ id: localGeneratedEnvkeyId }] = byType.generatedEnvkeys; await acceptInvite(invite1Params); state = getState(invite1Params.user.id); const invitee1DeviceId = getAuth<Client.ClientUserAuth>( state, invite1Params.user.id )!.deviceId; await loadAccount(ownerId); const promise = dispatch( { type: Api.ActionType.DELETE_ORG, payload: {}, }, ownerId ); state = getState(ownerId); expect(state.isRemoving[orgId]).toBeTrue(); const res = await promise; expect(res.success).toBeTrue(); state = getState(ownerId); expect(state.orgUserAccounts[ownerId]).toBeUndefined(); // console.log(`ensure org is marked deleted in the db`); const org = await getOrg(orgId, undefined); expect(org!.deletedAt).toBeNumber(); // console.log(`ensure encrypted keys are deleted`); const blobs = await Promise.all([ getUserEncryptedKeys( { orgId, userId: ownerId, deviceId, blobType: "env", }, { transactionConn: undefined } ), getUserEncryptedKeys( { orgId, userId: invitee1Id, deviceId: invitee1DeviceId, blobType: "env", }, { transactionConn: undefined } ), query({ pkey: ["envkey", localGeneratedEnvkeyId].join("|"), transactionConn: undefined, }), ]).then(R.flatten); expect(blobs).toEqual([]); // console.log(`ensure active invite can't be redeemed`); const [{ skey: inviteEmailToken }] = await query<Api.Db.InvitePointer>({ pkey: ["invite", invite2Params.identityHash].join("|"), transactionConn: undefined, }); const loadInviteRes = await dispatch< Client.Action.ClientActions["LoadInvite"] >( { type: Client.ActionType.LOAD_INVITE, payload: { emailToken: inviteEmailToken, encryptionToken: [ invite2Params.identityHash, invite2Params.encryptionKey, ].join("_"), }, }, undefined ); expect(loadInviteRes.success).toBeFalse(); // console.log(`ensure active device grant can't be redeemed`); const [{ skey: deviceGrantEmailToken }] = await query<Api.Db.DeviceGrantPointer>({ pkey: ["deviceGrant", generatedDeviceGrant.identityHash].join("|"), transactionConn: undefined, }), deviceGrantLoadRes = await dispatch< Client.Action.ClientActions["LoadDeviceGrant"] >( { type: Client.ActionType.LOAD_DEVICE_GRANT, payload: { emailToken: deviceGrantEmailToken, encryptionToken: [ generatedDeviceGrant.identityHash, generatedDeviceGrant.encryptionKey, ].join("_"), }, }, undefined ); expect(deviceGrantLoadRes.success).toBeFalse(); // console.log(`ensure active recovery key can't be redeemed`); const recoveryKeyLoadRes = await dispatch< Client.Action.ClientActions["LoadRecoveryKey"] >( { type: Client.ActionType.LOAD_RECOVERY_KEY, payload: { encryptionKey: recoveryEncryptionKey, hostUrl, }, }, undefined ); expect(recoveryKeyLoadRes.success).toBeFalse(); expect( (recoveryKeyLoadRes.resultAction as any).payload.error.type ).not.toBe("requiresEmailAuthError"); }); test("rename user", async () => { let state = getState(ownerId), { orgRoles } = graphTypes(state.graph); const [basicRole, adminRole] = R.props( ["Basic User", "Org Admin"] as string[], R.indexBy(R.prop("name"), orgRoles) ); await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-1${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-2${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-2${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin-1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin-1${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin-2${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin-2${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const [ basic1InviteParams, basic2InviteParams, admin1InviteParams, admin2InviteParams, ] = state.generatedInvites, basic1InviteeId = basic1InviteParams.user.id, basic2InviteeId = basic2InviteParams.user.id, admin1InviteeId = admin1InviteParams.user.id, admin2InviteeId = admin2InviteParams.user.id; // owner can rename self const promise = dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: ownerId, firstName: "Renamed", lastName: "Owner", }, }, ownerId ); state = getState(ownerId); expect(state.isRenaming[ownerId]).toBeTrue(); const res1 = await promise; expect(res1.success).toBeTrue(); state = getState(ownerId); expect(state.isRenaming[ownerId]).toBeUndefined(); expect(state.graph[ownerId]).toEqual( expect.objectContaining({ firstName: "Renamed", lastName: "Owner", }) ); // owner can rename invited user const res2 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: basic1InviteeId, firstName: "Renamed", lastName: "Basic", }, }, ownerId ); expect(res2.success).toBeTrue(); state = getState(ownerId); expect(state.graph[basic1InviteeId]).toEqual( expect.objectContaining({ firstName: "Renamed", lastName: "Basic", }) ); //owner can rename active user await acceptInvite(basic1InviteParams); await loadAccount(ownerId); const res3 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: basic1InviteeId, firstName: "Renamed-Again", lastName: "Basic-Again", }, }, ownerId ); expect(res3.success).toBeTrue(); state = getState(ownerId); expect(state.graph[basic1InviteeId]).toEqual( expect.objectContaining({ firstName: "Renamed-Again", lastName: "Basic-Again", }) ); // org admin cannot rename another org admin they didn't invite await acceptInvite(admin1InviteParams); await acceptInvite(admin2InviteParams); const res4 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: admin1InviteeId, firstName: "Renamed", lastName: "Admin", }, }, admin2InviteParams.user.id ); expect(res4.success).toBeFalse(); // org admin can rename an invited org admin they *did* invite await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin-3${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin-3${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, ], }, admin2InviteParams.user.id ); state = getState(admin2InviteParams.user.id); const admin3InviteParams = state.generatedInvites.slice(-1)[0], admin3InviteeId = admin3InviteParams.user.id, res5 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: admin3InviteeId, firstName: "Renamed", lastName: "Admin", }, }, admin2InviteParams.user.id ); expect(res5.success).toBeTrue(); state = getState(admin2InviteParams.user.id); expect(state.graph[admin3InviteeId]).toEqual( expect.objectContaining({ firstName: "Renamed", lastName: "Admin", }) ); // org admin *cannot* rename an active org admin even if they did invite them await acceptInvite(admin3InviteParams); await loadAccount(admin2InviteeId); const res6 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: admin3InviteeId, firstName: "Renamed-Again", lastName: "Admin-Again", }, }, admin2InviteParams.user.id ); expect(res6.success).toBeFalse(); // org admin cannot rename self const res7 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: admin2InviteeId, firstName: "Renamed-Again", lastName: "Admin-Again", }, }, admin2InviteParams.user.id ); expect(res7.success).toBeFalse(); // basic user cannot rename another basic user await acceptInvite(basic2InviteParams); const res8 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: basic1InviteeId, firstName: "Renamed-Again", lastName: "Basic-Again", }, }, basic2InviteParams.user.id ); expect(res8.success).toBeFalse(); // basic user cannot rename self const res9 = await dispatch( { type: Api.ActionType.RENAME_USER, payload: { id: basic2InviteeId, firstName: "Renamed-Again", lastName: "Basic-Again", }, }, basic2InviteParams.user.id ); expect(res9.success).toBeFalse(); }); test("update user role", async () => { const { id: appId } = await createApp(ownerId); const { id: blockId } = await createBlock(ownerId); await updateEnvs(ownerId, appId); await updateLocals(ownerId, appId); await updateEnvs(ownerId, blockId); await updateLocals(ownerId, blockId); let state = getState(ownerId); const { orgRoles } = graphTypes(state.graph), [basicRole, adminRole] = R.props( ["Basic User", "Org Admin"] as string[], R.indexBy(R.prop("name"), orgRoles) ); await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-1${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const invite1Params = state.generatedInvites.slice(-1)[0], invitee1Id = invite1Params.user.id; // upgrading with an active invite const promise1 = dispatch( { type: Client.ActionType.UPDATE_USER_ROLES, payload: [ { id: invitee1Id, orgRoleId: adminRole.id, }, ], }, ownerId ); state = getState(ownerId); expect(state.isUpdatingUserRole[invitee1Id]).toBe(adminRole.id); const res1 = await promise1; expect(res1.success).toBeTrue(); state = getState(ownerId); expect(state.isUpdatingUserRole[invitee1Id]).toBeUndefined(); await acceptInvite(invite1Params); await fetchEnvsWithChangesets(invite1Params.user.id, appId, ownerId); // downgrading with an active invite await loadAccount(ownerId); state = getState(ownerId); await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin1${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const invite2Params = state.generatedInvites.slice(-1)[0], invitee2Id = invite2Params.user.id, res2 = await dispatch( { type: Client.ActionType.UPDATE_USER_ROLES, payload: [ { id: invitee2Id, orgRoleId: basicRole.id, }, ], }, ownerId ); expect(res2.success).toBeTrue(); await acceptInvite(invite2Params); state = getState(invite2Params.user.id); expect(state.envs).toEqual({}); expect(state.changesets).toEqual({}); // upgrading with an active user await loadAccount(ownerId); await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-3${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-3${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const invite3Params = state.generatedInvites.slice(-1)[0], invitee3Id = invite3Params.user.id; await acceptInvite(invite3Params); await loadAccount(ownerId); const res3 = await dispatch( { type: Client.ActionType.UPDATE_USER_ROLES, payload: [ { id: invitee3Id, orgRoleId: adminRole.id, }, ], }, ownerId ); expect(res3.success).toBeTrue(); await loadAccount(invitee3Id); await fetchEnvsWithChangesets(invitee3Id, appId, ownerId); // downgrading with an active user await loadAccount(ownerId); const inviteRes = await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin4${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin4${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const invite4Params = state.generatedInvites.slice(-1)[0], invitee4Id = invite4Params.user.id; await acceptInvite(invite4Params); await loadAccount(ownerId); const res4 = await dispatch( { type: Client.ActionType.UPDATE_USER_ROLES, payload: [ { id: invitee1Id, orgRoleId: basicRole.id, }, ], }, ownerId ); expect(res4.success).toBeTrue(); await loadAccount(invitee4Id); state = getState(invitee4Id); expect(state.envs).toEqual({}); expect(state.changesets).toEqual({}); // upgrading a cli user await loadAccount(ownerId); await dispatch( { type: Client.ActionType.CREATE_CLI_USER, payload: { name: "cli-user", orgRoleId: basicRole.id, }, }, ownerId ); state = getState(ownerId); const { cliKey } = state.generatedCliUsers[0], cliUser = graphTypes(state.graph).cliUsers[0]; await dispatch( { type: Client.ActionType.UPDATE_USER_ROLES, payload: [ { id: cliUser.id, orgRoleId: adminRole.id, }, ], }, ownerId ); await dispatch( { type: Client.ActionType.AUTHENTICATE_CLI_KEY, payload: { cliKey }, }, cliKey ); await fetchEnvsWithChangesets(cliKey, appId, ownerId); // downgrading a cli user await dispatch( { type: Client.ActionType.UPDATE_USER_ROLES, payload: [ { id: cliUser.id, orgRoleId: basicRole.id, }, ], }, ownerId ); await dispatch( { type: Client.ActionType.AUTHENTICATE_CLI_KEY, payload: { cliKey }, }, cliKey ); // wait for CLEAR_ORPHANED_BLOBS to run await wait(1000); state = getState(cliKey); expect(state.envs).toEqual({}); expect(state.changesets).toEqual({}); }); test("remove user", async () => { const { id: appId } = await createApp(ownerId); const { id: blockId } = await createBlock(ownerId); let state = getState(ownerId); const { orgRoles, appRoles } = graphTypes(state.graph), [basicRole, adminRole, ownerRole] = R.props( ["Basic User", "Org Admin", "Org Owner"] as string[], R.indexBy(R.prop("name"), orgRoles) ), [devRole] = R.props( ["Developer"] as string[], R.indexBy(R.prop("name"), appRoles) ); await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-1${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, appUserGrants: [{ appId, appRoleId: devRole.id }], }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-2${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-2${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, appUserGrants: [{ appId, appRoleId: devRole.id }], }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-3${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-3${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, appUserGrants: [{ appId, appRoleId: devRole.id }], }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin1${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin2${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin2${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin3${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin3${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-owner2${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-owner2${getTestId()}@simulator.amazonses.com`, orgRoleId: ownerRole.id, }, }, { user: { firstName: "Invited", lastName: "User", email: `success+invitee-owner3${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-owner3${getTestId()}@simulator.amazonses.com`, orgRoleId: ownerRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const [ basic1InviteParams, basic2InviteParams, basic3InviteParams, admin1InviteParams, admin2InviteParams, admin3InviteParams, owner2InviteParams, owner3InviteParams, ] = state.generatedInvites, admin1Id = admin1InviteParams.user.id, admin2Id = admin2InviteParams.user.id, admin3Id = admin3InviteParams.user.id, owner2Id = owner2InviteParams.user.id, owner3Id = owner3InviteParams.user.id, basic1Id = basic1InviteParams.user.id, basic2Id = basic2InviteParams.user.id, basic3Id = basic3InviteParams.user.id; await acceptInvite(admin1InviteParams); await acceptInvite(admin2InviteParams); await acceptInvite(admin3InviteParams); await acceptInvite(owner2InviteParams); await acceptInvite(owner3InviteParams); await acceptInvite(basic1InviteParams); await acceptInvite(basic2InviteParams); await acceptInvite(basic3InviteParams); // create a cli user to test that it can remove a user too // and also that it still works correctly after its creator is removed await dispatch( { type: Client.ActionType.CREATE_CLI_USER, payload: { name: "cli-user", orgRoleId: adminRole.id, }, }, ownerId ); state = getState(ownerId); const { cliKey } = state.generatedCliUsers[0]; await dispatch( { type: Client.ActionType.AUTHENTICATE_CLI_KEY, payload: { cliKey }, }, cliKey ); state = getState(cliKey); const cliAuth = getAuth<Client.ClientCliAuth>(state, cliKey); const cliUserId = cliAuth!.userId; // update envs with admin so we can test pubkey revocation requests await updateEnvs(admin1Id, appId); await updateLocals(admin1Id, appId); await updateEnvs(admin1Id, blockId); await updateLocals(admin1Id, blockId); // create a server so we can test root pubkey replacements const [appDevelopment] = getEnvironments(ownerId, appId); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Dev Server", environmentId: appDevelopment.id, }, }, ownerId ); state = getState(ownerId); const byType = graphTypes(state.graph); const { id: serverId } = byType.servers[byType.servers.length - 1]; const { id: serverGeneratedEnvkeyId } = byType.generatedEnvkeys[byType.generatedEnvkeys.length - 1]; const { envkeyIdPart: serverEnvkeyIdPart, encryptionKey: serverEncryptionKey, } = R.find( R.propEq("keyableParentId", serverId), Object.values(state.generatedEnvkeys) )!; // create an invite, device grant, and recovery key with a user who won't be removed so we can ensure invite acceptance works after root replacements await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-admin4${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-admin4${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, ], }, owner3Id ); await dispatch( { type: Client.ActionType.APPROVE_DEVICES, payload: [{ granteeId: owner3Id }], }, owner3Id ); await dispatch( { type: Client.ActionType.CREATE_RECOVERY_KEY, }, owner3Id ); state = getState(owner3Id); const [pendingInviteParams] = state.generatedInvites; const [pendingDeviceGrantParams] = state.generatedDeviceGrants; if ( state.generateRecoveryKeyError || !R.isEmpty(state.generateDeviceGrantErrors) || !R.isEmpty(state.generateInviteErrors) ) { log("state.generateDeviceGrantErrors", state.generateDeviceGrantErrors); log("state.generateInviteErrors", state.generateInviteErrors); } state = getState(owner3Id); const pendingRecoveryKeyParams = state.generatedRecoveryKey!; let orgGraph = await getOrgGraph(orgId, { transactionConn: undefined }); const start = Date.now(); // console.log("owner can remove org admin"); await testRemoveUser({ actorId: ownerId, targetId: admin1Id, canRemove: true, canImmediatelyRevoke: false, canSubsequentlyRevoke: true, }); // console.log("org admin cannot remove another org admin"); await testRemoveUser({ actorId: admin2Id, targetId: admin3Id, canRemove: false, }); // console.log("org admin can remove basic user"); await testRemoveUser({ actorId: admin2Id, targetId: basic1Id, canRemove: true, canImmediatelyRevoke: true, }); // console.log("org admin can remove self"); await testRemoveUser({ actorId: admin2Id, targetId: admin2Id, canRemove: true, canImmediatelyRevoke: false, canSubsequentlyRevoke: false, revocationRequestProcessorId: owner2Id, }); await wait(2000); // console.log("basic user cannot remove an org admin"); await testRemoveUser({ actorId: basic2Id, targetId: admin3Id, canRemove: false, }); // console.log("basic user cannot remove another basic user"); await testRemoveUser({ actorId: basic2Id, targetId: basic3Id, canRemove: false, }); // console.log("basic user can remove self"); await testRemoveUser({ actorId: basic2Id, targetId: basic2Id, canRemove: true, canImmediatelyRevoke: true, }); // console.log("owner can remove self if there's another owner"); await testRemoveUser({ actorId: ownerId, targetId: ownerId, canRemove: true, canImmediatelyRevoke: false, canSubsequentlyRevoke: false, isRemovingRoot: true, numAdditionalKeyables: 3, revocationRequestProcessorId: owner2Id, uninvolvedUserId: admin3Id, }); await wait(2000); // console.log("owner can remove another owner"); await testRemoveUser({ actorId: owner3Id, targetId: owner2Id, canRemove: true, canImmediatelyRevoke: false, canSubsequentlyRevoke: true, isRemovingRoot: true, numAdditionalKeyables: 3, uninvolvedUserId: admin3Id, }); await wait(2000); // console.log("owner cannot remove self it they're the only owner"); await testRemoveUser({ actorId: owner3Id, targetId: owner3Id, canRemove: false, }); // console.log("admin cli user can remove a basic user"); await testRemoveUser({ actorId: cliUserId, actorCliKey: cliKey, targetId: basic3Id, canRemove: true, canImmediatelyRevoke: true, }); // test fetch ENVKEY root replacements await envkeyFetch(serverEnvkeyIdPart, serverEncryptionKey); orgGraph = await getOrgGraph(orgId, { transactionConn: undefined }); let generatedEnvkey = orgGraph[ serverGeneratedEnvkeyId ] as Api.Db.GeneratedEnvkey; const trustedRootUpdatedAt = generatedEnvkey.trustedRootUpdatedAt; expect(trustedRootUpdatedAt).toBeGreaterThan(start); const replacements = await getRootPubkeyReplacements(orgId, start); expect(replacements.length).toBe(2); for (let replacement of replacements) { expect(replacement.processedAtById[serverGeneratedEnvkeyId]).toBeNumber(); } await envkeyFetch(serverEnvkeyIdPart, serverEncryptionKey); orgGraph = await getOrgGraph(orgId, { transactionConn: undefined }); generatedEnvkey = orgGraph[ serverGeneratedEnvkeyId ] as Api.Db.GeneratedEnvkey; expect(generatedEnvkey.trustedRootUpdatedAt).toEqual(trustedRootUpdatedAt); // console.log("test accept invite root replacements"); await acceptInvite(pendingInviteParams); // console.log("test accept device grant root replacements"); await acceptDeviceGrant(owner3Id, pendingDeviceGrantParams); // console.log("test redeem recovery key root replacements"); state = getState(owner3Id); const { id: recoveryKeyId } = graphTypes(state.graph).recoveryKeys[0]; await dispatch( { type: Client.ActionType.LOAD_RECOVERY_KEY, payload: { ...pendingRecoveryKeyParams, hostUrl, }, }, owner3Id ); const recoveryKey = await getDb<Api.Db.RecoveryKey>(recoveryKeyId, { transactionConn: undefined, }); const emailToken = recoveryKey!.emailToken!; const loadRecoveryKeyRes = await dispatch( { type: Client.ActionType.LOAD_RECOVERY_KEY, payload: { ...pendingRecoveryKeyParams, emailToken, hostUrl, }, }, owner3Id ); expect(loadRecoveryKeyRes.success).toBeTrue(); const redeemRecoveryKeyRes = await dispatch( { type: Client.ActionType.REDEEM_RECOVERY_KEY, payload: { deviceName: "recovery-device", ...pendingRecoveryKeyParams, emailToken, hostUrl, }, }, owner3Id ); expect(redeemRecoveryKeyRes.success).toBeTrue(); }); test("export and import org archive", async () => { let state = getState(ownerId); const org = graphTypes(state.graph).org; await dispatch( { type: Api.ActionType.RENAME_ORG, payload: { name: "Renamed-Org", }, }, ownerId ); await dispatch( { type: Api.ActionType.UPDATE_ORG_SETTINGS, payload: R.mergeDeepRight(org.settings, { auth: { tokenExpirationMs: 1000 * 60, }, }), }, ownerId ); const { orgRoles, appRoles } = graphTypes(state.graph), [basicRole, adminRole] = R.props( ["Basic User", "Org Admin"] as string[], R.indexBy(R.prop("name"), orgRoles) ), [ appOrgOwnerRole, appOrgAdminRole, appAdminRole, appProdRole, appDevRole, ] = R.props( ["Org Owner", "Org Admin", "Admin", "DevOps", "Developer"] as string[], R.indexBy(R.prop("name"), appRoles) ); const { id: app1Id } = await createApp(ownerId, "App 1"); const { id: app2Id } = await createApp(ownerId, "App 2"); const { id: block1Id } = await createBlock(ownerId, "Block 1"); const { id: block2Id } = await createBlock(ownerId, "Block 2"); const { id: block3Id } = await createBlock(ownerId, "Block 3"); const { id: block4Id } = await createBlock(ownerId, "Block 4"); await updateEnvs(ownerId, app1Id); await updateLocals(ownerId, app1Id); await updateEnvs(ownerId, app2Id); await updateLocals(ownerId, app2Id); await updateEnvs(ownerId, block1Id); await updateLocals(ownerId, block1Id); await updateEnvs(ownerId, block2Id); await updateLocals(ownerId, block2Id); await updateEnvs(ownerId, block3Id); await updateLocals(ownerId, block3Id); await updateEnvs(ownerId, block4Id); await updateLocals(ownerId, block4Id); const environments = getEnvironments(ownerId, app1Id), [app1Development, app1Staging, app1Production] = environments; dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: app1Id, entryKey: "DEV_INHERITS_KEY", vals: { [app1Development.id]: { inheritsEnvironmentId: app1Production.id }, [app1Staging.id]: { isUndefined: true }, [app1Production.id]: { val: "prod-val", }, }, }, }, ownerId ); await dispatch( { type: Api.ActionType.RBAC_CREATE_ENVIRONMENT_ROLE, payload: { name: "New Role", description: "", hasLocalKeys: false, hasServers: true, defaultAllApps: false, defaultAllBlocks: false, settings: { autoCommit: false }, appRoleEnvironmentRoles: { [appProdRole.id]: ["read", "write"], [appDevRole.id]: ["read_meta"], }, }, }, ownerId ); state = getState(ownerId); const newEnvironmentRole = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environmentRoles) )!; await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { environmentRoleId: newEnvironmentRole.id, envParentId: app1Id, }, }, ownerId ); state = getState(ownerId); const app1NewRoleEnvironment = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) )!; await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { environmentRoleId: newEnvironmentRole.id, envParentId: block1Id, }, }, ownerId ); state = getState(ownerId); const block1NewRoleEnvironment = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) )!; const [block1Dev] = getEnvironments(ownerId, block1Id); await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { isSub: true, environmentRoleId: app1Development.environmentRoleId, envParentId: app1Id, parentEnvironmentId: app1Development.id, subName: "dev-sub", }, }, ownerId ); state = getState(ownerId); const app1Sub = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) )!; await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { isSub: true, environmentRoleId: block1Dev.environmentRoleId, envParentId: block1Id, parentEnvironmentId: block1Dev.id, subName: "dev-sub", }, }, ownerId ); state = getState(ownerId); const block1Sub = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) )!; await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { isSub: true, environmentRoleId: app1NewRoleEnvironment.environmentRoleId, envParentId: app1Id, parentEnvironmentId: app1NewRoleEnvironment.id, subName: "dev-sub", }, }, ownerId ); state = getState(ownerId); const app1NewRoleSub = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) )!; // await dispatch( // { // type: Api.ActionType.CREATE_ENVIRONMENT, // payload: { // isSub: true, // environmentRoleId: block1NewRoleEnvironment.environmentRoleId, // envParentId: block1Id, // parentEnvironmentId: block1NewRoleEnvironment.id, // subName: "dev-sub", // }, // }, // ownerId // ); await dispatch( { type: Client.ActionType.IMPORT_ENVIRONMENT, payload: { envParentId: app1Id, environmentId: app1NewRoleEnvironment.id, parsed: { IMPORTED_APP1_KEY1: "imported-val", IMPORTED_APP1_KEY2: "imported-val", }, }, }, ownerId ); await dispatch( { type: Client.ActionType.IMPORT_ENVIRONMENT, payload: { envParentId: block1Id, environmentId: block1NewRoleEnvironment.id, parsed: { IMPORTED_BLOCK1_KEY1: "imported-val", IMPORTED_BLOCK1_KEY2: "imported-val", }, }, }, ownerId ); await dispatch( { type: Client.ActionType.IMPORT_ENVIRONMENT, payload: { envParentId: app1Id, environmentId: app1Sub.id, parsed: { IMPORTED_APP1_SUB_KEY1: "imported-val", IMPORTED_APP1_SUB_KEY2: "imported-val", }, }, }, ownerId ); await dispatch( { type: Client.ActionType.IMPORT_ENVIRONMENT, payload: { envParentId: block1Id, environmentId: block1Sub.id, parsed: { IMPORTED_BLOCK1_KEY1: "imported-val", IMPORTED_BLOCK1_KEY2: "imported-val", }, }, }, ownerId ); await dispatch( { type: Client.ActionType.IMPORT_ENVIRONMENT, payload: { envParentId: app1Id, environmentId: app1NewRoleSub.id, parsed: { IMPORTED_APP1_SUB_KEY1: "imported-val", IMPORTED_APP1_SUB_KEY2: "imported-val", }, }, }, ownerId ); await dispatch( { type: Client.ActionType.COMMIT_ENVS, payload: {}, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId: app1Id, name: "Development Server", environmentId: app1Development.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId: app1Id, name: "Dev Sub Server", environmentId: app1Sub.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId: app1Id, name: "New Role Server", environmentId: app1NewRoleEnvironment.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId: app1Id, name: "New Role Sub Server", environmentId: app1NewRoleSub.id, }, }, ownerId ); await connectBlocks(ownerId, [ { appId: app1Id, blockId: block1Id, orderIndex: 0, }, { appId: app1Id, blockId: block2Id, orderIndex: 1, }, { appId: app1Id, blockId: block3Id, orderIndex: 2, }, { appId: app2Id, blockId: block4Id, orderIndex: 0, }, { appId: app2Id, blockId: block3Id, orderIndex: 1, }, { appId: app2Id, blockId: block2Id, orderIndex: 2, }, ]); await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-1${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-1${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, appUserGrants: [ { appId: app1Id, appRoleId: appDevRole.id, }, { appId: app2Id, appRoleId: appProdRole.id, }, ], }, { user: { firstName: "Invited", lastName: "Admin", email: `success+invitee-2${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-2${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, ], }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_CLI_USER, payload: { name: "cli-user-1", orgRoleId: basicRole.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_CLI_USER, payload: { name: "cli-user-2", orgRoleId: adminRole.id, }, }, ownerId ); const cwd = process.cwd(); const exportPromise = dispatch( { type: Client.ActionType.EXPORT_ORG, payload: { filePath: cwd + `/${org.name.split(" ").join("-").toLowerCase()}-${new Date() .toISOString() .slice(0, 10)}.envkey-archive`, }, }, ownerId ); state = getState(ownerId); expect(state.isExportingOrg).toBe(true); let res = await exportPromise; expect(res.success).toBe(true); state = getState(ownerId); expect(state.isExportingOrg).toBeUndefined(); const { encryptionKey, filePath } = ( res.resultAction as { payload: { encryptionKey: string; filePath: string }; } ).payload; // register a new org to import into resetTestId(); // otherwise creating a second org causes device context issues const { userId: owner2Id } = await registerWithEmail(email); const importPromise = dispatch( { type: Client.ActionType.IMPORT_ORG, payload: { encryptionKey, filePath, importOrgUsers: true, }, }, owner2Id ); state = getState(owner2Id); expect(state.isImportingOrg).toBeTrue(); await wait(10); state = getState(owner2Id); expect(state.importOrgStatus).toBeString(); res = await importPromise; expect(res.success).toBe(true); state = getState(owner2Id); expect(state.isImportingOrg).toBeUndefined(); expect(state.importOrgStatus).toBeUndefined(); const byType = graphTypes(state.graph); expect(byType.org.name).toBe("Renamed-Org"); expect(byType.org.settings.auth.tokenExpirationMs).toBe(1000 * 60); expect(byType.environmentRoles.length).toBe(4); expect(byType.apps.length).toBe(2); expect(byType.blocks.length).toBe(4); expect(byType.orgUsers.length).toBe(3); expect(state.generatedInvites.length).toBe(2); expect(byType.cliUsers.length).toBe(2); expect(state.generatedCliUsers.length).toBe(2); expect(byType.appBlocks.length).toBe(6); expect(byType.appUserGrants.length).toBe(2); expect(byType.environments.length).toBe(23); expect(byType.servers.length).toBe(4); expect(byType.generatedEnvkeys.length).toBe(4); expect(Object.keys(state.generatedEnvkeys).length).toBe(4); for (let envParent of [...byType.apps, ...byType.blocks]) { const [development, staging, production] = getEnvironments( owner2Id, envParent.id ); expect( getEnvWithMeta(state, { envParentId: envParent.id, environmentId: development.id, }) ).toEqual({ inherits: { ...(envParent.name == "App 1" ? { [production.id]: ["DEV_INHERITS_KEY"], } : {}), }, variables: { KEY2: { isUndefined: true }, KEY3: { val: "key3-val" }, IMPORTED_KEY1: { val: "imported-val" }, IMPORTED_KEY2: { val: "imported-val" }, ...(envParent.name == "App 1" ? { DEV_INHERITS_KEY: { inheritsEnvironmentId: production.id } } : {}), }, }); expect( getEnvWithMeta(state, { envParentId: envParent.id, environmentId: staging.id, }) ).toEqual({ inherits: {}, variables: { KEY2: { isEmpty: true, val: "" }, KEY3: { val: "key3-val" }, ...(envParent.name == "App 1" ? { DEV_INHERITS_KEY: { isUndefined: true } } : {}), }, }); expect( getEnvWithMeta(state, { envParentId: envParent.id, environmentId: production.id, }) ).toEqual({ inherits: {}, variables: { KEY2: { val: "val3" }, KEY3: { val: "key3-val" }, ...(envParent.name == "App 1" ? { DEV_INHERITS_KEY: { val: "prod-val", }, } : {}), }, }); expect( getEnvWithMeta(state, { envParentId: envParent.id, environmentId: [envParent.id, owner2Id].join("|"), }) ).toEqual({ inherits: {}, variables: { KEY2: { isUndefined: true }, KEY3: { val: "key3-locals-val" }, IMPORTED_KEY1: { val: "imported-val" }, IMPORTED_KEY2: { val: "imported-val" }, }, }); } const newRoleServer = graphTypes(state.graph).servers.find( R.propEq("name", "New Role Server") )!; const newRoleGeneratedEnvkey = state.generatedEnvkeys[newRoleServer.id]; const newRoleEnv = await envkeyFetch( newRoleGeneratedEnvkey.envkeyIdPart, newRoleGeneratedEnvkey.encryptionKey ); expect(newRoleEnv).toEqual({ IMPORTED_BLOCK1_KEY1: "imported-val", IMPORTED_BLOCK1_KEY2: "imported-val", IMPORTED_APP1_KEY1: "imported-val", IMPORTED_APP1_KEY2: "imported-val", }); const newRoleSubServer = graphTypes(state.graph).servers.find( R.propEq("name", "New Role Sub Server") )!; const newRoleSubGeneratedEnvkey = state.generatedEnvkeys[newRoleSubServer.id]; const newRoleSubEnv = await envkeyFetch( newRoleSubGeneratedEnvkey.envkeyIdPart, newRoleSubGeneratedEnvkey.encryptionKey ); expect(newRoleSubEnv).toEqual({ IMPORTED_BLOCK1_KEY1: "imported-val", IMPORTED_BLOCK1_KEY2: "imported-val", IMPORTED_APP1_KEY1: "imported-val", IMPORTED_APP1_KEY2: "imported-val", IMPORTED_APP1_SUB_KEY1: "imported-val", IMPORTED_APP1_SUB_KEY2: "imported-val", }); // console.log("import finished"); // console.log("invite a new user, accept, make an update"); const invite = await inviteAdminUser(ownerId); await acceptInvite(invite); await loadAccount(invite.user.id); await dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: app1Id, environmentId: app1Development.id, entryKey: "KEY1", update: { val: "val1-updated" }, }, }, invite.user.id ); await dispatch( { type: Client.ActionType.COMMIT_ENVS, payload: {}, }, invite.user.id ); // console.log("generate a new CLI key, authenticate, make an update"); await loadAccount(ownerId); const orgAdminRole = R.indexBy(R.prop("name"), orgRoles)["Org Admin"]; await dispatch( { type: Client.ActionType.CREATE_CLI_USER, payload: { name: "cli-user", orgRoleId: orgAdminRole.id, }, }, ownerId ); const { cliKey } = state.generatedCliUsers[0]; await dispatch( { type: Client.ActionType.AUTHENTICATE_CLI_KEY, payload: { cliKey }, }, cliKey ); await dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: app1Id, environmentId: app1Development.id, entryKey: "KEY1", update: { val: "val1-updated-by-cli-key" }, }, }, cliKey ); await dispatch( { type: Client.ActionType.COMMIT_ENVS, payload: {}, }, cliKey ); fs.unlinkSync(filePath); // delete archive file }); });
the_stack
import { IExecSyncResult } from 'azure-pipelines-task-lib/toolrunner'; import { IExecSyncOptions } from 'azure-pipelines-task-lib/toolrunner'; import * as azdev from "azure-devops-node-api"; import * as taskAgentAPI from "azure-devops-node-api/TaskAgentApi" import path = require("path"); import tl = require("azure-pipelines-task-lib"); import fs = require("fs"); import { TaskAgentPool, TaskAgentStatus, TaskGroupExpands } from 'azure-devops-node-api/interfaces/TaskAgentInterfaces'; export class azurecontainercreate { public static execSyncSilentOption = { silent: true } as IExecSyncOptions; public static checkIfAzurePythonSdkIsInstalled() { return !!tl.which("az", false); } public static async runMain() { var toolExecutionError = null; try { this.validateInputs(); this.throwIfError(tl.execSync("az", "--version", this.execSyncSilentOption)); var agentPoolName = tl.getInput("agentPool", true); this.throwIf(false === await this.agentPoolExists(agentPoolName, this.getToken()), tl.loc("InvalidAgentPool", agentPoolName)) this.getRegistryCredentials(); // set az cli config dir this.setConfigDirectory(); this.setAzureCloudBasedOnServiceEndpoint(); var connectedService: string = tl.getInput("connectedServiceNameARM", true); this.loginAzureRM(connectedService); this.createAgentContainer(); if (false === await this.waitForAgentToBecomeOnline(this.agentPool, this.agentName, this.getToken())) { if (tl.getBoolInput("skipContainerDeletionOnError") === true) { tl.warning(`Agent didn't come online. Skipping container and agent deletion.`); } else { tl.warning(`Agent didn't come online. Going to delete container ${this.containerName}.`); this.deleteAgentContainer(); this.deleteAgent(this.agentPool, this.agentName, this.getToken()); } this.throwIf(true, tl.loc("WaitForAgentOnlineTimeout", this.agentName)); } // Set output variables tl.setVariable('ImageNameOutput', this.containerName); tl.setVariable('ImageIdOutput', this.containerId); } catch (err) { if (err.stderr) { toolExecutionError = err.stderr; } else { toolExecutionError = err; } //go to finally and logout of azure and set task result } finally { if (this.cliPasswordPath) { tl.debug('Removing spn certificate file'); tl.rmRF(this.cliPasswordPath); } //set the task result to either succeeded or failed based on error was thrown or not if (toolExecutionError) { tl.setResult(tl.TaskResult.Failed, tl.loc("ScriptFailed", toolExecutionError)); } else { tl.setResult(tl.TaskResult.Succeeded, tl.loc("ScriptReturnCode", 0)); } //Logout of Azure if logged in if (this.isLoggedIn) { this.logoutAzure(); } } } private static isLoggedIn: boolean = false; private static cliPasswordPath: string = null; private static servicePrincipalId: string = null; private static servicePrincipalKey: string = null; private static tenantId: string = null; private static subscriptionId: string = null; private static cloudEnvironment: string = null; private static isManagedIdentity: boolean = false; private static agentPool: string; private static agentName: string = null; private static containerName: string = null; private static containerId: string = null; private static registryUsername: string = null; private static registryPassword: string = null; private static getToken() { return tl.getInput("azureDevOpsToken", true); } private static validateInputs() { // Validate vnet. If subnetmame is specified them vnet is also mandatory var subnetName = tl.getInput("subnetName"); if (subnetName) { this.throwIf(tl.getInput("vnetName") === null, tl.loc("VnetMandatoryWithSubnet")); } var taskJSON: string = fs.readFileSync(path.join(__dirname, "task.json"), 'utf8'); var taskObject = JSON.parse(taskJSON); var missingRequiredParameters = ""; for (let input of taskObject.inputs) { if (input.required === true && input.type.indexOf(":") === -1) { if (null === tl.getInput(input.name, false)) { missingRequiredParameters += `${input.name} `; } } } this.throwIf("" !== missingRequiredParameters, tl.loc("MissingRequiredInputs", missingRequiredParameters)); } private static getRegistryCredentials(): void { let registryService = tl.getInput("containerRegistry"); if (registryService !== null) { var registryType = tl.getEndpointDataParameter(registryService, "registrytype", true); if (registryType === "ACR") { tl.debug("Using ACR"); this.registryUsername = tl.getEndpointAuthorizationParameter(registryService, 'serviceprincipalid', true); this.registryPassword = tl.getEndpointAuthorizationParameter(registryService, 'serviceprincipalkey', true); } else { tl.debug("Using generic authenticated registry"); this.registryUsername = tl.getEndpointAuthorizationParameter(registryService, 'username', true); this.registryPassword = tl.getEndpointAuthorizationParameter(registryService, 'password', true); } } else { tl.debug("not using an authenticated registry"); } } private static getSubNetId(): string { var vnetResourceGroup = tl.getInput("vnetResourceGroupName", false); var subnetName = tl.getInput("subnetName", false); if (subnetName === null) { tl.debug("Not using a subnet for container.") return null; } var vnetName = tl.getInput("vnetName", true); // If no vnet resource group was specified than use the agent resource group if (vnetResourceGroup === null) { vnetResourceGroup = tl.getInput("resourceGroupName", true); } tl.debug(`looking for subnet ${subnetName} in vnet ${vnetName} in rg ${vnetResourceGroup}`) let getVnetResult = tl.execSync("az", "network vnet subnet show --resource-group \"" + vnetResourceGroup + "\" --name \"" + subnetName + "\" --vnet-name \"" + vnetName + "\" --output json", this.execSyncSilentOption); this.throwIfError(getVnetResult, tl.loc("GetSubnetFailed", subnetName, vnetName, vnetResourceGroup)); var subnetObject = JSON.parse(getVnetResult.stdout); var subnetId = subnetObject.id; tl.debug("Using subnetId " + subnetId) return subnetId; } private static async deleteAgent(agentPoolName: string, agentName: string, token?: string) { if (token === null) { token = tl.getVariable("SYSTEM_ACCESSTOKEN"); } var taskAgent = await this.getTaskAgentAPI(token); let agentPool: TaskAgentPool[] = await taskAgent.getAgentPools(agentPoolName); var agentPoolId = agentPool[0].id; let agents = await taskAgent.getAgents(agentPoolId, agentName, false, false, false); if (agents === null || agents.length === 0) { tl.debug("No agent to delete."); } else { var agentId = agents[0].id; console.log(`deleting agent ${agentId} from pool ${agentPoolId}`); taskAgent.deleteAgent(agentPool[0].id, agentId); } } private static deleteAgentContainer() { var azTool = tl.tool(tl.which("az", true)); var resourceGroup = tl.getInput("ResourceGroupName", true); tl.debug(`deleting ${this.agentName} in rg ${resourceGroup}`) azTool .arg(["container", "delete", "--yes"]) .arg(["--name", this.containerName]) .arg(["--resource-group", resourceGroup]); var deletionResult = azTool.execSync(this.execSyncSilentOption); tl.debug("delete container returned " + deletionResult.code); if (deletionResult.code !== 0) { tl.warning("Failed to delete container " + deletionResult.error); } } private static createAgentContainer() { var azTool = tl.tool(tl.which("az", true)); var resourceGroup = tl.getInput("ResourceGroupName", true); var location = tl.getInput("location", true); var agentPrefix = tl.getInput("agentPrefix", false) || ""; var imageName = tl.getInput("imageName"); var agentPool = tl.getInput('agentPool', true); var osType = tl.getInput("osType", true); var cpu = tl.getInput("CPU", false) || "1"; var memory = tl.getInput("memory", false) || "1.0"; var addSPNToContainer = tl.getBoolInput("addSPNToContainer"); var token = tl.getInput("azureDevOpsToken", true); var currentDate = new Date(); var uniqueId = (tl.getVariable("Build_BuildId") || "") + (tl.getVariable("Release_ReleaseId") || ""); var agentName = agentPrefix.toLowerCase() + `${uniqueId}${currentDate.getFullYear()}${currentDate.getMonth()}${currentDate.getDay()}${currentDate.getHours()}${currentDate.getMinutes()}${currentDate.getSeconds()}` var containerName = agentName; this.agentName = agentName; this.containerName = containerName; this.agentPool = agentPool; console.log(`Creating container/agent ${agentName} with image ${imageName}` ); var subnetId = this.getSubNetId(); azTool .arg(["container", "create"]) .arg(["--name", containerName]) .arg(["--resource-group", resourceGroup]) .arg(["--location", location]) .arg(["--image", imageName]) .arg(["--ip-address", "private"]) .arg(["--os-type", osType]) .arg(["--cpu", cpu]) .arg(["--memory", memory]) .arg(["--restart-policy", "Never"]) .argIf(subnetId !== null, ["--subnet", subnetId]) .arg(["--environment-variables", `AZP_URL=${tl.getVariable("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI")}`, `AZP_POOL=${agentPool}`, `AZP_AGENT_NAME=${agentName}`]) .argIf(addSPNToContainer, [ `AZ_ACI_NAME=${containerName}`, `AZ_ACI_RG=${resourceGroup}`, `AZ_TENANT_ID=${this.tenantId}`, `AZ_SUBSCRIPTION_ID=${this.subscriptionId}`, `AZ_MANAGED_IDENTITY=${this.isManagedIdentity}`, `AZ_CLOUD=${this.cloudEnvironment}` ]) .arg(["--secure-environment-variables", `AZP_TOKEN=${token}`]) .argIf(addSPNToContainer, [ `AZ_SERVICE_PRINCIPAL=${this.servicePrincipalId}`, `AZ_SERVICE_PRINCIPAL_KEY=${this.servicePrincipalKey}` ]) .argIf(this.registryUsername !== null, ["--registry-username", this.registryUsername]) .argIf(this.registryUsername !== null, ["--registry-password", this.registryPassword]) .arg(["--output","json"]); var creationResult = azTool.execSync(this.execSyncSilentOption); this.throwIfError(creationResult,tl.loc("FailedContainerCreation")); var creationObject = JSON.parse(creationResult.stdout); this.containerId = creationObject.id; } private static async getTaskAgentAPI(token: string, organizationUrl?: string): Promise<taskAgentAPI.ITaskAgentApi> { organizationUrl = organizationUrl || tl.getVariable("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"); let authHandler = azdev.getPersonalAccessTokenHandler(token); let connection = new azdev.WebApi(organizationUrl, authHandler); let taskAgent: taskAgentAPI.ITaskAgentApi = await connection.getTaskAgentApi(); return taskAgent; } private static async agentPoolExists(agentPoolName: string, token?: string): Promise<boolean> { let taskAgent = await this.getTaskAgentAPI(token); console.log(`Checking if ${agentPoolName} pool exists`); if (token === null) { token = tl.getVariable("SYSTEM_ACCESSTOKEN"); } let agentPool: TaskAgentPool[] = await taskAgent.getAgentPools(agentPoolName); return agentPool !== null && agentPool.length === 1 && agentPool[0].name.toLowerCase() === agentPoolName.toLowerCase(); } private static async waitForAgentToBecomeOnline(agentPoolName: string, agentName: string, token?: string): Promise<boolean> { var maxWaitTime = tl.getInput("timeoutAgentOnline", false) || 240; if (maxWaitTime === 0) { tl.warning("Skipping check if agent is online"); return true; } if (token === null) { token = tl.getVariable("SYSTEM_ACCESSTOKEN"); } tl.debug(`wait time for agent to become online ${maxWaitTime}`); var startTime = new Date(); var taskAgent = await this.getTaskAgentAPI(token); let agentPool: TaskAgentPool[] = await taskAgent.getAgentPools(agentPoolName); this.throwIf(agentPool === null || agentPool.length === 0, tl.loc("InvalidAgentPool", agentPoolName)); var agentPoolId = agentPool[0].id; tl.debug("Agentpoold id " + agentPoolId); console.log(`checking if ${agentName} is online in agent pool ${agentPoolName} (ID: ${agentPoolId})`); while (((new Date().getTime() - startTime.getTime()) / 1000 <= maxWaitTime)) { tl.debug("checking agent status"); let agents = await taskAgent.getAgents(agentPoolId, agentName, false, false, false); if (agents !== null && agents.length > 0) { if (agents[0].status === TaskAgentStatus.Online) { console.log(`Agent ${agentName} is online. Continuing`); return true; } tl.debug("Agent status" + agents[0].status); } console.log("Sleeping before checking status again."); await this.sleepFor(8); } return false; } private static sleepFor(sleepDurationInSeconds): Promise<any> { return new Promise((resolve, reeject) => { setTimeout(resolve, sleepDurationInSeconds * 1000); }); } private static loginAzureRM(connectedService: string): void { var authScheme: string = tl.getEndpointAuthorizationScheme(connectedService, true); var subscriptionID: string = tl.getEndpointDataParameter(connectedService, "SubscriptionID", true); var tenantId: string = tl.getEndpointAuthorizationParameter(connectedService, "tenantid", false); this.subscriptionId = subscriptionID; this.tenantId = tenantId; if (authScheme.toLowerCase() == "serviceprincipal") { let authType: string = tl.getEndpointAuthorizationParameter(connectedService, 'authenticationType', true); let cliPassword: string = null; var servicePrincipalId: string = tl.getEndpointAuthorizationParameter(connectedService, "serviceprincipalid", false); this.servicePrincipalId = servicePrincipalId; if (authType == "spnCertificate") { tl.debug('certificate based endpoint'); let certificateContent: string = tl.getEndpointAuthorizationParameter(connectedService, "servicePrincipalCertificate", false); cliPassword = path.join(tl.getVariable('Agent.TempDirectory') || tl.getVariable('system.DefaultWorkingDirectory'), 'spnCert.pem'); fs.writeFileSync(cliPassword, certificateContent); this.cliPasswordPath = cliPassword; } else { tl.debug('key based endpoint'); cliPassword = tl.getEndpointAuthorizationParameter(connectedService, "serviceprincipalkey", false); this.servicePrincipalKey = cliPassword; } //login using svn this.throwIfError(tl.execSync("az", "login --service-principal -u \"" + servicePrincipalId + "\" -p \"" + cliPassword + "\" --tenant \"" + tenantId + "\""), tl.loc("LoginFailed")); } else if (authScheme.toLowerCase() == "managedserviceidentity") { //login using msi this.throwIfError(tl.execSync("az", "login --identity", this.execSyncSilentOption), tl.loc("MSILoginFailed")); this.isManagedIdentity = true; } else { throw tl.loc('AuthSchemeNotSupported', authScheme); } this.isLoggedIn = true; //set the subscription imported to the current subscription this.throwIfError(tl.execSync("az", "account set --subscription \"" + subscriptionID + "\"", this.execSyncSilentOption), tl.loc("ErrorInSettingUpSubscription")); } private static setConfigDirectory(): void { if (tl.getBoolInput("useGlobalConfig")) { return; } if (!!tl.getVariable('Agent.TempDirectory')) { var azCliConfigPath = path.join(tl.getVariable('Agent.TempDirectory'), ".azclitask"); console.log(tl.loc('SettingAzureConfigDir', azCliConfigPath)); process.env['AZURE_CONFIG_DIR'] = azCliConfigPath; } else { console.warn(tl.loc('GlobalCliConfigAgentVersionWarning')); } } private static setAzureCloudBasedOnServiceEndpoint(): void { var connectedService: string = tl.getInput("connectedServiceNameARM", true); var environment = tl.getEndpointDataParameter(connectedService, 'environment', true); if (!!environment) { console.log(tl.loc('SettingAzureCloud', environment)); this.throwIfError(tl.execSync("az", "cloud set -n " + environment, this.execSyncSilentOption)); this.cloudEnvironment = environment; } } private static logoutAzure() { tl.debug("logoutAzure"); try { tl.execSync("az", " account clear", this.execSyncSilentOption); } catch (err) { // task should not fail if logout doesn`t occur tl.warning(tl.loc("FailedToLogout")); } } private static throwIf(isError: boolean, errormsg?: string): void { if (isError) { if (errormsg) { tl.error("Error: " + errormsg); } throw "error"; } } private static throwIfError(resultOfToolExecution: IExecSyncResult, errormsg?: string): void { if (resultOfToolExecution.code != 0) { tl.error("Error Code: [" + resultOfToolExecution.code + "]"); if (errormsg) { tl.error("Error: " + errormsg); } throw resultOfToolExecution; } } } tl.setResourcePath(path.join(__dirname, "task.json")); if (!azurecontainercreate.checkIfAzurePythonSdkIsInstalled()) { tl.setResult(tl.TaskResult.Failed, tl.loc("AzureSDKNotFound")); } azurecontainercreate.runMain();
the_stack
import * as iam from '@aws-cdk/aws-iam'; import * as secretsmanager from '@aws-cdk/aws-secretsmanager'; import { IEngine } from './engine'; import { IOptionGroup } from './option-group'; import { Construct } from '@aws-cdk/core'; /** * The options passed to {@link IInstanceEngine.bind}. * * @stability stable */ export interface InstanceEngineBindOptions { /** * The Active Directory directory ID to create the DB instance in. * * @default - none (it's an optional field) * @stability stable */ readonly domain?: string; /** * The timezone of the database, set by the customer. * * @default - none (it's an optional field) * @stability stable */ readonly timezone?: string; /** * The role used for S3 importing. * * @default - none * @stability stable */ readonly s3ImportRole?: iam.IRole; /** * The role used for S3 exporting. * * @default - none * @stability stable */ readonly s3ExportRole?: iam.IRole; /** * The option group of the database. * * @default - none * @stability stable */ readonly optionGroup?: IOptionGroup; } /** * The type returned from the {@link IInstanceEngine.bind} method. * * @stability stable */ export interface InstanceEngineConfig { /** * Features supported by the database engine. * * @default - no features * @see https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DBEngineVersion.html * @stability stable */ readonly features?: InstanceEngineFeatures; /** * Option group of the database. * * @default - none * @stability stable */ readonly optionGroup?: IOptionGroup; } /** * Represents Database Engine features. * * @stability stable */ export interface InstanceEngineFeatures { /** * Feature name for the DB instance that the IAM role to access the S3 bucket for import is to be associated with. * * @default - no s3Import feature name * @stability stable */ readonly s3Import?: string; /** * Feature name for the DB instance that the IAM role to export to S3 bucket is to be associated with. * * @default - no s3Export feature name * @stability stable */ readonly s3Export?: string; } /** * Interface representing a database instance (as opposed to cluster) engine. * * @stability stable */ export interface IInstanceEngine extends IEngine { /** * The application used by this engine to perform rotation for a single-user scenario. * * @stability stable */ readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication; /** * The application used by this engine to perform rotation for a multi-user scenario. * * @stability stable */ readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication; /** * Method called when the engine is used to create a new instance. * * @stability stable */ bindToInstance(scope: Construct, options: InstanceEngineBindOptions): InstanceEngineConfig; } /** * The versions for the MariaDB instance engines (those returned by {@link DatabaseInstanceEngine.mariaDb}). * * @stability stable */ export declare class MariaDbEngineVersion { /** * Version "10.0" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_10_0: MariaDbEngineVersion; /** * Version "10.0.17". * * @stability stable */ static readonly VER_10_0_17: MariaDbEngineVersion; /** * Version "10.0.24". * * @stability stable */ static readonly VER_10_0_24: MariaDbEngineVersion; /** * Version "10.0.28". * * @stability stable */ static readonly VER_10_0_28: MariaDbEngineVersion; /** * Version "10.0.31". * * @stability stable */ static readonly VER_10_0_31: MariaDbEngineVersion; /** * Version "10.0.32". * * @stability stable */ static readonly VER_10_0_32: MariaDbEngineVersion; /** * Version "10.0.34". * * @stability stable */ static readonly VER_10_0_34: MariaDbEngineVersion; /** * Version "10.0.35". * * @stability stable */ static readonly VER_10_0_35: MariaDbEngineVersion; /** * Version "10.1" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_10_1: MariaDbEngineVersion; /** * Version "10.1.14". * * @stability stable */ static readonly VER_10_1_14: MariaDbEngineVersion; /** * Version "10.1.19". * * @stability stable */ static readonly VER_10_1_19: MariaDbEngineVersion; /** * Version "10.1.23". * * @stability stable */ static readonly VER_10_1_23: MariaDbEngineVersion; /** * Version "10.1.26". * * @stability stable */ static readonly VER_10_1_26: MariaDbEngineVersion; /** * Version "10.1.31". * * @stability stable */ static readonly VER_10_1_31: MariaDbEngineVersion; /** * Version "10.1.34". * * @stability stable */ static readonly VER_10_1_34: MariaDbEngineVersion; /** * Version "10.2" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_10_2: MariaDbEngineVersion; /** * Version "10.2.11". * * @stability stable */ static readonly VER_10_2_11: MariaDbEngineVersion; /** * Version "10.2.12". * * @stability stable */ static readonly VER_10_2_12: MariaDbEngineVersion; /** * Version "10.2.15". * * @stability stable */ static readonly VER_10_2_15: MariaDbEngineVersion; /** * Version "10.2.21". * * @stability stable */ static readonly VER_10_2_21: MariaDbEngineVersion; /** * Version "10.3" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_10_3: MariaDbEngineVersion; /** * Version "10.3.8". * * @stability stable */ static readonly VER_10_3_8: MariaDbEngineVersion; /** * Version "10.3.13". * * @stability stable */ static readonly VER_10_3_13: MariaDbEngineVersion; /** * Version "10.3.20". * * @stability stable */ static readonly VER_10_3_20: MariaDbEngineVersion; /** * Version "10.3.23". * * @stability stable */ static readonly VER_10_3_23: MariaDbEngineVersion; /** * Version "10.4" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_10_4: MariaDbEngineVersion; /** * Version "10.4.8". * * @stability stable */ static readonly VER_10_4_8: MariaDbEngineVersion; /** * Version "10.4.13". * * @stability stable */ static readonly VER_10_4_13: MariaDbEngineVersion; /** * Create a new MariaDbEngineVersion with an arbitrary version. * * @param mariaDbFullVersion the full version string, for example "10.5.28". * @param mariaDbMajorVersion the major version of the engine, for example "10.5". * @stability stable */ static of(mariaDbFullVersion: string, mariaDbMajorVersion: string): MariaDbEngineVersion; /** * The full version string, for example, "10.5.28". * * @stability stable */ readonly mariaDbFullVersion: string; /** * The major version of the engine, for example, "10.5". * * @stability stable */ readonly mariaDbMajorVersion: string; private constructor(); } /** * Properties for MariaDB instance engines. * * Used in {@link DatabaseInstanceEngine.mariaDb}. * * @stability stable */ export interface MariaDbInstanceEngineProps { /** * The exact version of the engine to use. * * @stability stable */ readonly version: MariaDbEngineVersion; } /** * The versions for the MySQL instance engines (those returned by {@link DatabaseInstanceEngine.mysql}). * * @stability stable */ export declare class MysqlEngineVersion { /** * Version "5.5" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_5_5: MysqlEngineVersion; /** * Version "5.5.46". * * @stability stable */ static readonly VER_5_5_46: MysqlEngineVersion; /** * Version "5.5.53". * * @stability stable */ static readonly VER_5_5_53: MysqlEngineVersion; /** * Version "5.5.57". * * @stability stable */ static readonly VER_5_5_57: MysqlEngineVersion; /** * Version "5.5.59". * * @stability stable */ static readonly VER_5_5_59: MysqlEngineVersion; /** * Version "5.5.61". * * @stability stable */ static readonly VER_5_5_61: MysqlEngineVersion; /** * Version "5.6" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_5_6: MysqlEngineVersion; /** * Version "5.6.34". * * @stability stable */ static readonly VER_5_6_34: MysqlEngineVersion; /** * Version "5.6.35". * * @stability stable */ static readonly VER_5_6_35: MysqlEngineVersion; /** * Version "5.6.37". * * @stability stable */ static readonly VER_5_6_37: MysqlEngineVersion; /** * Version "5.6.39". * * @stability stable */ static readonly VER_5_6_39: MysqlEngineVersion; /** * Version "5.6.40". * * @stability stable */ static readonly VER_5_6_40: MysqlEngineVersion; /** * Version "5.6.41". * * @stability stable */ static readonly VER_5_6_41: MysqlEngineVersion; /** * Version "5.6.43". * * @stability stable */ static readonly VER_5_6_43: MysqlEngineVersion; /** * Version "5.6.44". * * @stability stable */ static readonly VER_5_6_44: MysqlEngineVersion; /** * Version "5.6.46". * * @stability stable */ static readonly VER_5_6_46: MysqlEngineVersion; /** * Version "5.6.48". * * @stability stable */ static readonly VER_5_6_48: MysqlEngineVersion; /** * Version "5.7" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_5_7: MysqlEngineVersion; /** * Version "5.7.16". * * @stability stable */ static readonly VER_5_7_16: MysqlEngineVersion; /** * Version "5.7.17". * * @stability stable */ static readonly VER_5_7_17: MysqlEngineVersion; /** * Version "5.7.19". * * @stability stable */ static readonly VER_5_7_19: MysqlEngineVersion; /** * Version "5.7.21". * * @stability stable */ static readonly VER_5_7_21: MysqlEngineVersion; /** * Version "5.7.22". * * @stability stable */ static readonly VER_5_7_22: MysqlEngineVersion; /** * Version "5.7.23". * * @stability stable */ static readonly VER_5_7_23: MysqlEngineVersion; /** * Version "5.7.24". * * @stability stable */ static readonly VER_5_7_24: MysqlEngineVersion; /** * Version "5.7.25". * * @stability stable */ static readonly VER_5_7_25: MysqlEngineVersion; /** * Version "5.7.26". * * @stability stable */ static readonly VER_5_7_26: MysqlEngineVersion; /** * Version "5.7.28". * * @stability stable */ static readonly VER_5_7_28: MysqlEngineVersion; /** * Version "5.7.30". * * @stability stable */ static readonly VER_5_7_30: MysqlEngineVersion; /** * Version "5.7.31". * * @stability stable */ static readonly VER_5_7_31: MysqlEngineVersion; /** * Version "8.0" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_8_0: MysqlEngineVersion; /** * Version "8.0.11". * * @stability stable */ static readonly VER_8_0_11: MysqlEngineVersion; /** * Version "8.0.13". * * @stability stable */ static readonly VER_8_0_13: MysqlEngineVersion; /** * Version "8.0.15". * * @stability stable */ static readonly VER_8_0_15: MysqlEngineVersion; /** * Version "8.0.16". * * @stability stable */ static readonly VER_8_0_16: MysqlEngineVersion; /** * Version "8.0.17". * * @stability stable */ static readonly VER_8_0_17: MysqlEngineVersion; /** * Version "8.0.19". * * @stability stable */ static readonly VER_8_0_19: MysqlEngineVersion; /** * Version "8.0.20 ". * * @stability stable */ static readonly VER_8_0_20: MysqlEngineVersion; /** * Version "8.0.21 ". * * @stability stable */ static readonly VER_8_0_21: MysqlEngineVersion; /** * Create a new MysqlEngineVersion with an arbitrary version. * * @param mysqlFullVersion the full version string, for example "8.1.43". * @param mysqlMajorVersion the major version of the engine, for example "8.1". * @stability stable */ static of(mysqlFullVersion: string, mysqlMajorVersion: string): MysqlEngineVersion; /** * The full version string, for example, "10.5.28". * * @stability stable */ readonly mysqlFullVersion: string; /** * The major version of the engine, for example, "10.5". * * @stability stable */ readonly mysqlMajorVersion: string; private constructor(); } /** * Properties for MySQL instance engines. * * Used in {@link DatabaseInstanceEngine.mysql}. * * @stability stable */ export interface MySqlInstanceEngineProps { /** * The exact version of the engine to use. * * @stability stable */ readonly version: MysqlEngineVersion; } /** * Features supported by the Postgres database engine. * * @stability stable */ export interface PostgresEngineFeatures { /** * Whether this version of the Postgres engine supports the S3 data import feature. * * @default false * @stability stable */ readonly s3Import?: boolean; } /** * The versions for the PostgreSQL instance engines (those returned by {@link DatabaseInstanceEngine.postgres}). * * @stability stable */ export declare class PostgresEngineVersion { /** * Version "9.5" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_9_5: PostgresEngineVersion; /** * Version "9.5.2". * * @stability stable */ static readonly VER_9_5_2: PostgresEngineVersion; /** * Version "9.5.4". * * @stability stable */ static readonly VER_9_5_4: PostgresEngineVersion; /** * Version "9.5.6". * * @stability stable */ static readonly VER_9_5_6: PostgresEngineVersion; /** * Version "9.5.7". * * @stability stable */ static readonly VER_9_5_7: PostgresEngineVersion; /** * Version "9.5.9". * * @stability stable */ static readonly VER_9_5_9: PostgresEngineVersion; /** * Version "9.5.10". * * @stability stable */ static readonly VER_9_5_10: PostgresEngineVersion; /** * Version "9.5.12". * * @stability stable */ static readonly VER_9_5_12: PostgresEngineVersion; /** * Version "9.5.13". * * @stability stable */ static readonly VER_9_5_13: PostgresEngineVersion; /** * Version "9.5.14". * * @stability stable */ static readonly VER_9_5_14: PostgresEngineVersion; /** * Version "9.5.15". * * @stability stable */ static readonly VER_9_5_15: PostgresEngineVersion; /** * Version "9.5.16". * * @stability stable */ static readonly VER_9_5_16: PostgresEngineVersion; /** * Version "9.5.18". * * @stability stable */ static readonly VER_9_5_18: PostgresEngineVersion; /** * Version "9.5.19". * * @stability stable */ static readonly VER_9_5_19: PostgresEngineVersion; /** * Version "9.5.20". * * @stability stable */ static readonly VER_9_5_20: PostgresEngineVersion; /** * Version "9.5.21". * * @stability stable */ static readonly VER_9_5_21: PostgresEngineVersion; /** * Version "9.5.22". * * @stability stable */ static readonly VER_9_5_22: PostgresEngineVersion; /** * Version "9.5.23". * * @stability stable */ static readonly VER_9_5_23: PostgresEngineVersion; /** * Version "9.6" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_9_6: PostgresEngineVersion; /** * Version "9.6.1". * * @stability stable */ static readonly VER_9_6_1: PostgresEngineVersion; /** * Version "9.6.2". * * @stability stable */ static readonly VER_9_6_2: PostgresEngineVersion; /** * Version "9.6.3". * * @stability stable */ static readonly VER_9_6_3: PostgresEngineVersion; /** * Version "9.6.5". * * @stability stable */ static readonly VER_9_6_5: PostgresEngineVersion; /** * Version "9.6.6". * * @stability stable */ static readonly VER_9_6_6: PostgresEngineVersion; /** * Version "9.6.8". * * @stability stable */ static readonly VER_9_6_8: PostgresEngineVersion; /** * Version "9.6.9". * * @stability stable */ static readonly VER_9_6_9: PostgresEngineVersion; /** * Version "9.6.10". * * @stability stable */ static readonly VER_9_6_10: PostgresEngineVersion; /** * Version "9.6.11". * * @stability stable */ static readonly VER_9_6_11: PostgresEngineVersion; /** * Version "9.6.12". * * @stability stable */ static readonly VER_9_6_12: PostgresEngineVersion; /** * Version "9.6.14". * * @stability stable */ static readonly VER_9_6_14: PostgresEngineVersion; /** * Version "9.6.15". * * @stability stable */ static readonly VER_9_6_15: PostgresEngineVersion; /** * Version "9.6.16". * * @stability stable */ static readonly VER_9_6_16: PostgresEngineVersion; /** * Version "9.6.17". * * @stability stable */ static readonly VER_9_6_17: PostgresEngineVersion; /** * Version "9.6.18". * * @stability stable */ static readonly VER_9_6_18: PostgresEngineVersion; /** * Version "9.6.19". * * @stability stable */ static readonly VER_9_6_19: PostgresEngineVersion; /** * Version "10" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_10: PostgresEngineVersion; /** * Version "10.1". * * @stability stable */ static readonly VER_10_1: PostgresEngineVersion; /** * Version "10.3". * * @stability stable */ static readonly VER_10_3: PostgresEngineVersion; /** * Version "10.4". * * @stability stable */ static readonly VER_10_4: PostgresEngineVersion; /** * Version "10.5". * * @stability stable */ static readonly VER_10_5: PostgresEngineVersion; /** * Version "10.6". * * @stability stable */ static readonly VER_10_6: PostgresEngineVersion; /** * Version "10.7". * * @stability stable */ static readonly VER_10_7: PostgresEngineVersion; /** * Version "10.9". * * @stability stable */ static readonly VER_10_9: PostgresEngineVersion; /** * Version "10.10". * * @stability stable */ static readonly VER_10_10: PostgresEngineVersion; /** * Version "10.11". * * @stability stable */ static readonly VER_10_11: PostgresEngineVersion; /** * Version "10.12". * * @stability stable */ static readonly VER_10_12: PostgresEngineVersion; /** * Version "10.13". * * @stability stable */ static readonly VER_10_13: PostgresEngineVersion; /** * Version "10.14". * * @stability stable */ static readonly VER_10_14: PostgresEngineVersion; /** * Version "11" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_11: PostgresEngineVersion; /** * Version "11.1". * * @stability stable */ static readonly VER_11_1: PostgresEngineVersion; /** * Version "11.2". * * @stability stable */ static readonly VER_11_2: PostgresEngineVersion; /** * Version "11.4". * * @stability stable */ static readonly VER_11_4: PostgresEngineVersion; /** * Version "11.5". * * @stability stable */ static readonly VER_11_5: PostgresEngineVersion; /** * Version "11.6". * * @stability stable */ static readonly VER_11_6: PostgresEngineVersion; /** * Version "11.7". * * @stability stable */ static readonly VER_11_7: PostgresEngineVersion; /** * Version "11.8". * * @stability stable */ static readonly VER_11_8: PostgresEngineVersion; /** * Version "11.9". * * @stability stable */ static readonly VER_11_9: PostgresEngineVersion; /** * Version "12" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_12: PostgresEngineVersion; /** * Version "12.2". * * @stability stable */ static readonly VER_12_2: PostgresEngineVersion; /** * Version "12.3". * * @stability stable */ static readonly VER_12_3: PostgresEngineVersion; /** * Version "12.4". * * @stability stable */ static readonly VER_12_4: PostgresEngineVersion; /** * Create a new PostgresEngineVersion with an arbitrary version. * * @param postgresFullVersion the full version string, for example "13.11". * @param postgresMajorVersion the major version of the engine, for example "13". * @stability stable */ static of(postgresFullVersion: string, postgresMajorVersion: string, postgresFeatures?: PostgresEngineFeatures): PostgresEngineVersion; /** * The full version string, for example, "13.11". * * @stability stable */ readonly postgresFullVersion: string; /** * The major version of the engine, for example, "13". * * @stability stable */ readonly postgresMajorVersion: string; /** * The supported features for the DB engine * @internal */ readonly _features: InstanceEngineFeatures; private constructor(); } /** * Properties for PostgreSQL instance engines. * * Used in {@link DatabaseInstanceEngine.postgres}. * * @stability stable */ export interface PostgresInstanceEngineProps { /** * The exact version of the engine to use. * * @stability stable */ readonly version: PostgresEngineVersion; } /** * (deprecated) The versions for the legacy Oracle instance engines (those returned by {@link DatabaseInstanceEngine.oracleSe} and {@link DatabaseInstanceEngine.oracleSe1}). Note: RDS will stop allowing creating new databases with this version in August 2020. * * @deprecated instances can no longer be created with these engine versions. See https://forums.aws.amazon.com/ann.jspa?annID=7341 */ export declare class OracleLegacyEngineVersion { /** * (deprecated) Version "11.2" (only a major version, without a specific minor version). * * @deprecated */ static readonly VER_11_2: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.2.v2". * * @deprecated */ static readonly VER_11_2_0_2_V2: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v1". * * @deprecated */ static readonly VER_11_2_0_4_V1: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v3". * * @deprecated */ static readonly VER_11_2_0_4_V3: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v4". * * @deprecated */ static readonly VER_11_2_0_4_V4: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v5". * * @deprecated */ static readonly VER_11_2_0_4_V5: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v6". * * @deprecated */ static readonly VER_11_2_0_4_V6: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v7". * * @deprecated */ static readonly VER_11_2_0_4_V7: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v8". * * @deprecated */ static readonly VER_11_2_0_4_V8: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v9". * * @deprecated */ static readonly VER_11_2_0_4_V9: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v10". * * @deprecated */ static readonly VER_11_2_0_4_V10: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v11". * * @deprecated */ static readonly VER_11_2_0_4_V11: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v12". * * @deprecated */ static readonly VER_11_2_0_4_V12: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v13". * * @deprecated */ static readonly VER_11_2_0_4_V13: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v14". * * @deprecated */ static readonly VER_11_2_0_4_V14: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v15". * * @deprecated */ static readonly VER_11_2_0_4_V15: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v16". * * @deprecated */ static readonly VER_11_2_0_4_V16: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v17". * * @deprecated */ static readonly VER_11_2_0_4_V17: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v18". * * @deprecated */ static readonly VER_11_2_0_4_V18: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v19". * * @deprecated */ static readonly VER_11_2_0_4_V19: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v20". * * @deprecated */ static readonly VER_11_2_0_4_V20: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v21". * * @deprecated */ static readonly VER_11_2_0_4_V21: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v22". * * @deprecated */ static readonly VER_11_2_0_4_V22: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v23". * * @deprecated */ static readonly VER_11_2_0_4_V23: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v24". * * @deprecated */ static readonly VER_11_2_0_4_V24: OracleLegacyEngineVersion; /** * (deprecated) Version "11.2.0.4.v25". * * @deprecated */ static readonly VER_11_2_0_4_V25: OracleLegacyEngineVersion; private static of; /** * (deprecated) The full version string, for example, "11.2.0.4.v24". * * @deprecated */ readonly oracleLegacyFullVersion: string; /** * (deprecated) The major version of the engine, for example, "11.2". * * @deprecated */ readonly oracleLegacyMajorVersion: string; private constructor(); } /** * The versions for the Oracle instance engines (those returned by {@link DatabaseInstanceEngine.oracleSe2} and {@link DatabaseInstanceEngine.oracleEe}). * * @stability stable */ export declare class OracleEngineVersion { /** * Version "12.1" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_12_1: OracleEngineVersion; /** * Version "12.1.0.2.v1". * * @stability stable */ static readonly VER_12_1_0_2_V1: OracleEngineVersion; /** * Version "12.1.0.2.v2". * * @stability stable */ static readonly VER_12_1_0_2_V2: OracleEngineVersion; /** * Version "12.1.0.2.v3". * * @stability stable */ static readonly VER_12_1_0_2_V3: OracleEngineVersion; /** * Version "12.1.0.2.v4". * * @stability stable */ static readonly VER_12_1_0_2_V4: OracleEngineVersion; /** * Version "12.1.0.2.v5". * * @stability stable */ static readonly VER_12_1_0_2_V5: OracleEngineVersion; /** * Version "12.1.0.2.v6". * * @stability stable */ static readonly VER_12_1_0_2_V6: OracleEngineVersion; /** * Version "12.1.0.2.v7". * * @stability stable */ static readonly VER_12_1_0_2_V7: OracleEngineVersion; /** * Version "12.1.0.2.v8". * * @stability stable */ static readonly VER_12_1_0_2_V8: OracleEngineVersion; /** * Version "12.1.0.2.v9". * * @stability stable */ static readonly VER_12_1_0_2_V9: OracleEngineVersion; /** * Version "12.1.0.2.v10". * * @stability stable */ static readonly VER_12_1_0_2_V10: OracleEngineVersion; /** * Version "12.1.0.2.v11". * * @stability stable */ static readonly VER_12_1_0_2_V11: OracleEngineVersion; /** * Version "12.1.0.2.v12". * * @stability stable */ static readonly VER_12_1_0_2_V12: OracleEngineVersion; /** * Version "12.1.0.2.v13". * * @stability stable */ static readonly VER_12_1_0_2_V13: OracleEngineVersion; /** * Version "12.1.0.2.v14". * * @stability stable */ static readonly VER_12_1_0_2_V14: OracleEngineVersion; /** * Version "12.1.0.2.v15". * * @stability stable */ static readonly VER_12_1_0_2_V15: OracleEngineVersion; /** * Version "12.1.0.2.v16". * * @stability stable */ static readonly VER_12_1_0_2_V16: OracleEngineVersion; /** * Version "12.1.0.2.v17". * * @stability stable */ static readonly VER_12_1_0_2_V17: OracleEngineVersion; /** * Version "12.1.0.2.v18". * * @stability stable */ static readonly VER_12_1_0_2_V18: OracleEngineVersion; /** * Version "12.1.0.2.v19". * * @stability stable */ static readonly VER_12_1_0_2_V19: OracleEngineVersion; /** * Version "12.1.0.2.v20". * * @stability stable */ static readonly VER_12_1_0_2_V20: OracleEngineVersion; /** * Version "12.1.0.2.v21". * * @stability stable */ static readonly VER_12_1_0_2_V21: OracleEngineVersion; /** * Version "12.2" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_12_2: OracleEngineVersion; /** * Version "12.2.0.1.ru-2018-10.rur-2018-10.r1". * * @stability stable */ static readonly VER_12_2_0_1_2018_10_R1: OracleEngineVersion; /** * Version "12.2.0.1.ru-2019-01.rur-2019-01.r1". * * @stability stable */ static readonly VER_12_2_0_1_2019_01_R1: OracleEngineVersion; /** * Version "12.2.0.1.ru-2019-04.rur-2019-04.r1". * * @stability stable */ static readonly VER_12_2_0_1_2019_04_R1: OracleEngineVersion; /** * Version "12.2.0.1.ru-2019-07.rur-2019-07.r1". * * @stability stable */ static readonly VER_12_2_0_1_2019_07_R1: OracleEngineVersion; /** * Version "12.2.0.1.ru-2019-10.rur-2019-10.r1". * * @stability stable */ static readonly VER_12_2_0_1_2019_10_R1: OracleEngineVersion; /** * Version "12.2.0.1.ru-2020-01.rur-2020-01.r1". * * @stability stable */ static readonly VER_12_2_0_1_2020_01_R1: OracleEngineVersion; /** * Version "12.2.0.1.ru-2020-04.rur-2020-04.r1". * * @stability stable */ static readonly VER_12_2_0_1_2020_04_R1: OracleEngineVersion; /** * Version "12.2.0.1.ru-2020-07.rur-2020-07.r1". * * @stability stable */ static readonly VER_12_2_0_1_2020_07_R1: OracleEngineVersion; /** * Version "18" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_18: OracleEngineVersion; /** * Version "18.0.0.0.ru-2019-07.rur-2019-07.r1". * * @stability stable */ static readonly VER_18_0_0_0_2019_07_R1: OracleEngineVersion; /** * Version "18.0.0.0.ru-2019-10.rur-2019-10.r1". * * @stability stable */ static readonly VER_18_0_0_0_2019_10_R1: OracleEngineVersion; /** * Version "18.0.0.0.ru-2020-01.rur-2020-01.r1". * * @stability stable */ static readonly VER_18_0_0_0_2020_01_R1: OracleEngineVersion; /** * Version "18.0.0.0.ru-2020-04.rur-2020-04.r1". * * @stability stable */ static readonly VER_18_0_0_0_2020_04_R1: OracleEngineVersion; /** * Version "18.0.0.0.ru-2020-07.rur-2020-07.r1". * * @stability stable */ static readonly VER_18_0_0_0_2020_07_R1: OracleEngineVersion; /** * Version "19" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_19: OracleEngineVersion; /** * Version "19.0.0.0.ru-2019-07.rur-2019-07.r1". * * @stability stable */ static readonly VER_19_0_0_0_2019_07_R1: OracleEngineVersion; /** * Version "19.0.0.0.ru-2019-10.rur-2019-10.r1". * * @stability stable */ static readonly VER_19_0_0_0_2019_10_R1: OracleEngineVersion; /** * Version "19.0.0.0.ru-2020-01.rur-2020-01.r1". * * @stability stable */ static readonly VER_19_0_0_0_2020_01_R1: OracleEngineVersion; /** * Version "19.0.0.0.ru-2020-04.rur-2020-04.r1". * * @stability stable */ static readonly VER_19_0_0_0_2020_04_R1: OracleEngineVersion; /** * Version "19.0.0.0.ru-2020-07.rur-2020-07.r1". * * @stability stable */ static readonly VER_19_0_0_0_2020_07_R1: OracleEngineVersion; /** * Creates a new OracleEngineVersion with an arbitrary version. * * @param oracleFullVersion the full version string, for example "19.0.0.0.ru-2019-10.rur-2019-10.r1". * @param oracleMajorVersion the major version of the engine, for example "19". * @stability stable */ static of(oracleFullVersion: string, oracleMajorVersion: string): OracleEngineVersion; /** * The full version string, for example, "19.0.0.0.ru-2019-10.rur-2019-10.r1". * * @stability stable */ readonly oracleFullVersion: string; /** * The major version of the engine, for example, "19". * * @stability stable */ readonly oracleMajorVersion: string; private constructor(); } interface OracleInstanceEngineProps { /** * The exact version of the engine to use. * * @stability stable */ readonly version: OracleEngineVersion; } /** * (deprecated) Properties for Oracle Standard Edition instance engines. * * Used in {@link DatabaseInstanceEngine.oracleSe}. * * @deprecated instances can no longer be created with this engine. See https://forums.aws.amazon.com/ann.jspa?annID=7341 */ export interface OracleSeInstanceEngineProps { /** * (deprecated) The exact version of the engine to use. * * @deprecated */ readonly version: OracleLegacyEngineVersion; } /** * (deprecated) Properties for Oracle Standard Edition 1 instance engines. * * Used in {@link DatabaseInstanceEngine.oracleSe1}. * * @deprecated instances can no longer be created with this engine. See https://forums.aws.amazon.com/ann.jspa?annID=7341 */ export interface OracleSe1InstanceEngineProps { /** * (deprecated) The exact version of the engine to use. * * @deprecated */ readonly version: OracleLegacyEngineVersion; } /** * Properties for Oracle Standard Edition 2 instance engines. * * Used in {@link DatabaseInstanceEngine.oracleSe2}. * * @stability stable */ export interface OracleSe2InstanceEngineProps extends OracleInstanceEngineProps { } /** * Properties for Oracle Enterprise Edition instance engines. * * Used in {@link DatabaseInstanceEngine.oracleEe}. * * @stability stable */ export interface OracleEeInstanceEngineProps extends OracleInstanceEngineProps { } /** * The versions for the SQL Server instance engines (those returned by {@link DatabaseInstanceEngine.sqlServerSe}, {@link DatabaseInstanceEngine.sqlServerEx}, {@link DatabaseInstanceEngine.sqlServerWeb} and {@link DatabaseInstanceEngine.sqlServerEe}). * * @stability stable */ export declare class SqlServerEngineVersion { /** * Version "11.00" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_11: SqlServerEngineVersion; /** * Version "11.00.5058.0.v1". * * @stability stable */ static readonly VER_11_00_5058_0_V1: SqlServerEngineVersion; /** * Version "11.00.6020.0.v1". * * @stability stable */ static readonly VER_11_00_6020_0_V1: SqlServerEngineVersion; /** * Version "11.00.6594.0.v1". * * @stability stable */ static readonly VER_11_00_6594_0_V1: SqlServerEngineVersion; /** * Version "11.00.7462.6.v1". * * @stability stable */ static readonly VER_11_00_7462_6_V1: SqlServerEngineVersion; /** * Version "11.00.7493.4.v1". * * @stability stable */ static readonly VER_11_00_7493_4_V1: SqlServerEngineVersion; /** * Version "12.00" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_12: SqlServerEngineVersion; /** * Version "12.00.5000.0.v1". * * @stability stable */ static readonly VER_12_00_5000_0_V1: SqlServerEngineVersion; /** * Version "12.00.5546.0.v1". * * @stability stable */ static readonly VER_12_00_5546_0_V1: SqlServerEngineVersion; /** * Version "12.00.5571.0.v1". * * @stability stable */ static readonly VER_12_00_5571_0_V1: SqlServerEngineVersion; /** * Version "12.00.6293.0.v1". * * @stability stable */ static readonly VER_12_00_6293_0_V1: SqlServerEngineVersion; /** * Version "12.00.6329.1.v1". * * @stability stable */ static readonly VER_12_00_6329_1_V1: SqlServerEngineVersion; /** * Version "13.00" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_13: SqlServerEngineVersion; /** * Version "13.00.2164.0.v1". * * @stability stable */ static readonly VER_13_00_2164_0_V1: SqlServerEngineVersion; /** * Version "13.00.4422.0.v1". * * @stability stable */ static readonly VER_13_00_4422_0_V1: SqlServerEngineVersion; /** * Version "13.00.4451.0.v1". * * @stability stable */ static readonly VER_13_00_4451_0_V1: SqlServerEngineVersion; /** * Version "13.00.4466.4.v1". * * @stability stable */ static readonly VER_13_00_4466_4_V1: SqlServerEngineVersion; /** * Version "13.00.4522.0.v1". * * @stability stable */ static readonly VER_13_00_4522_0_V1: SqlServerEngineVersion; /** * Version "13.00.5216.0.v1". * * @stability stable */ static readonly VER_13_00_5216_0_V1: SqlServerEngineVersion; /** * Version "13.00.5292.0.v1". * * @stability stable */ static readonly VER_13_00_5292_0_V1: SqlServerEngineVersion; /** * Version "13.00.5366.0.v1". * * @stability stable */ static readonly VER_13_00_5366_0_V1: SqlServerEngineVersion; /** * Version "13.00.5426.0.v1". * * @stability stable */ static readonly VER_13_00_5426_0_V1: SqlServerEngineVersion; /** * Version "13.00.5598.27.v1". * * @stability stable */ static readonly VER_13_00_5598_27_V1: SqlServerEngineVersion; /** * Version "13.00.5820.21.v1". * * @stability stable */ static readonly VER_13_00_5820_21_V1: SqlServerEngineVersion; /** * Version "14.00" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_14: SqlServerEngineVersion; /** * Version "14.00.1000.169.v1". * * @stability stable */ static readonly VER_14_00_1000_169_V1: SqlServerEngineVersion; /** * Version "14.00.3015.40.v1". * * @stability stable */ static readonly VER_14_00_3015_40_V1: SqlServerEngineVersion; /** * Version "14.00.3035.2.v1". * * @stability stable */ static readonly VER_14_00_3035_2_V1: SqlServerEngineVersion; /** * Version "14.00.3049.1.v1". * * @stability stable */ static readonly VER_14_00_3049_1_V1: SqlServerEngineVersion; /** * Version "14.00.3192.2.v1". * * @stability stable */ static readonly VER_14_00_3192_2_V1: SqlServerEngineVersion; /** * Version "14.00.3223.3.v1". * * @stability stable */ static readonly VER_14_00_3223_3_V1: SqlServerEngineVersion; /** * Version "14.00.3281.6.v1". * * @stability stable */ static readonly VER_14_00_3281_6_V1: SqlServerEngineVersion; /** * Version "14.00.3294.2.v1". * * @stability stable */ static readonly VER_14_00_3294_2_V1: SqlServerEngineVersion; /** * Version "15.00" (only a major version, without a specific minor version). * * @stability stable */ static readonly VER_15: SqlServerEngineVersion; /** * Version "15.00.4043.16.v1". * * @stability stable */ static readonly VER_15_00_4043_16_V1: SqlServerEngineVersion; /** * Create a new SqlServerEngineVersion with an arbitrary version. * * @param sqlServerFullVersion the full version string, for example "15.00.3049.1.v1". * @param sqlServerMajorVersion the major version of the engine, for example "15.00". * @stability stable */ static of(sqlServerFullVersion: string, sqlServerMajorVersion: string): SqlServerEngineVersion; /** * The full version string, for example, "15.00.3049.1.v1". * * @stability stable */ readonly sqlServerFullVersion: string; /** * The major version of the engine, for example, "15.00". * * @stability stable */ readonly sqlServerMajorVersion: string; private constructor(); } interface SqlServerInstanceEngineProps { /** * The exact version of the engine to use. * * @stability stable */ readonly version: SqlServerEngineVersion; } /** * Properties for SQL Server Standard Edition instance engines. * * Used in {@link DatabaseInstanceEngine.sqlServerSe}. * * @stability stable */ export interface SqlServerSeInstanceEngineProps extends SqlServerInstanceEngineProps { } /** * Properties for SQL Server Express Edition instance engines. * * Used in {@link DatabaseInstanceEngine.sqlServerEx}. * * @stability stable */ export interface SqlServerExInstanceEngineProps extends SqlServerInstanceEngineProps { } /** * Properties for SQL Server Web Edition instance engines. * * Used in {@link DatabaseInstanceEngine.sqlServerWeb}. * * @stability stable */ export interface SqlServerWebInstanceEngineProps extends SqlServerInstanceEngineProps { } /** * Properties for SQL Server Enterprise Edition instance engines. * * Used in {@link DatabaseInstanceEngine.sqlServerEe}. * * @stability stable */ export interface SqlServerEeInstanceEngineProps extends SqlServerInstanceEngineProps { } /** * A database instance engine. * * Provides mapping to DatabaseEngine used for * secret rotation. * * @stability stable */ export declare class DatabaseInstanceEngine { /** * (deprecated) The unversioned 'mariadb' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link mariaDb()} method */ static readonly MARIADB: IInstanceEngine; /** * (deprecated) The unversioned 'mysql' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link mysql()} method */ static readonly MYSQL: IInstanceEngine; /** * (deprecated) The unversioned 'oracle-ee' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link oracleEe()} method */ static readonly ORACLE_EE: IInstanceEngine; /** * (deprecated) The unversioned 'oracle-se2' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link oracleSe2()} method */ static readonly ORACLE_SE2: IInstanceEngine; /** * (deprecated) The unversioned 'oracle-se1' instance engine. * * @deprecated instances can no longer be created with this engine. See https://forums.aws.amazon.com/ann.jspa?annID=7341 */ static readonly ORACLE_SE1: IInstanceEngine; /** * (deprecated) The unversioned 'oracle-se' instance engine. * * @deprecated instances can no longer be created with this engine. See https://forums.aws.amazon.com/ann.jspa?annID=7341 */ static readonly ORACLE_SE: IInstanceEngine; /** * (deprecated) The unversioned 'postgres' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link postgres()} method */ static readonly POSTGRES: IInstanceEngine; /** * (deprecated) The unversioned 'sqlserver-ee' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link sqlServerEe()} method */ static readonly SQL_SERVER_EE: IInstanceEngine; /** * (deprecated) The unversioned 'sqlserver-se' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link sqlServerSe()} method */ static readonly SQL_SERVER_SE: IInstanceEngine; /** * (deprecated) The unversioned 'sqlserver-ex' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link sqlServerEx()} method */ static readonly SQL_SERVER_EX: IInstanceEngine; /** * (deprecated) The unversioned 'sqlserver-web' instance engine. * * @deprecated using unversioned engines is an availability risk. * We recommend using versioned engines created using the {@link sqlServerWeb()} method */ static readonly SQL_SERVER_WEB: IInstanceEngine; /** * Creates a new MariaDB instance engine. * * @stability stable */ static mariaDb(props: MariaDbInstanceEngineProps): IInstanceEngine; /** * Creates a new MySQL instance engine. * * @stability stable */ static mysql(props: MySqlInstanceEngineProps): IInstanceEngine; /** * Creates a new PostgreSQL instance engine. * * @stability stable */ static postgres(props: PostgresInstanceEngineProps): IInstanceEngine; /** * (deprecated) Creates a new Oracle Standard Edition instance engine. * * @deprecated instances can no longer be created with this engine. See https://forums.aws.amazon.com/ann.jspa?annID=7341 */ static oracleSe(props: OracleSeInstanceEngineProps): IInstanceEngine; /** * (deprecated) Creates a new Oracle Standard Edition 1 instance engine. * * @deprecated instances can no longer be created with this engine. See https://forums.aws.amazon.com/ann.jspa?annID=7341 */ static oracleSe1(props: OracleSe1InstanceEngineProps): IInstanceEngine; /** * Creates a new Oracle Standard Edition 1 instance engine. * * @stability stable */ static oracleSe2(props: OracleSe2InstanceEngineProps): IInstanceEngine; /** * Creates a new Oracle Enterprise Edition instance engine. * * @stability stable */ static oracleEe(props: OracleEeInstanceEngineProps): IInstanceEngine; /** * Creates a new SQL Server Standard Edition instance engine. * * @stability stable */ static sqlServerSe(props: SqlServerSeInstanceEngineProps): IInstanceEngine; /** * Creates a new SQL Server Express Edition instance engine. * * @stability stable */ static sqlServerEx(props: SqlServerExInstanceEngineProps): IInstanceEngine; /** * Creates a new SQL Server Web Edition instance engine. * * @stability stable */ static sqlServerWeb(props: SqlServerWebInstanceEngineProps): IInstanceEngine; /** * Creates a new SQL Server Enterprise Edition instance engine. * * @stability stable */ static sqlServerEe(props: SqlServerEeInstanceEngineProps): IInstanceEngine; } export {};
the_stack