text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {
DescriptorProto,
EnumDescriptorProto,
EnumValueDescriptorProto,
FieldDescriptorProto,
FieldDescriptorProto_Type,
FieldOptions_JSType,
FileDescriptorProto,
MethodDescriptorProto,
OneofDescriptorProto,
ServiceDescriptorProto
} from "./google/protobuf/descriptor";
import {AnyDescriptorProto, IDescriptorInfo, isAnyTypeDescriptorProto, ScalarValueType} from "./descriptor-info";
import {IDescriptorTree} from "./descriptor-tree";
import {ISourceCodeInfoLookup} from "./source-code-info";
import {ITypeNameLookup} from "./type-names";
import {assert, assertNever} from "@protobuf-ts/runtime";
export interface IStringFormat {
/**
* Returns type ('message', 'field', etc.) and descriptor name.
*
* Examples:
* message Bar
* field value = 2
* rpc Fetch()
*/
formatName(descriptor: AnyDescriptorProto): string;
/**
* Returns qualified name, consisting of:
* - keyword like "message", "enum", etc. followed by " "
* - package name followed by "."
* - parent type descriptor names separated by "."
* - descriptor name
*
* Examples:
* message .foo.Bar
* field .foo.Bar.value = 2
* rpc .foo.Service.Fetch()
*
* If `includeFileInfo` is set, the name of the file containing
* the descriptor is added, including line number.
*/
formatQualifiedName(descriptor: AnyDescriptorProto, includeFileInfo?: boolean): string;
/**
* Returns field declaration, similar to how it appeared
* in the .proto file.
*
* Examples:
* repeated string foo = 1 [deprecated = true];
* .foo.Bar bar = 2 [json_name = "baz"];
* map<string, .foo.Bar> map = 3;
* uint64 foo = 4 [jstype = JS_NUMBER];
*/
formatFieldDeclaration(descriptor: FieldDescriptorProto): string;
/**
* Returns declaration of enum value, similar to how it
* appeared in the .proto file.
*
* Examples:
* STATE_UNKNOWN = 0;
* STATE_READY = 1 [deprecated = true];
*/
formatEnumValueDeclaration(descriptor: EnumValueDescriptorProto): string;
/**
* Returns declaration of an rpc method, similar to how
* it appeared in the .proto file, but does not show any options.
*
* Examples:
* rpc Fetch(FetchRequest) returns (stream FetchResponse);
*/
formatRpcDeclaration(descriptor: MethodDescriptorProto): string;
}
export class StringFormat implements IStringFormat {
private readonly nameLookup: ITypeNameLookup;
private readonly treeLookup: IDescriptorTree;
private readonly sourceCodeLookup: ISourceCodeInfoLookup;
private readonly descriptorInfo: IDescriptorInfo;
constructor(lookup: ITypeNameLookup & IDescriptorTree & ISourceCodeInfoLookup & IDescriptorInfo);
constructor(nameLookup: ITypeNameLookup, treeLookup: IDescriptorTree, sourceCodeLookup: ISourceCodeInfoLookup, descriptorInfo: IDescriptorInfo);
constructor(a: any, b?: any, c?: any, d?: any) {
if (b === undefined) {
this.nameLookup = a;
this.treeLookup = a;
this.sourceCodeLookup = a;
this.descriptorInfo = a;
} else {
this.nameLookup = a;
this.treeLookup = b;
this.sourceCodeLookup = c;
this.descriptorInfo = d;
}
}
/**
* Returns name of a scalar value type like it would
* appear in a .proto.
*
* For example, `FieldDescriptorProto_Type.UINT32` -> `"uint32"`.
*/
static formatScalarType(type: ScalarValueType): string {
let name = FieldDescriptorProto_Type[type];
assert(name !== undefined, "unexpected ScalarValueType " + type);
return name.toLowerCase();
}
/**
* Returns type ('message', 'field', etc.) and descriptor name.
*
* Examples:
* message Bar
* field value = 2
* rpc Fetch()
*/
static formatName(descriptor: AnyDescriptorProto): string {
if (FileDescriptorProto.is(descriptor)) {
return `file ${descriptor.name}`;
} else if (DescriptorProto.is(descriptor)) {
return `message ${descriptor.name}`;
} else if (FieldDescriptorProto.is(descriptor)) {
if (descriptor.extendee !== undefined) {
return `extension field ${descriptor.name} = ${descriptor.number}`;
}
return `field ${descriptor.name} = ${descriptor.number}`;
} else if (EnumDescriptorProto.is(descriptor)) {
return `enum ${descriptor.name}`;
} else if (EnumValueDescriptorProto.is(descriptor)) {
return `enum value ${descriptor.name} = ${descriptor.number}`;
} else if (ServiceDescriptorProto.is(descriptor)) {
return `service ${descriptor.name}`;
} else if (MethodDescriptorProto.is(descriptor)) {
return `rpc ${descriptor.name}()`;
} else
// noinspection SuspiciousTypeOfGuard
if (OneofDescriptorProto.is(descriptor)) {
return `oneof ${descriptor.name}`;
}
assertNever(descriptor);
assert(false);
}
formatQualifiedName(descriptor: AnyDescriptorProto, includeFileInfo: boolean): string {
if (FileDescriptorProto.is(descriptor)) {
return `file ${descriptor.name}`;
}
const file = includeFileInfo ? ' in ' + getSourceWithLineNo(descriptor, this.treeLookup, this.sourceCodeLookup) : '';
if (DescriptorProto.is(descriptor)) {
return `message ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
if (EnumDescriptorProto.is(descriptor)) {
return `enum ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
if (ServiceDescriptorProto.is(descriptor)) {
return `service ${this.nameLookup.makeTypeName(descriptor)}${file}`;
}
let parent = this.treeLookup.parentOf(descriptor);
if (FieldDescriptorProto.is(descriptor) && this.descriptorInfo.isExtension(descriptor)) {
let extensionName = this.descriptorInfo.getExtensionName(descriptor);
assert(descriptor.extendee);
let extendeeTypeName = this.nameLookup.normalizeTypeName(descriptor.extendee);
return `extension ${extendeeTypeName}.(${extensionName})${file}`;
}
assert(isAnyTypeDescriptorProto(parent));
let parentTypeName = this.nameLookup.makeTypeName(parent);
if (FieldDescriptorProto.is(descriptor)) {
return `field ${parentTypeName}.${descriptor.name}${file}`;
}
if (EnumValueDescriptorProto.is(descriptor)) {
return `enum value ${parentTypeName}.${descriptor.name}${file}`;
}
if (MethodDescriptorProto.is(descriptor)) {
return `rpc ${parentTypeName}.${descriptor.name}()${file}`;
}
return `oneof ${parentTypeName}.${descriptor.name}${file}`;
}
formatName(descriptor: AnyDescriptorProto): string {
return StringFormat.formatName(descriptor);
}
formatFieldDeclaration(descriptor: FieldDescriptorProto): string {
let text = '';
// repeated ?
if (this.descriptorInfo.isUserDeclaredRepeated(descriptor)) {
text += 'repeated ';
}
// optional ?
if (this.descriptorInfo.isUserDeclaredOptional(descriptor)) {
text += 'optional ';
}
switch (descriptor.type) {
case FieldDescriptorProto_Type.ENUM:
text += this.nameLookup.makeTypeName(
this.descriptorInfo.getEnumFieldEnum(descriptor)
);
break;
case FieldDescriptorProto_Type.MESSAGE:
if (this.descriptorInfo.isMapField(descriptor)) {
let mapK = StringFormat.formatScalarType(
this.descriptorInfo.getMapKeyType(descriptor)
);
let mapVType = this.descriptorInfo.getMapValueType(descriptor);
let mapV = typeof mapVType === "number"
? StringFormat.formatScalarType(mapVType)
: this.nameLookup.makeTypeName(mapVType);
text += `map<${mapK}, ${mapV}>`;
} else {
text += this.nameLookup.makeTypeName(
this.descriptorInfo.getMessageFieldMessage(descriptor)
);
}
break;
case FieldDescriptorProto_Type.DOUBLE:
case FieldDescriptorProto_Type.FLOAT:
case FieldDescriptorProto_Type.INT64:
case FieldDescriptorProto_Type.UINT64:
case FieldDescriptorProto_Type.INT32:
case FieldDescriptorProto_Type.FIXED64:
case FieldDescriptorProto_Type.FIXED32:
case FieldDescriptorProto_Type.BOOL:
case FieldDescriptorProto_Type.STRING:
case FieldDescriptorProto_Type.BYTES:
case FieldDescriptorProto_Type.UINT32:
case FieldDescriptorProto_Type.SFIXED32:
case FieldDescriptorProto_Type.SFIXED64:
case FieldDescriptorProto_Type.SINT32:
case FieldDescriptorProto_Type.SINT64:
text += StringFormat.formatScalarType(descriptor.type);
break;
case FieldDescriptorProto_Type.GROUP:
text += "group";
break;
case FieldDescriptorProto_Type.UNSPECIFIED$:
text += "???";
break;
}
// name
text += ' ' + descriptor.name;
// number
text += ' = ' + descriptor.number;
// options
let options = [];
if (this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor)) {
options.push('deprecated = true');
}
if (this.descriptorInfo.getFieldCustomJsonName(descriptor)) {
options.push(`json_name = "${this.descriptorInfo.getFieldCustomJsonName(descriptor)}"`);
}
if (descriptor.options?.jstype == FieldOptions_JSType.JS_STRING) {
options.push(`jstype = JS_STRING`);
}
if (descriptor.options?.jstype == FieldOptions_JSType.JS_NUMBER) {
options.push(`jstype = JS_NUMBER`);
}
if (descriptor.options?.jstype == FieldOptions_JSType.JS_NORMAL) {
options.push(`jstype = JS_NORMAL`);
}
if (descriptor.options?.packed === true) {
options.push(`packed = true`);
}
if (descriptor.options?.packed === false) {
options.push(`packed = false`);
}
if (options.length) {
text += ' [' + options.join(', ') + ']';
}
// semicolon
text += ';';
return text;
}
formatEnumValueDeclaration(descriptor: EnumValueDescriptorProto): string {
let text = `${descriptor.name} = ${descriptor.number}`;
if (this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor)) {
text += ' [deprecated = true]';
}
return text + ';';
}
formatRpcDeclaration(descriptor: MethodDescriptorProto): string {
this.descriptorInfo.isExplicitlyDeclaredDeprecated(descriptor)
let
m = descriptor.name!,
i = descriptor.inputType!,
is = descriptor.clientStreaming ? 'stream ' : '',
o = descriptor.outputType!,
os = descriptor.serverStreaming ? 'stream ' : '';
if (i.startsWith('.')) {
i = i.substring(1);
}
if (o.startsWith('.')) {
o = o.substring(1);
}
return `${m}(${is}${i}) returns (${os}${o});`;
}
}
function getSourceWithLineNo(descriptor: AnyDescriptorProto, treeLookup: IDescriptorTree, sourceCodeLookup: ISourceCodeInfoLookup): string {
let
file = treeLookup.fileOf(descriptor),
[l] = sourceCodeLookup.sourceCodeCursor(descriptor);
return `${file.name}:${l}`;
} | the_stack |
import * as markdownit from 'markdown-it'
import * as path from 'path'
import * as vscode from 'vscode'
import { withLanguageClient } from '../extension'
import { constructCommandString, getVersionedParamsAtPosition, registerCommand } from '../utils'
function openArgs(href: string) {
const matches = href.match(/^((\w+\:\/\/)?.+?)(?:[\:#](\d+))?$/)
let uri
let line
if (matches[1] && matches[3] && matches[2] === undefined) {
uri = matches[1]
line = parseInt(matches[3])
} else {
uri = vscode.Uri.parse(matches[1])
}
return { uri, line }
}
const md = new markdownit().use(
require('@traptitech/markdown-it-katex'),
{
output: 'html'
}
).use(
require('markdown-it-footnote')
)
// add custom validator to allow for file:// links
const BAD_PROTO_RE = /^(vbscript|javascript|data):/
const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/
md.validateLink = (url) => {
// url should be normalized at this point, and existing entities are decoded
const str = url.trim().toLowerCase()
return BAD_PROTO_RE.test(str) ? (GOOD_DATA_RE.test(str) ? true : false) : true
}
md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
const aIndex = tokens[idx].attrIndex('href')
if (aIndex >= 0 && tokens[idx].attrs[aIndex][1] === '@ref' && tokens.length > idx + 1) {
const commandUri = constructCommandString('language-julia.search-word', { searchTerm: tokens[idx + 1].content })
tokens[idx].attrs[aIndex][1] = vscode.Uri.parse(commandUri).toString()
} else if (aIndex >= 0 && tokens.length > idx + 1) {
const href = tokens[idx + 1].content
const { uri, line } = openArgs(href)
let commandUri
if (line === undefined) {
commandUri = constructCommandString('vscode.open', uri)
} else {
commandUri = constructCommandString('language-julia.openFile', { path: uri, line })
}
tokens[idx].attrs[aIndex][1] = commandUri
}
return self.renderToken(tokens, idx, options)
}
export function activate(context: vscode.ExtensionContext) {
const provider = new DocumentationViewProvider(context)
context.subscriptions.push(
registerCommand('language-julia.show-documentation-pane', () => provider.showDocumentationPane()),
registerCommand('language-julia.show-documentation', () => provider.showDocumentation()),
registerCommand('language-julia.browse-back-documentation', () => provider.browseBack()),
registerCommand('language-julia.browse-forward-documentation', () => provider.browseForward()),
registerCommand('language-julia.search-word', (params) => provider.findHelp(params)),
vscode.window.registerWebviewViewProvider('julia-documentation', provider)
)
}
class DocumentationViewProvider implements vscode.WebviewViewProvider {
private view?: vscode.WebviewView
private context: vscode.ExtensionContext
private backStack = Array<string>() // also keep current page
private forwardStack = Array<string>()
constructor(context) {
this.context = context
}
resolveWebviewView(view: vscode.WebviewView, context: vscode.WebviewViewResolveContext) {
this.view = view
view.webview.options = {
enableScripts: true,
enableCommandUris: true
}
view.webview.html = this.createWebviewHTML('Use the `language-julia.show-documentation` command in an editor or search for documentation above.')
view.webview.onDidReceiveMessage(msg => {
if (msg.type === 'search') {
this.showDocumentationFromWord(msg.query)
} else {
console.error('unknown message received')
}
})
}
findHelp(params: { searchTerm: string }) {
this.showDocumentationFromWord(params.searchTerm)
}
async showDocumentationPane() {
if (this.view?.show === undefined) {
// this forces the webview to be resolved, but changes focus:
await vscode.commands.executeCommand('julia-documentation.focus')
}
this.view.show(true)
}
async showDocumentationFromWord(word: string) {
const docAsMD = await this.getDocumentationFromWord(word)
if (!docAsMD) { return }
await this.showDocumentationPane()
const html = this.createWebviewHTML(docAsMD)
this.setHTML(html)
}
async getDocumentationFromWord(word: string): Promise<string> {
return await withLanguageClient(
async languageClient => {
return await languageClient.sendRequest('julia/getDocFromWord', { word: word })
}, err => {
console.error('LC request failed with ', err)
return ''
}
)
}
async showDocumentation() {
// telemetry.traceEvent('command-showdocumentation')
const editor = vscode.window.activeTextEditor
if (!editor) { return }
const docAsMD = await this.getDocumentation(editor)
if (!docAsMD) { return }
this.forwardStack = [] // initialize forward page stack for manual search
await this.showDocumentationPane()
const html = this.createWebviewHTML(docAsMD)
this.setHTML(html)
}
async getDocumentation(editor: vscode.TextEditor): Promise<string> {
return await withLanguageClient(
async languageClient => {
return await languageClient.sendRequest<string>('julia/getDocAt', getVersionedParamsAtPosition(editor.document, editor.selection.start))
}, err => {
console.error('LC request failed with ', err)
return ''
}
)
}
createWebviewHTML(docAsMD: string) {
const docAsHTML = md.render(docAsMD)
const extensionPath = this.context.extensionPath
const googleFontscss = this.view.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'libs', 'google_fonts', 'css')))
const fontawesomecss = this.view.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'libs', 'fontawesome', 'fontawesome.min.css')))
const solidcss = this.view.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'libs', 'fontawesome', 'solid.min.css')))
const brandscss = this.view.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'libs', 'fontawesome', 'brands.min.css')))
const documenterStylesheetcss = this.view.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'libs', 'documenter', 'documenter-vscode.css')))
const katexcss = this.view.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'libs', 'katex', 'katex.min.css')))
const webfontjs = this.view.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'libs', 'webfont', 'webfont.js')))
return `
<html lang="en" class='theme--documenter-vscode'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Julia Documentation Pane</title>
<link href=${googleFontscss} rel="stylesheet" type="text/css" />
<link href=${fontawesomecss} rel="stylesheet" type="text/css" />
<link href=${solidcss} rel="stylesheet" type="text/css" />
<link href=${brandscss} rel="stylesheet" type="text/css" />
<link href=${katexcss} rel="stylesheet" type="text/css" />
<link href=${documenterStylesheetcss} rel="stylesheet" type="text/css">
<script type="text/javascript">
WebFontConfig = {
custom: {
families: ['KaTeX_AMS', 'KaTeX_Caligraphic:n4,n7', 'KaTeX_Fraktur:n4,n7','KaTeX_Main:n4,n7,i4,i7', 'KaTeX_Math:i4,i7', 'KaTeX_Script','KaTeX_SansSerif:n4,n7,i4', 'KaTeX_Size1', 'KaTeX_Size2', 'KaTeX_Size3', 'KaTeX_Size4', 'KaTeX_Typewriter'],
urls: ['${katexcss}']
},
}
</script>
<style>
body {
word-break: normal;
overflow-wrap: break-word;
}
body:active {
outline: 1px solid var(--vscode-focusBorder);
}
.search {
position: fixed;
background-color: var(--vscode-sideBar-background);
width: 100%;
padding: 5px;
display: flex;
z-index: 2;
}
.search input[type="text"] {
width: 100%;
background-color: var(--vscode-input-background);
border: none;
outline: none;
color: var(--vscode-input-foreground);
padding: 4px;
}
.search input[type="text"]:focus {
outline: 1px solid var(--vscode-editorWidget-border);
}
button {
width: 30px;
margin: 0 5px 0 0;
display: inline;
border: none;
box-sizing: border-box;
padding: 5px 7px;
text-align: center;
cursor: pointer;
justify-content: center;
align-items: center;
background-color: var(--vscode-button-background);
color: var(--vscode-button-foreground);
font-family: var(--vscode-font-family);
}
button:hover {
background-color: var(--vscode-button-hoverBackground);
}
button:focus {
outline: 1px solid var(--vscode-focusBorder);
outline-offset: 0px;
}
</style>
<script src=${webfontjs}></script>
</head>
<body>
<div class="search">
<input id="search-input" type="text" placeholder="Search"></input>
</div>
<div class="docs-main" style="padding: 50px 1em 1em 1em">
<article class="content">
${docAsHTML}
</article>
</div>
<script>
const vscode = acquireVsCodeApi()
function search(val) {
if (val) {
vscode.postMessage({
type: 'search',
query: val
})
}
}
function onKeyDown(ev) {
if (ev && ev.keyCode === 13) {
const val = document.getElementById('search-input').value
search(val)
}
}
document.getElementById('search-input').addEventListener('keydown', onKeyDown)
</script>
</body>
</html>
`
}
setHTML(html: string) {
// set current stack
this.backStack.push(html)
if (this.view) {
this.view.webview.html = html
}
}
isBrowseBackAvailable() {
return this.backStack.length > 1
}
isBrowseForwardAvailable() {
return this.forwardStack.length > 0
}
browseBack() {
if (!this.isBrowseBackAvailable()) { return }
const current = this.backStack.pop()
this.forwardStack.push(current)
this.setHTML(this.backStack.pop())
}
browseForward() {
if (!this.isBrowseForwardAvailable()) { return }
this.setHTML(this.forwardStack.pop())
}
} | the_stack |
import React, {
FC, useCallback, useEffect, useRef, useState,
} from 'react';
import { useUserUISettings } from '~/client/services/user-ui-settings';
import {
useDrawerMode, useDrawerOpened,
useSidebarCollapsed,
useCurrentSidebarContents,
useCurrentProductNavWidth,
useSidebarResizeDisabled,
useSidebarScrollerRef,
} from '~/stores/ui';
import DrawerToggler from './Navbar/DrawerToggler';
import SidebarNav from './Sidebar/SidebarNav';
import SidebarContents from './Sidebar/SidebarContents';
import { NavigationResizeHexagon } from './Sidebar/NavigationResizeHexagon';
import { StickyStretchableScroller } from './StickyStretchableScroller';
const sidebarMinWidth = 240;
const sidebarMinimizeWidth = 20;
const sidebarFixedWidthInDrawerMode = 320;
const GlobalNavigation = () => {
const { data: isDrawerMode } = useDrawerMode();
const { data: currentContents } = useCurrentSidebarContents();
const { data: isCollapsed, mutate: mutateSidebarCollapsed } = useSidebarCollapsed();
const { scheduleToPut } = useUserUISettings();
const itemSelectedHandler = useCallback((selectedContents) => {
if (isDrawerMode) {
return;
}
let newValue = false;
// already selected
if (currentContents === selectedContents) {
// toggle collapsed
newValue = !isCollapsed;
}
mutateSidebarCollapsed(newValue, false);
scheduleToPut({ isSidebarCollapsed: newValue });
}, [currentContents, isCollapsed, isDrawerMode, mutateSidebarCollapsed, scheduleToPut]);
return <SidebarNav onItemSelected={itemSelectedHandler} />;
};
const SidebarContentsWrapper = () => {
const { mutate: mutateSidebarScroller } = useSidebarScrollerRef();
const calcViewHeight = useCallback(() => {
const elem = document.querySelector('#grw-sidebar-contents-wrapper');
return elem != null
? window.innerHeight - elem?.getBoundingClientRect().top
: window.innerHeight;
}, []);
return (
<>
<div id="grw-sidebar-contents-wrapper" style={{ minHeight: '100%' }}>
<StickyStretchableScroller
simplebarRef={mutateSidebarScroller}
stickyElemSelector=".grw-sidebar"
calcViewHeight={calcViewHeight}
>
<SidebarContents />
</StickyStretchableScroller>
</div>
<DrawerToggler iconClass="icon-arrow-left" />
</>
);
};
type Props = {
}
const Sidebar: FC<Props> = (props: Props) => {
const { data: isDrawerMode } = useDrawerMode();
const { data: isDrawerOpened, mutate: mutateDrawerOpened } = useDrawerOpened();
const { data: currentProductNavWidth, mutate: mutateProductNavWidth } = useCurrentProductNavWidth();
const { data: isCollapsed, mutate: mutateSidebarCollapsed } = useSidebarCollapsed();
const { data: isResizeDisabled, mutate: mutateSidebarResizeDisabled } = useSidebarResizeDisabled();
const { scheduleToPut } = useUserUISettings();
const [isTransitionEnabled, setTransitionEnabled] = useState(false);
const [isHover, setHover] = useState(false);
const [isHoverOnResizableContainer, setHoverOnResizableContainer] = useState(false);
const [isDragging, setDrag] = useState(false);
const resizableContainer = useRef<HTMLDivElement>(null);
const timeoutIdRef = useRef<NodeJS.Timeout>();
const isResizableByDrag = !isResizeDisabled && !isDrawerMode && (!isCollapsed || isHover);
const toggleDrawerMode = useCallback((bool) => {
const isStateModified = isResizeDisabled !== bool;
if (!isStateModified) {
return;
}
// Drawer <-- Dock
if (bool) {
// disable resize
mutateSidebarResizeDisabled(true, false);
}
// Drawer --> Dock
else {
// enable resize
mutateSidebarResizeDisabled(false, false);
}
}, [isResizeDisabled, mutateSidebarResizeDisabled]);
const backdropClickedHandler = useCallback(() => {
mutateDrawerOpened(false, false);
}, [mutateDrawerOpened]);
const setContentWidth = useCallback((newWidth: number) => {
if (resizableContainer.current == null) {
return;
}
resizableContainer.current.style.width = `${newWidth}px`;
}, []);
const hoverOnHandler = useCallback(() => {
if (!isCollapsed || isDrawerMode || isDragging) {
return;
}
setHover(true);
}, [isCollapsed, isDragging, isDrawerMode]);
const hoverOutHandler = useCallback(() => {
if (!isCollapsed || isDrawerMode || isDragging) {
return;
}
setHover(false);
}, [isCollapsed, isDragging, isDrawerMode]);
const hoverOnResizableContainerHandler = useCallback(() => {
if (!isCollapsed || isDrawerMode || isDragging) {
return;
}
setHoverOnResizableContainer(true);
}, [isCollapsed, isDrawerMode, isDragging]);
const hoverOutResizableContainerHandler = useCallback(() => {
if (!isCollapsed || isDrawerMode || isDragging) {
return;
}
setHoverOnResizableContainer(false);
}, [isCollapsed, isDrawerMode, isDragging]);
const toggleNavigationBtnClickHandler = useCallback(() => {
const newValue = !isCollapsed;
mutateSidebarCollapsed(newValue, false);
scheduleToPut({ isSidebarCollapsed: newValue });
}, [isCollapsed, mutateSidebarCollapsed, scheduleToPut]);
useEffect(() => {
if (isCollapsed) {
setContentWidth(sidebarMinimizeWidth);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
setContentWidth(currentProductNavWidth!);
}
}, [currentProductNavWidth, isCollapsed, setContentWidth]);
const draggableAreaMoveHandler = useCallback((event: MouseEvent) => {
event.preventDefault();
const newWidth = event.pageX - 60;
if (resizableContainer.current != null) {
setContentWidth(newWidth);
resizableContainer.current.classList.add('dragging');
}
}, [setContentWidth]);
const dragableAreaMouseUpHandler = useCallback(() => {
if (resizableContainer.current == null) {
return;
}
setDrag(false);
if (resizableContainer.current.clientWidth < sidebarMinWidth) {
// force collapsed
mutateSidebarCollapsed(true);
mutateProductNavWidth(sidebarMinWidth, false);
scheduleToPut({ isSidebarCollapsed: true, currentProductNavWidth: sidebarMinWidth });
}
else {
const newWidth = resizableContainer.current.clientWidth;
mutateSidebarCollapsed(false);
mutateProductNavWidth(newWidth, false);
scheduleToPut({ isSidebarCollapsed: false, currentProductNavWidth: newWidth });
}
resizableContainer.current.classList.remove('dragging');
}, [mutateProductNavWidth, mutateSidebarCollapsed, scheduleToPut]);
const dragableAreaMouseDownHandler = useCallback((event: React.MouseEvent) => {
if (!isResizableByDrag) {
return;
}
event.preventDefault();
setDrag(true);
const removeEventListeners = () => {
document.removeEventListener('mousemove', draggableAreaMoveHandler);
document.removeEventListener('mouseup', dragableAreaMouseUpHandler);
document.removeEventListener('mouseup', removeEventListeners);
};
document.addEventListener('mousemove', draggableAreaMoveHandler);
document.addEventListener('mouseup', dragableAreaMouseUpHandler);
document.addEventListener('mouseup', removeEventListeners);
}, [dragableAreaMouseUpHandler, draggableAreaMoveHandler, isResizableByDrag]);
useEffect(() => {
setTimeout(() => {
setTransitionEnabled(true);
}, 1000);
}, []);
useEffect(() => {
toggleDrawerMode(isDrawerMode);
}, [isDrawerMode, toggleDrawerMode]);
// open/close resizable container
useEffect(() => {
if (!isCollapsed) {
return;
}
if (isHoverOnResizableContainer) {
// schedule to open
timeoutIdRef.current = setTimeout(() => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
setContentWidth(currentProductNavWidth!);
}, 70);
}
else if (timeoutIdRef.current != null) {
// cancel schedule to open
clearTimeout(timeoutIdRef.current);
timeoutIdRef.current = undefined;
}
// close
if (!isHover) {
setContentWidth(sidebarMinimizeWidth);
timeoutIdRef.current = undefined;
}
}, [isCollapsed, isHover, isHoverOnResizableContainer, currentProductNavWidth, setContentWidth]);
// open/close resizable container when drawer mode
useEffect(() => {
if (isDrawerMode) {
setContentWidth(sidebarFixedWidthInDrawerMode);
}
else if (isCollapsed) {
setContentWidth(sidebarMinimizeWidth);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
setContentWidth(currentProductNavWidth!);
}
}, [currentProductNavWidth, isCollapsed, isDrawerMode, setContentWidth]);
const showContents = isDrawerMode || isHover || !isCollapsed;
return (
<>
<div className={`grw-sidebar d-print-none ${isDrawerMode ? 'grw-sidebar-drawer' : ''} ${isDrawerOpened ? 'open' : ''}`}>
<div className="data-layout-container">
<div
className={`navigation ${isTransitionEnabled ? 'transition-enabled' : ''}`}
onMouseEnter={hoverOnHandler}
onMouseLeave={hoverOutHandler}
>
<div className="grw-navigation-wrap">
<div className="grw-global-navigation">
<GlobalNavigation></GlobalNavigation>
</div>
<div
ref={resizableContainer}
className="grw-contextual-navigation"
onMouseEnter={hoverOnResizableContainerHandler}
onMouseLeave={hoverOutResizableContainerHandler}
style={{ width: isCollapsed ? sidebarMinimizeWidth : currentProductNavWidth }}
>
<div className="grw-contextual-navigation-child">
<div role="group" data-testid="grw-contextual-navigation-sub" className={`grw-contextual-navigation-sub ${showContents ? '' : 'd-none'}`}>
<SidebarContentsWrapper></SidebarContentsWrapper>
</div>
</div>
</div>
</div>
<div className="grw-navigation-draggable">
{ isResizableByDrag && (
<div
className="grw-navigation-draggable-hitarea"
onMouseDown={dragableAreaMouseDownHandler}
>
<div className="grw-navigation-draggable-hitarea-child"></div>
</div>
) }
<button
data-testid="grw-navigation-resize-button"
className={`grw-navigation-resize-button ${!isDrawerMode ? 'resizable' : ''} ${isCollapsed ? 'collapsed' : ''} `}
type="button"
aria-expanded="true"
aria-label="Toggle navigation"
disabled={isDrawerMode}
onClick={toggleNavigationBtnClickHandler}
>
<span className="hexagon-container" role="presentation">
<NavigationResizeHexagon />
</span>
<span className="hitarea" role="presentation"></span>
</button>
</div>
</div>
</div>
</div>
{ isDrawerOpened && (
<div className="grw-sidebar-backdrop modal-backdrop show" onClick={backdropClickedHandler}></div>
) }
</>
);
};
export default Sidebar; | the_stack |
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { FocusArbitratorProvider } from '../common/utils/AutoFocusHelper';
import { Types } from '../common/Interfaces';
import { applyFocusableComponentMixin } from './utils/FocusManager';
import { isEmpty } from './utils/lodashMini';
import Styles from './Styles';
export interface TextInputState {
inputValue?: string;
autoResize?: boolean;
}
const _isMac = (typeof navigator !== 'undefined') && (typeof navigator.platform === 'string') && (navigator.platform.indexOf('Mac') >= 0);
// Cast to any to allow merging of web and RX styles
const _styles = {
defaultStyle: {
position: 'relative',
display: 'flex',
flexDirection: 'row',
flexBasis: 'auto',
flexGrow: 0,
flexShrink: 0,
overflowX: 'hidden',
overflowY: 'auto',
alignItems: 'stretch',
} as any,
formStyle: {
display: 'flex',
flex: 1,
} as any,
};
export interface TextInputContext {
focusArbitrator?: FocusArbitratorProvider;
}
interface TextInputPlaceholderCacheItem {
refCounter: number;
styleElement: HTMLStyleElement;
}
class TextInputPlaceholderSupport {
private static _cachedStyles: { [color: string]: TextInputPlaceholderCacheItem } = {};
static getClassName(color: string): string {
const key = this._colorKey(color);
return `reactxp-placeholder-${key}`;
}
static addRef(color: string) {
if (typeof document === undefined) {
return;
}
const cache = this._cachedStyles;
const key = this._colorKey(color);
if (cache.hasOwnProperty(key)) {
cache[key].refCounter++;
} else {
const className = this.getClassName(color);
const style = document.createElement('style');
style.type = 'text/css';
style.textContent = this._getStyle(className, color);
document.head.appendChild(style);
cache[key] = {
refCounter: 1,
styleElement: style,
};
}
}
static removeRef(color: string) {
const cache = this._cachedStyles;
const key = this._colorKey(color);
if (cache.hasOwnProperty(key)) {
const item = cache[key];
if (--item.refCounter < 1) {
const styleElement = item.styleElement;
if (styleElement.parentNode) {
styleElement.parentNode.removeChild(styleElement);
}
delete cache[key];
}
}
}
private static _colorKey(color: string): string {
return color.toLowerCase()
.replace(/(,|\.|#)/g, '_')
.replace(/[^a-z0-9_]/g, '');
}
private static _getStyle(className: string, placeholderColor: string): string {
const selectors = [
'::placeholder', // Modern browsers
'::-webkit-input-placeholder', // Webkit
'::-moz-placeholder', // Firefox 19+
':-moz-placeholder', // Firefox 18-
':-ms-input-placeholder', // IE 10+
];
return selectors
.map(pseudoSelector =>
`.${className}${pseudoSelector} {\n` +
` opacity: 1;\n` +
` color: ${placeholderColor};\n` +
`}`,
).join('\n');
}
}
export class TextInput extends React.Component<Types.TextInputProps, TextInputState> {
static contextTypes: React.ValidationMap<any> = {
focusArbitrator: PropTypes.object,
};
context!: TextInputContext;
private _mountedComponent: HTMLInputElement | HTMLTextAreaElement | null = null;
private _selectionStart = 0;
private _selectionEnd = 0;
private _isFocused = false;
private _ariaLiveEnabled = false;
constructor(props: Types.TextInputProps, context?: TextInputContext) {
super(props, context);
this.state = {
inputValue: props.value !== undefined ? props.value : (props.defaultValue || ''),
autoResize: TextInput._shouldAutoResize(props),
};
}
UNSAFE_componentWillReceiveProps(nextProps: Types.TextInputProps) {
const nextState: Partial<TextInputState> = {};
if (nextProps.value !== undefined && nextProps.value !== this.state.inputValue) {
nextState.inputValue = nextProps.value;
}
if (nextProps.style !== this.props.style || nextProps.multiline !== this.props.multiline) {
const fixedHeight = TextInput._shouldAutoResize(nextProps);
if (this.state.autoResize !== fixedHeight) {
nextState.autoResize = fixedHeight;
}
}
if (nextProps.placeholderTextColor !== this.props.placeholderTextColor) {
if (nextProps.placeholderTextColor) {
TextInputPlaceholderSupport.addRef(nextProps.placeholderTextColor);
}
if (this.props.placeholderTextColor) {
TextInputPlaceholderSupport.removeRef(this.props.placeholderTextColor);
}
}
if (!isEmpty(nextState)) {
this.setState(nextState, () => {
// Resize as needed after state is set
if (this._mountedComponent instanceof HTMLTextAreaElement) {
TextInput._updateScrollPositions(this._mountedComponent, !!this.state.autoResize);
}
});
}
}
componentDidMount() {
if (this.props.placeholderTextColor) {
TextInputPlaceholderSupport.addRef(this.props.placeholderTextColor);
}
if (this.props.autoFocus) {
this.requestFocus();
}
}
componentWillUnmount() {
if (this.props.placeholderTextColor) {
TextInputPlaceholderSupport.removeRef(this.props.placeholderTextColor);
}
}
render() {
const combinedStyles = Styles.combine([_styles.defaultStyle, this.props.style]);
// Always hide the outline.
combinedStyles.outline = 'none';
combinedStyles.resize = 'none';
// Set the border to zero width if not otherwise specified.
if (combinedStyles.borderWidth === undefined) {
combinedStyles.borderWidth = 0;
}
// By default, the control is editable.
const editable = (this.props.editable !== undefined ? this.props.editable : true);
const spellCheck = (this.props.spellCheck !== undefined ? this.props.spellCheck : this.props.autoCorrect);
const className = this.props.placeholderTextColor !== undefined ?
TextInputPlaceholderSupport.getClassName(this.props.placeholderTextColor) : undefined;
// Use a textarea for multi-line and a regular input for single-line.
if (this.props.multiline) {
return (
<textarea
ref={ this._onMount }
style={ combinedStyles }
value={ this.state.inputValue }
title={ this.props.title }
tabIndex={ this.props.tabIndex }
autoCorrect={ this.props.autoCorrect === false ? 'off' : undefined }
spellCheck={ spellCheck }
disabled={ !editable }
maxLength={ this.props.maxLength }
placeholder={ this.props.placeholder }
className={ className }
onChange={ this._onInputChanged }
onKeyDown={ this._onKeyDown }
onKeyUp={ this._checkSelectionChanged }
onInput={ this._onMultilineInput }
onFocus={ this._onFocus }
onBlur={ this._onBlur }
onMouseDown={ this._checkSelectionChanged }
onMouseUp={ this._checkSelectionChanged }
onPaste={ this._onPaste }
onScroll={ this._onScroll }
aria-label={ this.props.accessibilityLabel || this.props.title }
data-test-id={ this.props.testId }
/>
);
} else {
const { keyboardTypeValue, wrapInForm, pattern } = this._getKeyboardType();
let input = (
<input
ref={ this._onMount }
style={ combinedStyles }
value={ this.state.inputValue }
title={ this.props.title }
tabIndex={ this.props.tabIndex }
className={ className }
autoCapitalize={ this.props.autoCapitalize }
autoCorrect={ this.props.autoCorrect === false ? 'off' : undefined }
spellCheck={ spellCheck }
disabled={ !editable }
maxLength={ this.props.maxLength }
placeholder={ this.props.placeholder }
size={ 1 }
onChange={ this._onInputChanged }
onKeyDown={ this._onKeyDown }
onKeyUp={ this._checkSelectionChanged }
onInput={ this._onInput }
onFocus={ this._onFocus }
onBlur={ this._onBlur }
onMouseDown={ this._checkSelectionChanged }
onMouseUp={ this._checkSelectionChanged }
onPaste={ this._onPaste }
aria-label={ this.props.accessibilityLabel || this.props.title }
type={ keyboardTypeValue }
pattern={ pattern }
data-test-id={ this.props.testId }
/>
);
if (wrapInForm) {
// Wrap the input in a form tag if required
input = (
<form action='' onSubmit={ ev => { /* prevent form submission/page reload */ ev.preventDefault(); this.blur(); } }
style={ _styles.formStyle }>
{ input }
</form>
);
}
return input;
}
}
private _onMount = (comp: HTMLInputElement | HTMLTextAreaElement | null) => {
this._mountedComponent = comp;
if (this._mountedComponent && this._mountedComponent instanceof HTMLTextAreaElement) {
TextInput._updateScrollPositions(this._mountedComponent, !!this.state.autoResize);
}
};
private _onMultilineInput = (ev: React.FormEvent<HTMLTextAreaElement>) => {
this._onInput();
TextInput._updateScrollPositions(ev.currentTarget, !!this.state.autoResize);
};
private _onInput = () => {
if (_isMac && this._mountedComponent && this._isFocused && !this._ariaLiveEnabled) {
// VoiceOver does not handle text inputs properly at the moment, aria-live is a temporary workaround.
// And we're adding aria-live only for the focused input which is being edited, otherwise it might
// interrupt some required announcements.
this._mountedComponent.setAttribute('aria-live', 'assertive');
this._ariaLiveEnabled = true;
}
};
private static _shouldAutoResize(props: Types.TextInputProps) {
// Single line boxes don't need auto-resize
if (!props.multiline) {
return false;
}
const combinedStyles = Styles.combine(props.style);
if (!combinedStyles || typeof combinedStyles === 'number') {
// Number-type styles aren't allowed on web but if they're found we can't decode them so assume not fixed height
return true;
} else if (Array.isArray(combinedStyles)) {
// Iterate across the array and see if there's any height value
// It's possible that the height could be set via another mechanism (like absolute positioning) which would potenailly
// incorrectly engage the autoResize mode
return combinedStyles.some(style => {
if (!style || typeof style === 'number') {
return true;
}
return style.height === undefined;
});
} else {
return combinedStyles.height === undefined;
}
}
private static _updateScrollPositions(element: HTMLTextAreaElement, autoResize: boolean) {
// If the height is fixed, there's nothing more to do
if (!autoResize) {
return;
}
// When scrolling we need to retain scroll tops of all elements
const scrollTops = this._getParentElementAndTops(element);
// Reset height to 1px so that we can detect shrinking TextInputs
element.style.height = '1px';
element.style.height = element.scrollHeight + 'px';
scrollTops.forEach(obj => {
obj.el.scrollTop = obj.top;
});
}
private static _getParentElementAndTops(textAreaElement: HTMLTextAreaElement) {
let element: HTMLElement = textAreaElement;
const results = [];
while (element && element.parentElement) {
element = element.parentElement;
results.push({
el: element,
top: element.scrollTop,
});
}
return results;
}
private _onFocus = (e: Types.FocusEvent) => {
if (this._mountedComponent) {
this._isFocused = true;
if (this.props.onFocus) {
this.props.onFocus(e);
}
}
};
private _onBlur = (e: Types.FocusEvent) => {
if (this._mountedComponent) {
this._isFocused = false;
if (_isMac && this._ariaLiveEnabled) {
this._mountedComponent.removeAttribute('aria-live');
this._ariaLiveEnabled = false;
}
if (this.props.onBlur) {
this.props.onBlur(e);
}
}
};
private _getKeyboardType(): { keyboardTypeValue: string; wrapInForm: boolean; pattern: string | undefined } {
// Determine the correct virtual keyboardType in HTML 5.
// Some types require the <input> tag to be wrapped in a form.
// Pattern is used on numeric keyboardType to display numbers only.
let keyboardTypeValue = 'text';
let wrapInForm = false;
let pattern;
if (this.props.keyboardType === 'numeric') {
pattern = '\\d*';
} else if (this.props.keyboardType === 'number-pad') {
keyboardTypeValue = 'tel';
} else if (this.props.keyboardType === 'email-address') {
keyboardTypeValue = 'email';
}
if (this.props.returnKeyType === 'search') {
keyboardTypeValue = 'search';
wrapInForm = true;
}
if (this.props.secureTextEntry) {
keyboardTypeValue = 'password';
}
return { keyboardTypeValue, wrapInForm, pattern };
}
private _onPaste = (e: Types.ClipboardEvent) => {
if (this.props.onPaste) {
this.props.onPaste(e);
}
this._checkSelectionChanged();
};
private _onInputChanged = (event: React.ChangeEvent<HTMLElement>) => {
if (!event.defaultPrevented) {
if (this._mountedComponent) {
// Has the input value changed?
const value = this._mountedComponent.value || '';
if (this.state.inputValue !== value) {
// If the parent component didn't specify a value, we'll keep
// track of the modified value.
if (this.props.value === undefined) {
this.setState({
inputValue: value,
});
}
if (this.props.onChangeText) {
this.props.onChangeText(value);
}
}
this._checkSelectionChanged();
}
}
};
private _checkSelectionChanged = () => {
if (this._mountedComponent) {
if (this._selectionStart !== this._mountedComponent.selectionStart ||
this._selectionEnd !== this._mountedComponent.selectionEnd) {
this._selectionStart = this._mountedComponent.selectionStart || 0;
this._selectionEnd = this._mountedComponent.selectionEnd || 0;
if (this.props.onSelectionChange) {
this.props.onSelectionChange(this._selectionStart, this._selectionEnd);
}
}
}
};
private _onKeyDown = (e: Types.KeyboardEvent) => {
// Generate a "submit editing" event if the user
// pressed enter or return.
if (e.keyCode === 13 && (!this.props.multiline || this.props.blurOnSubmit)) {
if (this.props.onSubmitEditing) {
this.props.onSubmitEditing();
}
if (this.props.blurOnSubmit) {
this.blur();
}
}
if (this.props.onKeyPress) {
this.props.onKeyPress(e);
}
this._checkSelectionChanged();
};
private _onScroll = (e: React.UIEvent<HTMLTextAreaElement>) => {
const targetElement = e.currentTarget;
// Fix scrollTop if the TextInput can auto-grow
// If the item is bounded by max-height, don't scroll since we want input to follow the cursor at that point
if (this.state.autoResize && targetElement.scrollHeight < targetElement.clientHeight) {
targetElement.scrollTop = 0;
}
if (this.props.onScroll) {
this.props.onScroll(targetElement.scrollLeft, targetElement.scrollTop);
}
};
private _focus = () => {
FocusArbitratorProvider.requestFocus(
this,
() => this.focus(),
() => !!this._mountedComponent,
);
};
blur() {
if (this._mountedComponent) {
this._mountedComponent.blur();
}
}
requestFocus() {
this._focus();
}
focus() {
if (this._mountedComponent) {
this._mountedComponent.focus();
}
}
setAccessibilityFocus() {
this._focus();
}
isFocused() {
if (this._mountedComponent) {
return document.activeElement === this._mountedComponent;
}
return false;
}
selectAll() {
if (this._mountedComponent) {
this._mountedComponent.select();
}
}
selectRange(start: number, end: number) {
if (this._mountedComponent) {
const component = this._mountedComponent as HTMLInputElement;
component.setSelectionRange(start, end);
}
}
getSelectionRange(): { start: number; end: number } {
const range = {
start: 0,
end: 0,
};
if (this._mountedComponent) {
range.start = this._mountedComponent.selectionStart || 0;
range.end = this._mountedComponent.selectionEnd || 0;
}
return range;
}
setValue(value: string): void {
const inputValue = value || '';
if (this.state.inputValue !== inputValue) {
// It's important to set the actual value in the DOM immediately. This allows us to call other related methods
// like selectRange synchronously afterward.
if (this._mountedComponent) {
this._mountedComponent.value = inputValue;
}
this.setState({
inputValue: inputValue,
});
if (this.props.onChangeText) {
this.props.onChangeText(value);
}
}
}
}
applyFocusableComponentMixin(TextInput);
export default TextInput; | the_stack |
import { buildQueryFactory } from "./buildQuery";
import gql from "plain-tag";
import gqlReal from "graphql-tag";
import { GetListParams } from "./buildVariables";
import { IntrospectionResult, Resource } from "./constants/interfaces";
import { getTestIntrospection } from "./testUtils/getTestIntrospection";
import "./testUtils/testTypes";
import { defaultOurOptions } from "./buildDataProvider";
describe("buildQueryFactory", () => {
let testIntrospection: IntrospectionResult;
let testUserResource: Resource;
beforeAll(async () => {
testIntrospection = await getTestIntrospection();
testUserResource = testIntrospection.resources.find(
(r) => r.type.kind === "OBJECT" && r.type.name === "User",
);
});
it("throws an error if resource is unknown", () => {
expect(() =>
buildQueryFactory(testIntrospection, defaultOurOptions)(
"GET_LIST",
"Airplane",
{} as any,
),
).toThrow(
"Unknown resource Airplane. Make sure it has been declared on your server side schema. Known resources are User, UserRole",
);
});
/*
it("throws an error if resource does not have a query or mutation for specified AOR fetch type", () => {
expect(() =>
buildQueryFactory(testIntrospection)("CREATE", "Post", {} as any),
).toThrow(
"No query or mutation matching aor fetch type CREATE could be found for resource Post",
);
});
*/
describe("resourceViews", () => {
it("throws an error if a view resource point to a non-existing resource", () => {
expect(() =>
buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
AirplaneWithManufacturer: {
resource: "Airplane",
fragment: gqlReal`
fragment AirplaneWithManufacturer on Airplane {
id
manufacturer {
id
}
}
`,
},
},
})("GET_LIST", "AirplaneWithManufacturer", {} as any),
).toThrow(
"Unknown resource Airplane. Make sure it has been declared on your server side schema. Known resources are User, UserRole",
);
});
it("enables to whitelist fields", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
type: "whitelist",
fields: ["id", "firstName", "lastName", "userSocialMedia"],
},
},
},
});
const { query } = buildQuery("GET_LIST", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: {},
} as GetListParams);
expect(query).toEqualGraphql(gql`
query users(
$where: UserWhereInput
$orderBy: [UserOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: users(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
firstName
lastName
userSocialMedia {
id
instagram
twitter
user {
id
}
}
}
total: usersCount(where: $where)
}
`);
});
it("enables to blacklist fields", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
type: "blacklist",
fields: [
"userSocialMedia",
"blogPosts",
"comments",
"companies",
"address",
"roles",
],
},
},
},
});
const { query } = buildQuery("GET_LIST", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: {},
} as GetListParams);
expect(query).toEqualGraphql(gql`
query users(
$where: UserWhereInput
$orderBy: [UserOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: users(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
email
firstName
lastName
yearOfBirth
gender
wantsNewsletter
interests
weddingDate
}
total: usersCount(where: $where)
}
`);
});
it("allows to use a single custom virtual view resources for one and many", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: gqlReal`
fragment UserWithTwitter on User {
id
socialMedia {
twitter
}
}
`,
},
},
});
const { query } = buildQuery("GET_LIST", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: {},
} as GetListParams);
expect(query).toEqualGraphql(gql`
query users(
$where: UserWhereInput
$orderBy: [UserOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: users(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
socialMedia {
twitter
}
}
total: usersCount(where: $where)
}
`);
});
describe("allows to use different custom virtual view resources", () => {
it("for get one fetch", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
one: gqlReal`
fragment OneUserWithTwitter on User {
id
userSocialMedia {
twitter
}
}
`,
many: gqlReal`
fragment ManyUsersWithTwitter on User {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_ONE", "UserWithTwitter", { id: 1 });
expect(query).toEqualGraphql(gql`
query user($where: UserWhereUniqueInput!) {
data: user(where: $where) {
id
userSocialMedia {
twitter
}
}
}
`);
});
it("for get list fetch", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
one: gqlReal`
fragment OneUserWithTwitter on User {
id
userSocialMedia {
twitter
}
}
`,
many: gqlReal`
fragment ManyUsersWithTwitter on User {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_LIST", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: {},
} as GetListParams);
expect(query).toEqualGraphql(gql`
query users(
$where: UserWhereInput
$orderBy: [UserOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: users(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
total: usersCount(where: $where)
}
`);
});
it("for get list fetch with typegraphql count option", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
queryDialect: "typegraphql",
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
one: gqlReal`
fragment OneUserWithTwitter on User {
id
userSocialMedia {
twitter
}
}
`,
many: gqlReal`
fragment ManyUsersWithTwitter on User {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_LIST", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: { field: "id", order: "ASC" },
} as GetListParams);
expect(query).toEqualGraphql(gql`
query users(
$where: UserWhereInput
$orderBy: [UserOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: users(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
total: aggregateUser(where: $where) {
count {
_all
}
}
}
`);
});
it("for get list fetch with typegraphql count option - plural ending in 'ies'", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
queryDialect: "typegraphql",
resourceViews: {
CompanyWithUser: {
resource: "Company",
fragment: {
one: gqlReal`
fragment OneCompanyWithUser on Company {
id
user {
id
email
}
}
`,
many: gqlReal`
fragment ManyCompaniesWithUser on Company {
id
user {
id
email
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_LIST", "CompanyWithUser", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: { field: "id", order: "ASC" },
} as GetListParams);
expect(query).toEqualGraphql(gql`
query companies(
$where: CompanyWhereInput
$orderBy: [CompanyOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: companies(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
user {
id
email
}
}
total: aggregateCompany(where: $where) {
count {
_all
}
}
}
`);
});
it("for get list fetch with typegraphql count option, without order", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
queryDialect: "typegraphql",
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
one: gqlReal`
fragment OneUserWithTwitter on User {
id
userSocialMedia {
twitter
}
}
`,
many: gqlReal`
fragment ManyUsersWithTwitter on User {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_LIST", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: {},
} as GetListParams);
expect(query).toEqualGraphql(gql`
query users($where: UserWhereInput, $take: Int, $skip: Int) {
items: users(where: $where, take: $take, skip: $skip) {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
total: aggregateUser(where: $where) {
count {
_all
}
}
}
`);
});
it("for get many fetch", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
one: gqlReal`
fragment OneUserWithTwitter on User {
id
userSocialMedia {
twitter
}
}
`,
many: gqlReal`
fragment ManyUsersWithTwitter on User {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_MANY", "UserWithTwitter", {
ids: [1, 2],
});
expect(query).toEqualGraphql(gql`
query users($where: UserWhereInput) {
items: users(where: $where) {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
total: usersCount(where: $where)
}
`);
});
it("for get many reference fetch", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
...defaultOurOptions,
resourceViews: {
UserWithTwitter: {
resource: "User",
fragment: {
one: gqlReal`
fragment OneUserWithTwitter on User {
id
userSocialMedia {
twitter
}
}
`,
many: gqlReal`
fragment ManyUsersWithTwitter on User {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_MANY_REFERENCE", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
sort: {},
id: 1,
target: "id",
});
expect(query).toEqualGraphql(gql`
query users(
$where: UserWhereInput
$orderBy: [UserOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: users(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
email
wantsNewsletter
userSocialMedia {
twitter
}
}
total: usersCount(where: $where)
}
`);
});
describe("supports defining only one or many", () => {
it("uses the fragment for one, but the default for many", () => {
const buildQuery = buildQueryFactory(testIntrospection, {
resourceViews: {
UserWithTwitter: {
resource: "User",
// @ts-ignore
fragment: {
one: gqlReal`
fragment OneUserWithTwitter on User {
id
userSocialMedia {
twitter
}
}
`,
},
},
},
});
const { query } = buildQuery("GET_LIST", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: {},
} as GetListParams);
expect(query).toEqualGraphql(gql`
query users(
$where: UserWhereInput
$orderBy: [UserOrderByWithRelationInput!]
$take: Int
$skip: Int
) {
items: users(
where: $where
orderBy: $orderBy
take: $take
skip: $skip
) {
id
email
firstName
lastName
yearOfBirth
roles {
id
}
gender
wantsNewsletter
userSocialMedia {
id
instagram
twitter
user {
id
}
}
blogPosts {
id
}
comments {
id
}
companies {
id
}
interests
weddingDate
address {
street
city
countryCode
}
}
}
`);
const { query: oneQuery } = buildQuery("GET_ONE", "UserWithTwitter", {
pagination: {
page: 1,
perPage: 50,
},
filter: {},
sort: {},
} as GetListParams);
expect(oneQuery).toEqualGraphql(gql`
query user($where: UserWhereUniqueInput!) {
data: user(where: $where) {
id
userSocialMedia {
twitter
}
}
}
`);
});
});
});
});
}); | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://www.googleapis.com/discovery/v1/apis/resourceviews/v1beta2/rest
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Compute Engine Instance Groups API v1beta2 */
function load(name: "resourceviews", version: "v1beta2"): PromiseLike<void>;
function load(name: "resourceviews", version: "v1beta2", callback: () => any): void;
const zoneOperations: resourceviews.ZoneOperationsResource;
const zoneViews: resourceviews.ZoneViewsResource;
namespace resourceviews {
interface Label {
/** Key of the label. */
key?: string;
/** Value of the label. */
value?: string;
}
interface ListResourceResponseItem {
/** The list of service end points on the resource. */
endpoints?: Record<string, number[]>;
/** The full URL of the resource. */
resource?: string;
}
interface Operation {
/**
* [Output only] An optional identifier specified by the client when the mutation was initiated. Must be unique for all operation resources in the
* project.
*/
clientOperationId?: string;
/** [Output Only] The time that this operation was requested, in RFC3339 text format. */
creationTimestamp?: string;
/** [Output Only] The time that this operation was completed, in RFC3339 text format. */
endTime?: string;
/** [Output Only] If errors occurred during processing of this operation, this field will be populated. */
error?: {
/** [Output Only] The array of errors encountered while processing this operation. */
errors?: Array<{
/** [Output Only] The error type identifier for this error. */
code?: string;
/** [Output Only] Indicates the field in the request which caused the error. This property is optional. */
location?: string;
/** [Output Only] An optional, human-readable error message. */
message?: string;
}>;
};
/** [Output only] If operation fails, the HTTP error message returned. */
httpErrorMessage?: string;
/** [Output only] If operation fails, the HTTP error status code returned. */
httpErrorStatusCode?: number;
/** [Output Only] Unique identifier for the resource, generated by the server. */
id?: string;
/** [Output Only] The time that this operation was requested, in RFC3339 text format. */
insertTime?: string;
/** [Output only] Type of the resource. */
kind?: string;
/** [Output Only] Name of the resource. */
name?: string;
/** [Output only] Type of the operation. Operations include insert, update, and delete. */
operationType?: string;
/**
* [Output only] An optional progress indicator that ranges from 0 to 100. There is no requirement that this be linear or support any granularity of
* operations. This should not be used to guess at when the operation will be complete. This number should be monotonically increasing as the operation
* progresses.
*/
progress?: number;
/** [Output Only] URL of the region where the operation resides. Only available when performing regional operations. */
region?: string;
/** [Output Only] Server-defined fully-qualified URL for this resource. */
selfLink?: string;
/** [Output Only] The time that this operation was started by the server, in RFC3339 text format. */
startTime?: string;
/** [Output Only] Status of the operation. */
status?: string;
/** [Output Only] An optional textual description of the current status of the operation. */
statusMessage?: string;
/** [Output Only] Unique target ID which identifies a particular incarnation of the target. */
targetId?: string;
/** [Output only] URL of the resource the operation is mutating. */
targetLink?: string;
/** [Output Only] User who requested the operation, for example: user@example.com. */
user?: string;
/** [Output Only] If there are issues with this operation, a warning is returned. */
warnings?: Array<{
/** [Output only] The warning type identifier for this warning. */
code?: string;
/** [Output only] Metadata for this warning in key:value format. */
data?: Array<{
/** [Output Only] Metadata key for this warning. */
key?: string;
/** [Output Only] Metadata value for this warning. */
value?: string;
}>;
/** [Output only] Optional human-readable details for this warning. */
message?: string;
}>;
/** [Output Only] URL of the zone where the operation resides. Only available when performing per-zone operations. */
zone?: string;
}
interface OperationList {
/** Unique identifier for the resource; defined by the server (output only). */
id?: string;
/** The operation resources. */
items?: Operation[];
/** Type of resource. */
kind?: string;
/** A token used to continue a truncated list request (output only). */
nextPageToken?: string;
/** Server defined URL for this resource (output only). */
selfLink?: string;
}
interface ResourceView {
/** The creation time of the resource view. */
creationTimestamp?: string;
/** The detailed description of the resource view. */
description?: string;
/** Services endpoint information. */
endpoints?: ServiceEndpoint[];
/** The fingerprint of the service endpoint information. */
fingerprint?: string;
/** [Output Only] The ID of the resource view. */
id?: string;
/** Type of the resource. */
kind?: string;
/** The labels for events. */
labels?: Label[];
/** The name of the resource view. */
name?: string;
/** The URL of a Compute Engine network to which the resources in the view belong. */
network?: string;
/** A list of all resources in the resource view. */
resources?: string[];
/** [Output Only] A self-link to the resource view. */
selfLink?: string;
/** The total number of resources in the resource view. */
size?: number;
}
interface ServiceEndpoint {
/** The name of the service endpoint. */
name?: string;
/** The port of the service endpoint. */
port?: number;
}
interface ZoneViewsAddResourcesRequest {
/** The list of resources to be added. */
resources?: string[];
}
interface ZoneViewsGetServiceResponse {
/** The service information. */
endpoints?: ServiceEndpoint[];
/** The fingerprint of the service information. */
fingerprint?: string;
}
interface ZoneViewsList {
/** The result that contains all resource views that meet the criteria. */
items?: ResourceView[];
/** Type of resource. */
kind?: string;
/** A token used for pagination. */
nextPageToken?: string;
/** Server defined URL for this resource (output only). */
selfLink?: string;
}
interface ZoneViewsListResourcesResponse {
/** The formatted JSON that is requested by the user. */
items?: ListResourceResponseItem[];
/** The URL of a Compute Engine network to which the resources in the view belong. */
network?: string;
/** A token used for pagination. */
nextPageToken?: string;
}
interface ZoneViewsRemoveResourcesRequest {
/** The list of resources to be removed. */
resources?: string[];
}
interface ZoneViewsSetServiceRequest {
/** The service information to be updated. */
endpoints?: ServiceEndpoint[];
/** Fingerprint of the service information; a hash of the contents. This field is used for optimistic locking when updating the service entries. */
fingerprint?: string;
/** The name of the resource if user wants to update the service information of the resource. */
resourceName?: string;
}
interface ZoneOperationsResource {
/** Retrieves the specified zone-specific operation resource. */
get(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Name of the operation resource to return. */
operation: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Name of the project scoping this request. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** Name of the zone scoping this request. */
zone: string;
}): Request<Operation>;
/** Retrieves the list of operation resources contained within the specified zone. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Optional. Filter expression for filtering listed resources. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Name of the project scoping this request. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** Name of the zone scoping this request. */
zone: string;
}): Request<OperationList>;
}
interface ZoneViewsResource {
/** Add resources to the view. */
addResources(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The name of the resource view. */
resourceView: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<Operation>;
/** Delete a resource view. */
delete(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The name of the resource view. */
resourceView: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<Operation>;
/** Get the information of a zonal resource view. */
get(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The name of the resource view. */
resourceView: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<ResourceView>;
/** Get the service information of a resource view or a resource. */
getService(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The name of the resource if user wants to get the service information of the resource. */
resourceName?: string;
/** The name of the resource view. */
resourceView: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<ZoneViewsGetServiceResponse>;
/** Create a resource view. */
insert(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<Operation>;
/** List resource views. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Maximum count of results to be returned. Acceptable values are 0 to 5000, inclusive. (Default: 5000) */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Specifies a nextPageToken returned by a previous list request. This token can be used to request the next page of results from a previous list request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<ZoneViewsList>;
/** List the resources of the resource view. */
listResources(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* The requested format of the return value. It can be URL or URL_PORT. A JSON object will be included in the response based on the format. The default
* format is NONE, which results in no JSON in the response.
*/
format?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The state of the instance to list. By default, it lists all instances. */
listState?: string;
/** Maximum count of results to be returned. Acceptable values are 0 to 5000, inclusive. (Default: 5000) */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Specifies a nextPageToken returned by a previous list request. This token can be used to request the next page of results from a previous list request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The name of the resource view. */
resourceView: string;
/** The service name to return in the response. It is optional and if it is not set, all the service end points will be returned. */
serviceName?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<ZoneViewsListResourcesResponse>;
/** Remove resources from the view. */
removeResources(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The name of the resource view. */
resourceView: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<Operation>;
/** Update the service information of a resource view or a resource. */
setService(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The project name of the resource view. */
project: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The name of the resource view. */
resourceView: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
/** The zone name of the resource view. */
zone: string;
}): Request<Operation>;
}
}
} | the_stack |
import * as s from '../../src/utils/stream';
describe('stream', () => {
test('from Set', () => {
const stream = s.stream(new Set([1, 2, 3]));
expect(stream.toArray()).toMatchObject([1, 2, 3]);
});
test('from Map', () => {
const stream = s.stream(new Map([['a', 1], ['b', 2], ['c', 3]]));
expect(stream.toArray()).toMatchObject([['a', 1], ['b', 2], ['c', 3]]);
});
test('from array-like', () => {
const stream = s.stream({ length: 3, 0: 'a', 1: 'b', 2: 'c' });
expect(stream.toArray()).toMatchObject(['a', 'b', 'c']);
});
test('from multiple collections', () => {
const stream = s.stream<number | string>(
new Set([1, 2, 3]),
[],
{ length: 3, 0: 'a', 1: 'b', 2: 'c' },
[],
['foo', 123]
);
expect(stream.toArray()).toMatchObject([1, 2, 3, 'a', 'b', 'c', 'foo', 123]);
});
});
describe('Stream.isEmpty', () => {
test('empty stream', () => {
const stream = s.EMPTY_STREAM;
expect(stream.isEmpty()).toBe(true);
});
test('non-empty stream', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.isEmpty()).toBe(false);
});
});
describe('Stream.count', () => {
test('empty array', () => {
const stream = s.EMPTY_STREAM;
expect(stream.count()).toBe(0);
});
test('non-empty array', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.count()).toBe(3);
});
});
describe('Stream.toSet', () => {
test('empty stream', () => {
const stream = s.EMPTY_STREAM;
expect(stream.toSet()).toMatchObject(new Set());
});
test('non-empty array', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.toSet()).toMatchObject(new Set([1, 2, 3]));
});
});
describe('Stream.toMap', () => {
test('empty stream', () => {
const stream = s.EMPTY_STREAM;
expect(stream.toMap()).toMatchObject(new Map());
});
test('key and value unmapped', () => {
const stream = s.stream([{ a: 1, b: 'foo' }, { a: 2, b: 'bar' }, { a: 3, b: 'baz' }]);
expect(stream.toMap()).toMatchObject(new Map([
[{ a: 1, b: 'foo' }, { a: 1, b: 'foo' }],
[{ a: 2, b: 'bar' }, { a: 2, b: 'bar' }],
[{ a: 3, b: 'baz' }, { a: 3, b: 'baz' }]
]));
});
test('key mapped', () => {
const stream = s.stream([{ a: 1, b: 'foo' }, { a: 2, b: 'bar' }, { a: 3, b: 'baz' }]);
expect(stream.toMap(e => e.b)).toMatchObject(new Map([
['foo', { a: 1, b: 'foo' }],
['bar', { a: 2, b: 'bar' }],
['baz', { a: 3, b: 'baz' }]
]));
});
test('value mapped', () => {
const stream = s.stream([{ a: 1, b: 'foo' }, { a: 2, b: 'bar' }, { a: 3, b: 'baz' }]);
expect(stream.toMap(undefined, e => e.a)).toMatchObject(new Map([
[{ a: 1, b: 'foo' }, 1],
[{ a: 2, b: 'bar' }, 2],
[{ a: 3, b: 'baz' }, 3]
]));
});
test('key and value mapped', () => {
const stream = s.stream([{ a: 1, b: 'foo' }, { a: 2, b: 'bar' }, { a: 3, b: 'baz' }]);
expect(stream.toMap(e => e.b, e => e.a)).toMatchObject(new Map([
['foo', 1],
['bar', 2],
['baz', 3]
]));
});
});
describe('Stream.concat', () => {
test('multiple arrays', () => {
const a = s.stream(['a']);
const b = s.stream(['b']);
const c = s.stream(['c']);
expect(a.concat(b).concat(c).toArray()).toMatchObject(['a', 'b', 'c']);
});
test('nested concatenation', () => {
const a = s.stream(['a']);
const b = s.stream(['b']);
const c = s.stream(['c']);
expect(a.concat(b.concat(c)).toArray()).toMatchObject(['a', 'b', 'c']);
});
test('empty streams', () => {
const a = s.EMPTY_STREAM;
const b = s.EMPTY_STREAM;
expect(a.concat(b).toArray()).toMatchObject([]);
});
test('empty stream and array', () => {
const a = s.EMPTY_STREAM;
const b = s.stream(['b']);
expect(a.concat(b).toArray()).toMatchObject(['b']);
});
});
describe('Stream.join', () => {
test('empty stream', () => {
const stream = s.EMPTY_STREAM;
expect(stream.join()).toBe('');
});
test('string stream with default separator', () => {
const stream = s.stream(['a', 'b']);
expect(stream.join()).toBe('a,b');
});
test('string stream with custom separator', () => {
const stream = s.stream(['a', 'b']);
expect(stream.join(' & ')).toBe('a & b');
});
test('mixed type stream', () => {
const stream = s.stream([1, 'a', true, undefined]);
expect(stream.join()).toBe('1,a,true,undefined');
});
test('object stream', () => {
const stream = s.stream([{}]);
expect(stream.join()).toBe('[object Object]');
});
test('object stream with custom toString method', () => {
const stream = s.stream([customToString('a'), customToString('b')]);
expect(stream.join()).toBe('a,b');
});
test('object stream without prototype', () => {
const stream = s.stream([Object.create(null)]);
expect(stream.join()).toBe('[object Object]');
});
function customToString(input: string) {
return {
toString(): string {
return input;
}
};
}
});
describe('Stream.indexOf', () => {
test('number stream present', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.indexOf(2)).toBe(1);
});
test('number stream absent', () => {
const stream = s.stream([1, 3]);
expect(stream.indexOf(2)).toBe(-1);
});
test('object stream present', () => {
const a = { 'a': 1 };
const b = { 'b': 2 };
const c = { 'c': 3 };
const stream = s.stream([a, b, c]);
expect(stream.indexOf(b)).toBe(1);
});
test('object stream not equal', () => {
const a = { 'a': 1 };
const b = { 'b': 2 };
const c = { 'c': 3 };
const stream = s.stream([a, b, c]);
expect(stream.indexOf({ 'b': 2 })).toBe(-1);
});
});
describe('Stream.every', () => {
test('boolean check true', () => {
const stream = s.stream([true, true, true]);
expect(stream.every(value => value)).toBe(true);
});
test('boolean check false', () => {
const stream = s.stream([true, false, true]);
expect(stream.every(value => value)).toBe(false);
});
test('type inference', () => {
type A = { a: number };
type B = A & { b: number };
const isB = (value: A): value is B => typeof (value as B).b === 'number';
const stream: s.Stream<A> = s.stream([{ a: 1, b: 2 }, { a: 3, b: 4 }]);
if (stream.every(isB)) {
// This test is about the type inference, so we actually expect the compiler to accept the
// uncasted access to property `b`.
expect(stream.filter(v => v.b > 5).toArray()).toHaveLength(0);
} else {
fail('Expected every to return true');
}
});
});
describe('Stream.some', () => {
test('boolean check true', () => {
const stream = s.stream([false, true, false]);
expect(stream.some(value => value)).toBe(true);
});
test('boolean check false', () => {
const stream = s.stream([false, false, false]);
expect(stream.some(value => value)).toBe(false);
});
});
describe('Stream.forEach', () => {
test('sum numbers', () => {
const stream = s.stream([2, 4, 6]);
let sumValue = 0;
let sumIndex = 0;
stream.forEach((value, index) => {
sumValue += value;
sumIndex += index;
});
expect(sumValue).toBe(12);
expect(sumIndex).toBe(3);
});
});
describe('Stream.map', () => {
test('shift numbers', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.map(value => value + 1).toArray()).toMatchObject([2, 3, 4]);
});
});
describe('Stream.filter', () => {
test('compare numbers', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.filter(value => value >= 2).toArray()).toMatchObject([2, 3]);
});
test('type inference', () => {
type A = { a: number };
type B = A & { b: number };
const isB = (value: A): value is B => typeof (value as B).b === 'number';
const stream: s.Stream<A> = s.stream([{ a: 1, b: 2 }, { a: 3, b: 4 }]);
// This test is about the type inference, so we actually expect the compiler to accept the
// uncasted access to property `b`.
expect(stream.filter(isB).find(v => v.b > 5)).toBe(undefined);
});
});
describe('Stream.reduce', () => {
test('empty array', () => {
const stream: s.Stream<number> = s.EMPTY_STREAM;
expect(stream.reduce((a, b) => a + b)).toBe(undefined);
});
test('empty array with initial value', () => {
const stream: s.Stream<number> = s.EMPTY_STREAM;
expect(stream.reduce((a, b) => a + b, 0)).toBe(0);
});
test('sum numbers', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.reduce((a, b) => a + b)).toBe(6);
});
test('compose array', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.reduce<number[]>((array, value) => array.concat([value]), [])).toMatchObject([1, 2, 3]);
});
});
describe('Stream.reduceRight', () => {
test('empty array', () => {
const stream: s.Stream<number> = s.EMPTY_STREAM;
expect(stream.reduceRight((a, b) => a + b)).toBe(undefined);
});
test('empty array with initial value', () => {
const stream: s.Stream<number> = s.EMPTY_STREAM;
expect(stream.reduceRight((a, b) => a + b, 0)).toBe(0);
});
test('sum numbers', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.reduceRight((a, b) => a + b)).toBe(6);
});
test('compose array', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.reduceRight<number[]>((array, value) => array.concat([value]), [])).toMatchObject([3, 2, 1]);
});
});
describe('Stream.find', () => {
test('number stream present', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.find(value => value > 2)).toBe(3);
});
test('number stream absent', () => {
const stream = s.stream([1, 1.5, 2]);
expect(stream.find(value => value > 2)).toBe(undefined);
});
test('type inference', () => {
type A = { a: number };
type B = A & { b: number };
const isB = (value: A): value is B => typeof (value as B).b === 'number';
const stream: s.Stream<A> = s.stream([{ a: 1, b: 2 }, { a: 3, b: 4 }]);
// This test is about the type inference, so we actually expect the compiler to accept the
// uncasted access to property `b`.
expect(stream.find(isB)?.b).toBe(2);
});
});
describe('Stream.findIndex', () => {
test('number stream present', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.findIndex(value => value > 2)).toBe(2);
});
test('number stream absent', () => {
const stream = s.stream([1, 1.5, 2]);
expect(stream.findIndex(value => value > 2)).toBe(-1);
});
});
describe('Stream.includes', () => {
test('number stream present', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.includes(2)).toBe(true);
});
test('number stream absent', () => {
const stream = s.stream([1, 3]);
expect(stream.includes(2)).toBe(false);
});
test('object stream present', () => {
const a = { 'a': 1 };
const b = { 'b': 2 };
const c = { 'c': 3 };
const stream = s.stream([a, b, c]);
expect(stream.includes(b)).toBe(true);
});
test('object stream not equal', () => {
const a = { 'a': 1 };
const b = { 'b': 2 };
const c = { 'c': 3 };
const stream = s.stream([a, b, c]);
expect(stream.includes({ 'b': 2 })).toBe(false);
});
});
describe('Stream.flatMap', () => {
test('number stream', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.flatMap(value => [value]).toArray()).toMatchObject([1, 2, 3]);
});
test('mixed number / array property', () => {
const stream = s.stream([{ p: [1, 2] }, { p: 3 }, { p: [4, 5] }]);
expect(stream.flatMap(o => o.p).toArray()).toMatchObject([1, 2, 3, 4, 5]);
});
});
describe('Stream.flat', () => {
test('correct type with arrays', () => {
const stream = s.stream([[1, 2], [[3, 4]]]);
const flattened: s.Stream<number> = stream.flat(2);
expect(flattened.toArray()).toMatchObject([1, 2, 3, 4]);
});
test('correct type with streams', () => {
const stream = s.stream([s.stream([1, 2]), s.stream([s.stream([3, 4])])]);
const flattened: s.Stream<number> = stream.flat(2);
expect(flattened.toArray()).toMatchObject([1, 2, 3, 4]);
});
test('one level', () => {
const stream = s.stream([1, [2, [3, [4, [5]]]]]);
expect(stream.flat().toArray()).toMatchObject([1, 2, [3, [4, [5]]]]);
});
test('three levels', () => {
const stream = s.stream([1, [2, [3, [4, [5]]]]]);
expect(stream.flat(3).toArray()).toMatchObject([1, 2, 3, 4, [5]]);
});
});
describe('Stream.head', () => {
test('empty stream', () => {
const stream = s.EMPTY_STREAM;
expect(stream.head()).toBe(undefined);
});
test('number stream', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.head()).toBe(1);
});
});
describe('Stream.tail', () => {
test('empty stream', () => {
const stream = s.EMPTY_STREAM;
expect(stream.tail().toArray()).toMatchObject([]);
});
test('number stream', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.tail().toArray()).toMatchObject([2, 3]);
});
test('skip three elements', () => {
const stream = s.stream([1, 2, 3, 4, 5]);
expect(stream.tail(3).toArray()).toMatchObject([4, 5]);
});
});
describe('Stream.limit', () => {
test('size zero', () => {
const stream = s.stream([1, 2, 3]);
expect(stream.limit(0).toArray()).toMatchObject([]);
});
test('size three', () => {
const stream = s.stream([1, 2, 3, 4, 5]);
expect(stream.limit(3).toArray()).toMatchObject([1, 2, 3]);
});
});
describe('Stream.distinct', () => {
test('empty stream', () => {
const stream = s.EMPTY_STREAM;
expect(stream.distinct().toArray()).toMatchObject([]);
});
test('different items stay the same', () => {
const stream = s.stream(['a', 'b', 'c']);
expect(stream.distinct().toArray()).toMatchObject(['a', 'b', 'c']);
});
test('different items with different types stay the same', () => {
const stream = s.stream(['a', 1, true]);
expect(stream.distinct().toArray()).toMatchObject(['a', 1, true]);
});
test('duplicate entries are removed', () => {
const stream = s.stream(['a', 'a', 'b']);
expect(stream.distinct().toArray()).toMatchObject(['a', 'b']);
});
test('duplicate entries of different types stay the same', () => {
const stream = s.stream(['1', 1, '2']);
expect(stream.distinct().toArray()).toMatchObject(['1', 1, '2']);
});
test('distinct empty objects stay the same', () => {
const a = {};
const b = {};
const stream = s.stream([a, b]);
expect(stream.distinct().toArray()).toMatchObject([a, b]);
});
test('same objects are removed', () => {
const a = {};
const stream = s.stream([a, a]);
expect(stream.distinct().toArray()).toMatchObject([a]);
});
test('distinct objects by value are removed', () => {
const a = { value: 'a' };
const b = { value: 'a' };
const stream = s.stream([a, b]);
expect(stream.distinct(e => e.value).toArray()).toMatchObject([a]);
});
test('distinct objects by value stay the same', () => {
const a = { value: 'a' };
const b = { value: 'b' };
const stream = s.stream([a, b]);
expect(stream.distinct(e => e.value).toArray()).toMatchObject([a, b]);
});
}); | the_stack |
import {
ArchDescr,
t, // types
OpDescription,
ZeroWidth,
Constant,
Commutative,
ResultInArg0,
ResultNotInArgs,
Rematerializeable,
ClobberFlags,
Call,
NilCheck,
FaultOnNilArg0,
FaultOnNilArg1,
UsesScratch,
HasSideEffects,
Generic,
} from "./describe"
import { emptyRegSet } from "../ir/reg"
import { SymEffect } from "../ir/op"
const ops :OpDescription[] = [
// special
["Invalid"],
["Unknown"], // Unknown value. Used for Values whose values don't matter because they are dead code.
["Phi", -1, ZeroWidth], // select an argument based on which predecessor block we came from
["Copy", 1], // output = arg0
["Arg", 0, ZeroWidth, {aux: "SymOff", symEffect: SymEffect.Read}], // argument to current function. aux=name, auxInt=position.
["VarDef", 1, ZeroWidth, t.mem, {aux: "Sym", symEffect: SymEffect.None}], // aux=name
["InitMem", 0, ZeroWidth, t.mem], // memory input to a function.
["CallArg", 1, ZeroWidth], // argument for function call
["NilCheck", 2, t.nil, NilCheck, FaultOnNilArg0], // panic if arg0 is nil. arg1=mem.
// InlMark marks the start of an inlined function body. Its AuxInt field
// distinguishes which entry in the local inline tree it is marking.
["InlMark", 1, t.nil, {aux: "Int32"}], // arg[0]=mem, returns void.
// function calls
// Arguments to the call have already been written to the stack.
// Return values appear on the stack.
["Call", 1, Call, t.mem, {aux: "SymOff"}], // call function at aux. auxint=arglen, arg0=mem, returns mem
["TailCall", 1, Call, t.mem, {aux: "SymOff"}], // call function
// ["ClosureCall", 3, Call, {aux: "Int64"}] // arg0=code pointer, arg1=context ptr, arg2=memory. aux=arg size.
// ["ICall", 2, Call, {aux: "Int64"}] // interface call. arg0=code pointer, arg1=memory, aux=arg size.
// constants
// Constant values are stored in the aux field.
["ConstBool", Constant, {aux: "Bool"}], // aux is 0=false, 1=true
["ConstI8", 0, Constant, {aux: "Int8"}], // aux is sign-extended 8 bits
["ConstI16", 0, Constant, {aux: "Int16"}], // aux is sign-extended 16 bits
["ConstI32", 0, Constant, {aux: "Int32"}], // aux is sign-extended 32 bits
["ConstI64", Constant, {aux: "Int64"}], // aux is Int64
["ConstF32", Constant, {aux: "Int32"}],
["ConstF64", Constant, {aux: "Int64"}],
["ConstStr", {aux: "String"}], // value in aux (string)
// stack
["SP", ZeroWidth], // stack pointer
// The SP pseudo-register is a virtual stack pointer used to refer
// to frame-local variables and the arguments being prepared for
// function calls. It points to the top of the local stack frame,
// so references should use negative offsets in the range
// [−framesize, 0): x-8(SP), y-4(SP), and so on.
["SB", ZeroWidth, t.uintptr],
// static base pointer (a.k.a. globals pointer)
// SB is a pseudo-register that holds the "static base" pointer,
// i.e. the address of the beginning of the program address space.
// memory
["Load", 2], // Load from arg0. arg1=mem
["Store", 3, t.mem, {aux: "Type"}], // Store arg1 to arg0. arg2=mem, aux=type. Ret mem.
["Move", 3, t.mem], // arg0=destptr, arg1=srcptr, arg2=addr, aux=type
["Zero", 2, t.mem], // arg0=destptr, arg1=addr, auxInt=size, aux=type
["OffPtr", 1, t.mem, {aux: "Int64"}], // offset pointer. arg0 + auxint. arg0 and res is mem
// register allocation spill and restore
["StoreReg", 1],
["LoadReg", 1],
// 2-input arithmetic
// Types must be consistent with typing.
// Add, for example, must take two values of the same type and produces that
// same type
//
// arg0 + arg1 ; sign-agnostic addition
["AddI8", 2, Commutative, ResultInArg0],
["AddI16", 2, Commutative, ResultInArg0],
["AddI32", 2, Commutative, ResultInArg0],
["AddI64", 2, Commutative, ResultInArg0],
["AddF32", 2, Commutative, ResultInArg0],
["AddF64", 2, Commutative, ResultInArg0],
//
// arg0 - arg1 ; sign-agnostic subtraction
["SubI8", 2, ResultInArg0],
["SubI16", 2, ResultInArg0],
["SubI32", 2, ResultInArg0],
["SubI64", 2, ResultInArg0],
["SubF32", 2, ResultInArg0],
["SubF64", 2, ResultInArg0],
//
// arg0 * arg1 ; sign-agnostic multiplication
["MulI8", 2, Commutative, ResultInArg0],
["MulI16", 2, Commutative, ResultInArg0],
["MulI32", 2, Commutative, ResultInArg0],
["MulI64", 2, Commutative, ResultInArg0],
["MulF32", 2, Commutative, ResultInArg0],
["MulF64", 2, Commutative, ResultInArg0],
//
// arg0 / arg1 ; division
["DivS8", 2, ResultInArg0], // signed (result is truncated toward zero)
["DivU8", 2, ResultInArg0], // unsigned (result is floored)
["DivS16", 2, ResultInArg0],
["DivU16", 2, ResultInArg0],
["DivS32", 2, ResultInArg0],
["DivU32", 2, ResultInArg0],
["DivS64", 2, ResultInArg0],
["DivU64", 2, ResultInArg0],
["DivF32", 2, ResultInArg0],
["DivF64", 2, ResultInArg0],
//
// arg0 % arg1 ; remainder
["RemS8", 2, ResultInArg0], // signed (result has the sign of the dividend)
["RemU8", 2, ResultInArg0], // unsigned
["RemS16", 2, ResultInArg0],
["RemU16", 2, ResultInArg0],
["RemS32", 2, ResultInArg0],
["RemU32", 2, ResultInArg0],
["RemI64", 2, ResultInArg0],
["RemU64", 2, ResultInArg0],
//
// arg0 & arg1 ; sign-agnostic bitwise and
["AndI8", 2, Commutative, ResultInArg0],
["AndI16", 2, Commutative, ResultInArg0],
["AndI32", 2, Commutative, ResultInArg0],
["AndI64", 2, Commutative, ResultInArg0],
//
// arg0 | arg1 ; sign-agnostic bitwise inclusive or
["OrI8", 2, Commutative, ResultInArg0],
["OrI16", 2, Commutative, ResultInArg0],
["OrI32", 2, Commutative, ResultInArg0],
["OrI64", 2, Commutative, ResultInArg0],
//
// arg0 ^ arg1 ; sign-agnostic bitwise exclusive or
["XorI8", 2, Commutative, ResultInArg0],
["XorI16", 2, Commutative, ResultInArg0],
["XorI32", 2, Commutative, ResultInArg0],
["XorI64", 2, Commutative, ResultInArg0],
//
// For shifts, AxB means the shifted value has A bits and the shift amount
// has B bits.
// Shift amounts are considered unsigned.
// If arg1 is known to be less than the number of bits in arg0,
// then aux may be set to 1.
// According to the Go assembler, this enables better code generation
// on some platforms.
//
// arg0 << arg1 ; sign-agnostic shift left
["ShLI8x8", 2, {aux: "Bool"}],
["ShLI8x16", 2, {aux: "Bool"}],
["ShLI8x32", 2, {aux: "Bool"}],
["ShLI8x64", 2, {aux: "Bool"}],
["ShLI16x8", 2, {aux: "Bool"}],
["ShLI16x16", 2, {aux: "Bool"}],
["ShLI16x32", 2, {aux: "Bool"}],
["ShLI16x64", 2, {aux: "Bool"}],
["ShLI32x8", 2, {aux: "Bool"}],
["ShLI32x16", 2, {aux: "Bool"}],
["ShLI32x32", 2, {aux: "Bool"}],
["ShLI32x64", 2, {aux: "Bool"}],
["ShLI64x8", 2, {aux: "Bool"}],
["ShLI64x16", 2, {aux: "Bool"}],
["ShLI64x32", 2, {aux: "Bool"}],
["ShLI64x64", 2, {aux: "Bool"}],
//
// arg0 >> arg1 ; sign-replicating (arithmetic) shift right
["ShRS8x8", 2, {aux: "Bool"}],
["ShRS8x16", 2, {aux: "Bool"}],
["ShRS8x32", 2, {aux: "Bool"}],
["ShRS8x64", 2, {aux: "Bool"}],
["ShRS16x8", 2, {aux: "Bool"}],
["ShRS16x16", 2, {aux: "Bool"}],
["ShRS16x32", 2, {aux: "Bool"}],
["ShRS16x64", 2, {aux: "Bool"}],
["ShRS32x8", 2, {aux: "Bool"}],
["ShRS32x16", 2, {aux: "Bool"}],
["ShRS32x32", 2, {aux: "Bool"}],
["ShRS32x64", 2, {aux: "Bool"}],
["ShRS64x8", 2, {aux: "Bool"}],
["ShRS64x16", 2, {aux: "Bool"}],
["ShRS64x32", 2, {aux: "Bool"}],
["ShRS64x64", 2, {aux: "Bool"}],
//
// arg0 >> arg1 (aka >>>) ; zero-replicating (logical) shift right
["ShRU8x8", 2, {aux: "Bool"}],
["ShRU8x16", 2, {aux: "Bool"}],
["ShRU8x32", 2, {aux: "Bool"}],
["ShRU8x64", 2, {aux: "Bool"}],
["ShRU16x8", 2, {aux: "Bool"}],
["ShRU16x16", 2, {aux: "Bool"}],
["ShRU16x32", 2, {aux: "Bool"}],
["ShRU16x64", 2, {aux: "Bool"}],
["ShRU32x8", 2, {aux: "Bool"}],
["ShRU32x16", 2, {aux: "Bool"}],
["ShRU32x32", 2, {aux: "Bool"}],
["ShRU32x64", 2, {aux: "Bool"}],
["ShRU64x8", 2, {aux: "Bool"}],
["ShRU64x16", 2, {aux: "Bool"}],
["ShRU64x32", 2, {aux: "Bool"}],
["ShRU64x64", 2, {aux: "Bool"}],
// 2-input comparisons
//
// arg0 == arg1 ; sign-agnostic compare equal
["EqI8", 2, Commutative, t.bool],
["EqI16", 2, Commutative, t.bool],
["EqI32", 2, Commutative, t.bool],
["EqI64", 2, Commutative, t.bool],
["EqF32", 2, Commutative, t.bool],
["EqF64", 2, Commutative, t.bool],
//
// arg0 != arg1 ; sign-agnostic compare unequal
["NeqI8", 2, Commutative, t.bool],
["NeqI16", 2, Commutative, t.bool],
["NeqI32", 2, Commutative, t.bool],
["NeqI64", 2, Commutative, t.bool],
["NeqF32", 2, Commutative, t.bool],
["NeqF64", 2, Commutative, t.bool],
//
// arg0 < arg1 ; less than
["LessS8", 2, t.bool], // signed
["LessU8", 2, t.bool], // unsigned
["LessS16", 2, t.bool],
["LessU16", 2, t.bool],
["LessS32", 2, t.bool],
["LessU32", 2, t.bool],
["LessS64", 2, t.bool],
["LessU64", 2, t.bool],
["LessF32", 2, t.bool],
["LessF64", 2, t.bool],
//
// arg0 <= arg1 ; less than or equal
["LeqS8", 2, t.bool], // signed
["LeqU8", 2, t.bool], // unsigned
["LeqS16", 2, t.bool],
["LeqU16", 2, t.bool],
["LeqS32", 2, t.bool],
["LeqU32", 2, t.bool],
["LeqS64", 2, t.bool],
["LeqU64", 2, t.bool],
["LeqF32", 2, t.bool],
["LeqF64", 2, t.bool],
//
// arg0 > arg1 ; greater than
["GreaterS8", 2, t.bool], // signed
["GreaterU8", 2, t.bool], // unsigned
["GreaterS16", 2, t.bool],
["GreaterU16", 2, t.bool],
["GreaterS32", 2, t.bool],
["GreaterU32", 2, t.bool],
["GreaterS64", 2, t.bool],
["GreaterU64", 2, t.bool],
["GreaterF32", 2, t.bool],
["GreaterF64", 2, t.bool],
//
// arg0 <= arg1 ; greater than or equal
["GeqS8", 2, t.bool], // signed
["GeqU8", 2, t.bool], // unsigned
["GeqS16", 2, t.bool],
["GeqU16", 2, t.bool],
["GeqS32", 2, t.bool],
["GeqU32", 2, t.bool],
["GeqS64", 2, t.bool],
["GeqU64", 2, t.bool],
["GeqF32", 2, t.bool],
["GeqF64", 2, t.bool],
//
// boolean ops (AndB and OrB are not shortcircuited)
// ["AndB", 2, Commutative, t.bool], // arg0 && arg1
// ["OrB", 2, Commutative, t.bool], // arg0 || arg1
// ["EqB", 2, Commutative, t.bool], // arg0 == arg1
// ["NeqB", 2, Commutative, t.bool], // arg0 != arg1
["Not", 1, t.bool], // !arg0, boolean
// min(arg0, arg1) ; max(arg0, arg1)
["MinF32", 2],
["MinF64", 2],
["MaxF32", 2],
["MaxF64", 2],
// CondSelect is a conditional MOVE (register to register.)
//
// The type of a CondSelect is the same as the type of its first
// two arguments, which should be register-width scalars; the third
// argument should be a boolean.
//
// Placed during optimization by branchelim
//
// arg2 ? arg0 : arg1
// ["CondSelect", 3],
// 1-input ops
//
// -arg0 ; negation
["NegI8", 1],
["NegI16", 1],
["NegI32", 1],
["NegI64", 1],
["NegF32", 1],
["NegF64", 1],
//
// Count trailing (low order) zeroes
["CtzI8", 1], // returns 0-8
["CtzI16", 1], // returns 0-16
["CtzI32", 1], // returns 0-32
["CtzI64", 1], // returns 0-64
//
// same as above, but arg0 known to be non-zero
["CtzI8NonZero", 1], // returns 0-7
["CtzI16NonZero", 1], // returns 0-15
["CtzI32NonZero", 1], // returns 0-31
["CtzI64NonZero", 1], // returns 0-63
//
// Number of bits in arg0
["BitLen8", 1], // returns 0-8
["BitLen16", 1], // returns 0-16
["BitLen32", 1], // returns 0-32
["BitLen64", 1], // returns 0-64
//
// Swap bytes
// ["Bswap32", 1],
// ["Bswap64", 1], // Swap bytes
//
// Reverse the bits in arg0
// ["BitRev8", 1],
// ["BitRev16", 1], // Reverse the bits in arg0
// ["BitRev32", 1], // Reverse the bits in arg0
// ["BitRev64", 1], // Reverse the bits in arg0
//
// sign-agnostic count number of one bits in arg0
["PopCountI8", 1],
["PopCountI16", 1],
["PopCountI32", 1],
["PopCountI64", 1],
//
// Square root
// Special cases:
// +∞ → +∞
// ±0 → ±0 (sign preserved)
// x<0 → NaN
// NaN → NaN
["SqrtF32", 1], // √arg0
["SqrtF64", 1], // √arg0
//
// Round to integer
// Special cases:
// ±∞ → ±∞ (sign preserved)
// ±0 → ±0 (sign preserved)
// NaN → NaN
["FloorF32", 1], // round arg0 toward -∞
["FloorF64", 1],
["CeilF32", 1], // round arg0 toward +∞
["CeilF64", 1],
["TruncF32", 1], // round arg0 toward 0
["TruncF64", 1],
["RoundF32", 1], // round arg0 to nearest, ties away from 0
["RoundF64", 1],
//
// round arg0 to nearest, ties to even
["RoundToEvenF32", 1],
["RoundToEvenF64", 1],
//
// Modify the sign bit
["AbsF32", 1], // absolute value arg0
["AbsF64", 1],
["CopysignF32", 2], // copy sign from arg0 to arg1
["CopysignF64", 2],
// Conversions
//
// signed extensions
["SignExtI8to16", 1, t.i16], // i8 -> i16
["SignExtI8to32", 1, t.i32], // i8 -> i32
["SignExtI8to64", 1, t.i64], // i8 -> i64
["SignExtI16to32", 1, t.i32], // i16 -> i32
["SignExtI16to64", 1, t.i64], // i16 -> i64
["SignExtI32to64", 1, t.i64], // i32 -> i64
//
// zero (unsigned) extensions
["ZeroExtI8to16", 1, t.u16], // u8 -> u16
["ZeroExtI8to32", 1, t.u32], // u8 -> u32
["ZeroExtI8to64", 1, t.u64], // u8 -> u64
["ZeroExtI16to32", 1, t.u32], // u16 -> u32
["ZeroExtI16to64", 1, t.u64], // u16 -> u64
["ZeroExtI32to64", 1, t.u64], // u32 -> u64
//
// truncations to bool
["TruncI8toBool", 1, t.bool],
["TruncI16toBool", 1, t.bool],
["TruncI32toBool", 1, t.bool],
["TruncI64toBool", 1, t.bool],
["TruncF32toBool", 1, t.bool],
["TruncF64toBool", 1, t.bool],
//
// truncations
["TruncI16to8", 1], // i16 -> i8 ; u16 -> u8
["TruncI32to8", 1], // i32 -> i8 ; u32 -> u8
["TruncI32to16", 1], // i32 -> i16 ; u32 -> u16
["TruncI64to8", 1], // i64 -> i8 ; u64 -> u8
["TruncI64to16", 1], // i64 -> i16 ; u64 -> u16
["TruncI64to32", 1], // i64 -> i32 ; u64 -> u32
//
// conversions
["ConvI32toF32", 1, t.f32], // i32 -> f32
["ConvI32toF64", 1, t.f64], // i32 -> f64
["ConvI64toF32", 1, t.f32], // i64 -> f32
["ConvI64toF64", 1, t.f64], // i64 -> f64
["ConvF32toI32", 1, t.i32], // f32 -> i32
["ConvF32toI64", 1, t.i64], // f32 -> i64
["ConvF64toI32", 1, t.i32], // f64 -> i32
["ConvF64toI64", 1, t.i64], // f64 -> i64
["ConvF32toF64", 1, t.f64], // f32 -> f64
["ConvF64toF32", 1, t.f32], // f64 -> f32
//
// conversions only used on 32-bit arch
["ConvU32toF32", 1, t.f32], // u32 -> f32
["ConvU32toF64", 1, t.f64], // u32 -> f64
["ConvF32toU32", 1, t.u32], // f32 -> u32
["ConvF64toU32", 1, t.u32], // f64 -> u32
//
// conversions only used on archs that has the instruction
["ConvU64toF32", 1, t.f32], // u64 -> f32
["ConvU64toF64", 1, t.f64], // u64 -> f64
["ConvF32toU64", 1, t.u64], // f32 -> u64
["ConvF64toU64", 1, t.u64], // f64 -> u64
// Atomic operations used for semantically inlining runtime/internal/atomic.
// Atomic loads return a new memory so that the loads are properly ordered
// with respect to other loads and stores.
//
["AtomicLoad32", 2, /*{type: "(UInt32,Mem)"}*/], // Load from arg0. arg1=memory. Returns loaded value and new memory.
["AtomicLoad64", 2, /*{type: "(UInt64,Mem)"}*/], // Load from arg0. arg1=memory. Returns loaded value and new memory.
["AtomicLoadPtr", 2, /*{type: "(BytePtr,Mem)"}*/], // Load from arg0. arg1=memory. Returns loaded value and new memory.
["AtomicStore32", 3, HasSideEffects /*{type: "Mem"}*/], // Store arg1 to *arg0. arg2=memory. Returns memory.
["AtomicStore64", 3, HasSideEffects /*{type: "Mem"}*/], // Store arg1 to *arg0. arg2=memory. Returns memory.
["AtomicStorePtr", 3, HasSideEffects, t.mem], // Store arg1 to *arg0. arg2=memory. Returns memory.
["AtomicSwap32", 3, HasSideEffects /*{type: "(UInt32,Mem)"}*/], // Store arg1 to *arg0. arg2=memory. Returns old contents of *arg0 and new memory. like std::atomic::exchange
["AtomicSwap64", 3, HasSideEffects /*{type: "(UInt64,Mem)"}*/], // Store arg1 to *arg0. arg2=memory. Returns old contents of *arg0 and new memory. like std::atomic::exchange
["AtomicAdd32", 3, HasSideEffects /*{type: "(UInt32,Mem)"}*/], // Do *arg0 += arg1. arg2=memory. Returns sum and new memory.
["AtomicAdd64", 3, HasSideEffects /*{type: "(UInt64,Mem)"}*/], // Do *arg0 += arg1. arg2=memory. Returns sum and new memory.
["AtomicCAS32", 4, HasSideEffects /*{type: "(Bool,Mem)"}*/], // if *arg0==arg1, then set *arg0=arg2. Returns true if store happens and new memory.
["AtomicCAS64", 4, HasSideEffects /*{type: "(Bool,Mem)"}*/], // if *arg0==arg1, then set *arg0=arg2. Returns true if store happens and new memory.
["AtomicAnd8", 3, HasSideEffects, t.addr], // *arg0 &= arg1. arg2=memory. Returns memory.
["AtomicOr8", 3, HasSideEffects, t.addr], // *arg0 |= arg1. arg2=memory. Returns memory.
].map(d => {
// add generic flag to all generic ops
;(d as any as any[]).push(Generic)
return d
})
export default {
arch: "generic",
ops,
addrSize: 4,
regSize: 4,
intSize: 4,
registers: [],
hasGReg: false,
gpRegMask: emptyRegSet,
fpRegMask: emptyRegSet,
} as ArchDescr | the_stack |
module android.os {
import Runnable = java.lang.Runnable;
/**
* A Handler allows you to send and process {@link Message} and Runnable
* objects associated with a thread's {@link MessageQueue}. Each Handler
* instance is associated with a single thread and that thread's message
* queue. When you create a new Handler, it is bound to the thread /
* message queue of the thread that is creating it -- from that point on,
* it will deliver messages and runnables to that message queue and execute
* them as they come out of the message queue.
*
* <p>There are two main uses for a Handler: (1) to schedule messages and
* runnables to be executed as some point in the future; and (2) to enqueue
* an action to be performed on a different thread than your own.
*
* <p>Scheduling messages is accomplished with the
* {@link #post}, {@link #postAtTime(Runnable, long)},
* {@link #postDelayed}, {@link #sendEmptyMessage},
* {@link #sendMessage}, {@link #sendMessageAtTime}, and
* {@link #sendMessageDelayed} methods. The <em>post</em> versions allow
* you to enqueue Runnable objects to be called by the message queue when
* they are received; the <em>sendMessage</em> versions allow you to enqueue
* a {@link Message} object containing a bundle of data that will be
* processed by the Handler's {@link #handleMessage} method (requiring that
* you implement a subclass of Handler).
*
* <p>When posting or sending to a Handler, you can either
* allow the item to be processed as soon as the message queue is ready
* to do so, or specify a delay before it gets processed or absolute time for
* it to be processed. The latter two allow you to implement timeouts,
* ticks, and other timing-based behavior.
*
* <p>When a
* process is created for your application, its main thread is dedicated to
* running a message queue that takes care of managing the top-level
* application objects (activities, broadcast receivers, etc) and any windows
* they create. You can create your own threads, and communicate back with
* the main application thread through a Handler. This is done by calling
* the same <em>post</em> or <em>sendMessage</em> methods as before, but from
* your new thread. The given Runnable or Message will then be scheduled
* in the Handler's message queue and processed when appropriate.
*/
export class Handler {
mCallback:Handler.Callback;
/**
* Constructor associates this handler with the {@link Looper} for the
* current thread and takes a callback interface in which you can handle
* messages.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*
* @param callback The callback interface in which to handle messages, or null.
*/
constructor(callback?:Handler.Callback) {
this.mCallback = callback;
}
/**
* Subclasses must implement this to receive messages.
*/
handleMessage(msg:Message):void {
}
/**
* Handle system messages here.
*/
dispatchMessage(msg:Message) {
if (msg.callback != null) {
msg.callback.run();
} else {
if (this.mCallback != null) {
if (this.mCallback.handleMessage(msg)) {
return;
}
}
this.handleMessage(msg);
}
}
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
obtainMessage():Message;
/**
* Same as {@link #obtainMessage()}, except that it also sets the what member of the returned Message.
*
* @param what Value to assign to the returned Message.what field.
* @return A Message from the global message pool.
*/
obtainMessage(what:number):Message;
/**
*
* Same as {@link #obtainMessage()}, except that it also sets the what and obj members
* of the returned Message.
*
* @param what Value to assign to the returned Message.what field.
* @param obj Value to assign to the returned Message.obj field.
* @return A Message from the global message pool.
*/
obtainMessage(what:number, obj:any):Message;
/**
*
* Same as {@link #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
* Message.
* @param what Value to assign to the returned Message.what field.
* @param arg1 Value to assign to the returned Message.arg1 field.
* @param arg2 Value to assign to the returned Message.arg2 field.
* @return A Message from the global message pool.
*/
obtainMessage(what:number, arg1:number, arg2:number):Message;
/**
*
* Same as {@link #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the
* returned Message.
* @param what Value to assign to the returned Message.what field.
* @param arg1 Value to assign to the returned Message.arg1 field.
* @param arg2 Value to assign to the returned Message.arg2 field.
* @param obj Value to assign to the returned Message.obj field.
* @return A Message from the global message pool.
*/
obtainMessage(what:number, arg1:number, arg2:number, obj:any):Message;
obtainMessage(...args):Message {
if (args.length === 2) {
let [what, obj] = args;
return Message.obtain(this, what, obj);
} else {
let [what, arg1, arg2, obj] = args;
return Message.obtain(this, what, arg1, arg2, obj);
}
}
/**
* Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is
* attached.
*
* @param r The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
post(r:Runnable):boolean {
return this.sendMessageDelayed(Handler.getPostMessage(r), 0);
}
protected postAsTraversal(r:Runnable):boolean {
let msg = Handler.getPostMessage(r);
msg.mType = Message.Type_Traversal;
return this.sendMessageDelayed(msg, 0);
}
/**
* Causes the Runnable r to be added to the message queue, to be run
* at a specific time given by <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* The runnable will be run on the thread to which this handler is attached.
*
* @param r The Runnable that will be executed.
* @param uptimeMillis The absolute time at which the callback should run,
* using the {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
postAtTime(r:Runnable, uptimeMillis:number):boolean;
/**
* Causes the Runnable r to be added to the message queue, to be run
* at a specific time given by <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* The runnable will be run on the thread to which this handler is attached.
*
* @param r The Runnable that will be executed.
* @param uptimeMillis The absolute time at which the callback should run,
* using the {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*
* @see android.os.SystemClock#uptimeMillis
*/
postAtTime(r:Runnable, token:any, uptimeMillis:number):boolean;
postAtTime(...args):boolean {
if (args.length === 2) {
let [r, uptimeMillis] = args;
return this.sendMessageAtTime(Handler.getPostMessage(r), uptimeMillis);
} else {
let [r, token, uptimeMillis] = args;
return this.sendMessageAtTime(Handler.getPostMessage(r, token), uptimeMillis);
}
}
/**
* Causes the Runnable r to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the thread to which this handler
* is attached.
*
* @param r The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
postDelayed(r:Runnable, delayMillis:number):boolean {
return this.sendMessageDelayed(Handler.getPostMessage(r), delayMillis);
}
/**
* Posts a message to an object that implements Runnable.
* Causes the Runnable r to executed on the next iteration through the
* message queue. The runnable will be run on the thread to which this
* handler is attached.
* <b>This method is only for use in very special circumstances -- it
* can easily starve the message queue, cause ordering problems, or have
* other unexpected side-effects.</b>
*
* @param r The Runnable that will be executed.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
postAtFrontOfQueue(r:Runnable):boolean {
return this.post(r);
}
/**
* Remove any pending posts of Runnable <var>r</var> with Object
* <var>token</var> that are in the message queue. If <var>token</var> is null,
* all callbacks will be removed.
*/
removeCallbacks(r:Runnable, token?:any) {
MessageQueue.removeMessages(this, r, token);
}
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
sendMessage(msg:Message):boolean {
return this.sendMessageDelayed(msg, 0);
}
/**
* Sends a Message containing only the what value.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
sendEmptyMessage(what:number):boolean {
return this.sendEmptyMessageDelayed(what, 0);
}
/**
* Sends a Message containing only the what value, to be delivered
* after the specified amount of time elapses.
* @see #sendMessageDelayed(android.os.Message, long)
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
sendEmptyMessageDelayed(what:number, delayMillis:number):boolean {
let msg = Message.obtain();
msg.what = what;
return this.sendMessageDelayed(msg, delayMillis);
}
/**
* Sends a Message containing only the what value, to be delivered
* at a specific time.
* @see #sendMessageAtTime(android.os.Message, long)
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
sendEmptyMessageAtTime(what:number, uptimeMillis:number):boolean {
let msg = Message.obtain();
msg.what = what;
return this.sendMessageAtTime(msg, uptimeMillis);
}
/**
* Enqueue a message into the message queue after all pending messages
* before (current time + delayMillis). You will receive it in
* {@link #handleMessage}, in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
sendMessageDelayed(msg:Message, delayMillis:number):boolean {
if (delayMillis < 0) {
delayMillis = 0;
}
return this.sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
sendMessageAtTime(msg:Message, uptimeMillis:number) {
msg.target = this;
return MessageQueue.enqueueMessage(msg, uptimeMillis);
}
/**
* Enqueue a message at the front of the message queue, to be processed on
* the next iteration of the message loop. You will receive it in
* {@link #handleMessage}, in the thread attached to this handler.
* <b>This method is only for use in very special circumstances -- it
* can easily starve the message queue, cause ordering problems, or have
* other unexpected side-effects.</b>
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
sendMessageAtFrontOfQueue(msg:Message) {
return this.sendMessage(msg);
}
/**
* Remove any pending posts of messages with code 'what' and whose obj is
* 'object' that are in the message queue. If <var>object</var> is null,
* all messages will be removed.
*/
removeMessages(what:number, object?:any) {
MessageQueue.removeMessages(this, what, object);
}
/**
* Remove any pending posts of callbacks and sent messages whose
* <var>obj</var> is <var>token</var>. If <var>token</var> is null,
* all callbacks and messages will be removed.
*/
removeCallbacksAndMessages(token?:any) {
MessageQueue.removeCallbacksAndMessages(this, token);
}
/**
* Check if there are any pending posts of messages with code 'what' in
* the message queue.
*/
hasMessages(what:number, object?:any):boolean {
return MessageQueue.hasMessages(this, what, object);
}
private static getPostMessage(r:Runnable, token?:any):Message {
let m = Message.obtain();
m.obj = token;
m.callback = r;
return m;
}
}
export module Handler {
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
export interface Callback {
handleMessage(msg:Message):boolean;
}
}
} | the_stack |
import * as fs from "fs";
import * as path from "path";
import {uint16, uint32} from "./math";
var crypto = require('crypto');
const INTERESTING8 = new Uint8Array([-128, -1, 0, 1, 16, 32, 64, 100, 127]);
const INTERESTING16 = new Uint16Array([-32768, -129, 128, 255, 256, 512, 1000, 1024, 4096, 32767, -128, -1, 0, 1, 16, 32, 64, 100, 127]);
const INTERESTING32 = new Uint32Array([-2147483648, -100663046, -32769, 32768, 65535, 65536, 100663045, 2147483647, -32768, -129, 128, 255, 256, 512, 1000, 1024, 4096, 32767, -128, -1, 0, 1, 16, 32, 64, 100, 127]);
export class Corpus {
private inputs: Buffer[];
private corpusPath: string | undefined;
private maxInputSize: number;
private seedLength: number;
private readonly onlyAscii: boolean;
constructor(dir: string[], onlyAscii: boolean) {
this.inputs = [];
this.onlyAscii = onlyAscii;
this.maxInputSize = 4096;
for (let i of dir) {
if (!fs.existsSync(i)) {
fs.mkdirSync(i);
}
if (fs.lstatSync(i).isDirectory()) {
if (!this.corpusPath) {
this.corpusPath = i;
}
this.loadFiles(i)
} else {
this.inputs.push(fs.readFileSync(i));
}
}
this.seedLength = this.inputs.length;
}
loadFiles(dir: string) {
fs.readdirSync(dir).forEach(file => {
const full_path = path.join(dir, file);
this.inputs.push(fs.readFileSync(full_path))
});
}
getLength() {
return this.inputs.length;
}
generateInput() {
if (this.seedLength > 0) {
this.seedLength -= 1;
return this.inputs[this.seedLength];
}
if (this.inputs.length === 0) {
const buf = Buffer.alloc(0, 0);
this.putBuffer(buf);
return buf;
}
const buffer = this.inputs[this.rand(this.inputs.length)];
return this.mutate(buffer);
}
putBuffer(buf: Buffer) {
this.inputs.push(buf);
if (this.corpusPath) {
const filename = crypto.createHash('sha256').update(buf).digest('hex');
const filepath = path.join(this.corpusPath, filename);
fs.writeFileSync(filepath, buf)
}
}
randBool() {
return Math.random() >= 0.5;
}
rand(n: number) {
return Math.floor(Math.random() * Math.floor(n));
}
dec2bin(dec: number){
const bin = dec.toString(2);
return '0'.repeat(32 - bin.length) + bin;
}
// Exp2 generates n with probability 1/2^(n+1).
Exp2() {
const bin = this.dec2bin(this.rand(2**32));
let count = 0;
for (let i=0; i<32; i++) {
if(bin[i] === '0') {
count += 1;
} else {
break;
}
}
return count;
}
chooseLen(n: number) {
const x = this.rand(100);
if (x < 90) {
return this.rand(Math.min(8, n)) + 1
} else if (x < 99) {
return this.rand(Math.min(32, n)) + 1
} else {
return this.rand(n) + 1;
}
}
toAscii(buf: Buffer) {
let x;
for (let i = 0; i < buf.length; i++) {
x = buf[i] & 127;
if ((x < 0x20 || x > 0x7E) && x !== 0x09 && (x < 0xA || x > 0xD)) {
buf[i] = 0x20;
}
}
}
mutate(buf: Buffer) {
let res = Buffer.allocUnsafe(buf.length);
buf.copy(res, 0, 0, buf.length);
const nm = 1 + this.Exp2();
for (let i=0; i<nm; i++) {
const x = this.rand(16);
if ( x ===0 ) {
// Remove a range of bytes.
if (res.length <= 1) {
i--;
continue
}
const pos0 = this.rand(res.length);
const pos1 = pos0 + this.chooseLen(res.length - pos0);
res.copy(res, pos0, pos1, res.length);
res = res.slice(0, res.length - (pos1 - pos0));
} else if (x === 1) {
// Insert a range of random bytes.
const pos = this.rand(res.length + 1);
const n = this.chooseLen(10);
res = Buffer.concat([res, Buffer.alloc(n, 0)], res.length + n);
res.copy(res, pos + n, pos);
for (let k = 0; k < n; k++) {
res[pos + k] = this.rand(256)
}
} else if (x === 2) {
// Duplicate a range of bytes.
if (res.length <= 1) {
i--;
continue
}
const src = this.rand(res.length);
let dst = this.rand(res.length);
while (src === dst) {
dst = this.rand(res.length);
}
const n = this.chooseLen(res.length - src);
const tmp = Buffer.alloc(n, 0);
res.copy(tmp, 0, src);
res = Buffer.concat([res, Buffer.alloc(n, 0)]);
res.copy(res, dst+n, dst);
for (let k=0; k<n; k++) {
res[dst+k] = tmp[k]
}
} else if (x === 3) {
// Copy a range of bytes.
if (res.length <= 1) {
i--;
continue
}
const src = this.rand(res.length);
let dst = this.rand(res.length);
while (src === dst) {
dst = this.rand(res.length);
}
const n = this.chooseLen(res.length - src);
res.copy(res, dst, src, src+n);
} else if (x === 4) {
// Bit flip. Spooky!
if (res.length <= 1) {
i--;
continue
}
const pos = this.rand(res.length);
res[pos] ^= 1 << this.rand(8);
} else if (x === 5) {
// Set a byte to a random value.
if (res.length <= 1) {
i--;
continue
}
const pos = this.rand(res.length);
res[pos] ^= this.rand(255) + 1;
} else if (x === 6) {
// Swap 2 bytes.
if (res.length <= 1) {
i--;
continue
}
const src = this.rand(res.length);
let dst = this.rand(res.length);
while (src === dst) {
dst = this.rand(res.length);
}
[res[src], res[dst]] = [res[dst], res[src]]
} else if (x === 7) {
// Add/subtract from a byte.
if (res.length === 0) {
i--;
continue
}
const pos = this.rand(res.length);
const v = this.rand(35) + 1;
if (this.randBool()) {
res[pos] += v;
} else {
res[pos] -= v;
}
} else if (x === 8) {
// Add/subtract from a uint16.
if (res.length < 2) {
i--;
continue
}
const pos = this.rand(res.length - 1);
let v = this.rand(35) + 1;
if (this.randBool()) {
v = 0 - v;
}
if (this.randBool()) {
res.writeUInt16BE(uint16(res.readUInt16BE(pos) + v), pos)
} else {
res.writeUInt16LE(uint16(res.readUInt16LE(pos) + v), pos)
}
} else if (x === 9) {
// Add/subtract from a uint32.
if (res.length < 4) {
i--;
continue
}
const pos = this.rand(res.length - 3);
let v = this.rand(35) + 1;
if (this.randBool()) {
v = 0 - v;
}
if (this.randBool()) {
res.writeUInt32BE(uint32(res.readUInt32BE(pos) + v), pos)
} else {
res.writeUInt32LE(uint32(res.readUInt32LE(pos) + v), pos)
}
} else if (x === 10) {
// Replace a byte with an interesting value.
if (res.length === 0) {
i--;
continue;
}
const pos = this.rand(res.length);
res[pos] = INTERESTING8[this.rand(INTERESTING8.length)];
} else if (x === 11) {
// Replace an uint16 with an interesting value.
if (res.length < 2) {
i--;
continue;
}
const pos = this.rand(res.length - 1);
if (this.randBool()) {
res.writeUInt16BE(INTERESTING16[this.rand(INTERESTING8.length)], pos);
} else {
res.writeUInt16LE(INTERESTING16[this.rand(INTERESTING8.length)], pos);
}
} else if (x === 12) {
// Replace an uint32 with an interesting value.
if (res.length < 4) {
i--;
continue;
}
const pos = this.rand(res.length - 3);
if (this.randBool()) {
res.writeUInt32BE(INTERESTING32[this.rand(INTERESTING8.length)], pos);
} else {
res.writeUInt32LE(INTERESTING32[this.rand(INTERESTING8.length)], pos);
}
} else if (x === 13) {
// Replace an ascii digit with another digit.
const digits = [];
for (let k=0; k<res.length; k++) {
if (res[k] >= 48 && res[k] <= 57) {
digits.push(k)
}
}
if (digits.length === 0) {
i--;
continue;
}
const pos = this.rand(digits.length);
const was = res[digits[pos]];
let now = was;
while (now === was) {
now = this.rand(10) + 48 // '0' === 48
}
res[digits[pos]] = now
} else if (x === 14) {
// Splice another input.
if (res.length < 4 || this.inputs.length < 2) {
i--;
continue;
}
const other = this.inputs[this.rand(this.inputs.length)];
if (other.length < 4) {
i--;
continue;
}
// Find common prefix and suffix.
let idx0 = 0;
while (idx0 < res.length && idx0 < other.length && res[idx0] === other[idx0]) {
idx0++;
}
let idx1 = 0;
while (idx1 < res.length && idx1 < other.length && res[res.length-idx1-1] === other[other.length-idx1-1]) {
idx1++;
}
// If diffing parts are too small, there is no sense in splicing, rely on byte flipping.
const diff = Math.min(res.length-idx0-idx1, other.length-idx0-idx1);
if (diff < 4) {
i--;
continue;
}
other.copy(res, idx0, idx0, Math.min(other.length, idx0+this.rand(diff-2)+1))
} else if (x === 15) {
// Insert a part of another input.
if (res.length < 4 || this.inputs.length < 2) {
i--;
continue;
}
const other = this.inputs[this.rand(this.inputs.length)];
if (other.length < 4) {
i--;
continue;
}
const pos0 = this.rand(res.length+1);
const pos1 = this.rand(other.length-2);
const n = this.chooseLen(other.length-pos1-2) + 2;
res = Buffer.concat([res, Buffer.alloc(n, 0)], res.length + n);
res.copy(res, pos0+n, pos0);
for (let k=0; k<n; k++) {
res[pos0+k] = other[pos1+k]
}
}
}
if (res.length > this.maxInputSize) {
res = res.slice(0, this.maxInputSize)
}
if (this.onlyAscii) {
this.toAscii(res);
}
return res;
}
} | the_stack |
import {Command} from 'app/client/components/commands';
import {NeedUpgradeError, reportError} from 'app/client/models/errors';
import {colors, testId, vars} from 'app/client/ui2018/cssVars';
import {cssSelectBtn} from 'app/client/ui2018/select';
import {IconName} from 'app/client/ui2018/IconList';
import {icon} from 'app/client/ui2018/icons';
import {commonUrls} from 'app/common/gristUrls';
import {Computed, dom, DomElementArg, DomElementMethod, MaybeObsArray, MutableObsArray, Observable,
styled} from 'grainjs';
import * as weasel from 'popweasel';
import {cssCheckboxSquare, cssLabel, cssLabelText} from 'app/client/ui2018/checkbox';
export interface IOptionFull<T> {
value: T;
label: string;
disabled?: boolean;
icon?: IconName;
}
// For string options, we can use a string for label and value without wrapping into an object.
export type IOption<T> = (T & string) | IOptionFull<T>;
export function menu(createFunc: weasel.MenuCreateFunc, options?: weasel.IMenuOptions): DomElementMethod {
return weasel.menu(createFunc, {...defaults, ...options});
}
// TODO Weasel doesn't allow other options for submenus, but probably should.
export type ISubMenuOptions = weasel.ISubMenuOptions & weasel.IPopupOptions;
export function menuItemSubmenu(
submenu: weasel.MenuCreateFunc,
options: ISubMenuOptions,
...args: DomElementArg[]
): Element {
return weasel.menuItemSubmenu(submenu, {...defaults, ...options}, ...args);
}
const cssMenuElem = styled('div', `
font-family: ${vars.fontFamily};
font-size: ${vars.mediumFontSize};
line-height: initial;
max-width: 400px;
padding: 8px 0px 16px 0px;
box-shadow: 0 2px 20px 0 rgba(38,38,51,0.6);
min-width: 160px;
z-index: 999;
--weaseljs-selected-background-color: ${vars.primaryBg};
--weaseljs-menu-item-padding: 8px 24px;
@media print {
& {
display: none;
}
}
`);
const menuItemStyle = `
justify-content: flex-start;
align-items: center;
--icon-color: ${colors.lightGreen};
.${weasel.cssMenuItem.className}-sel {
--icon-color: ${colors.light};
}
&.disabled {
cursor: default;
opacity: 0.2;
}
`;
export const menuCssClass = cssMenuElem.className;
// Add grist-floating-menu class to support existing browser tests
const defaults = { menuCssClass: menuCssClass + ' grist-floating-menu' };
/**
* Creates a select dropdown widget. The observable `obs` reflects the value of the selected
* option, and `optionArray` is an array (regular or observable) of option values and labels.
* These may be either strings, or {label, value, icon, disabled} objects. Icons are optional
* and must be IconName strings from 'app/client/ui2018/IconList'.
*
* The type of value may be any type at all; it is opaque to this widget.
*
* If obs is set to an invalid or disabled value, then defLabel option is used to determine the
* label that the select box will show, blank by default.
*
* Usage:
* const fruit = observable("apple");
* select(fruit, ["apple", "banana", "mango"]);
*
* const employee = observable(17);
* const allEmployees = Observable.create(owner, [
* {value: 12, label: "Bob", disabled: true},
* {value: 17, label: "Alice"},
* {value: 21, label: "Eve"},
* ]);
* select(employee, allEmployees, {defLabel: "Select employee:"});
*
* Note that this select element is not compatible with browser address autofill for usage in
* forms, and that formSelect should be used for this purpose.
*/
export function select<T>(obs: Observable<T>, optionArray: MaybeObsArray<IOption<T>>,
options: weasel.ISelectUserOptions = {}) {
const _menu = cssSelectMenuElem(testId('select-menu'));
const _btn = cssSelectBtn(testId('select-open'));
const {menuCssClass: menuClass, ...otherOptions} = options;
const selectOptions = {
buttonArrow: cssInlineCollapseIcon('Collapse'),
menuCssClass: _menu.className + ' ' + (menuClass || ''),
buttonCssClass: _btn.className,
...otherOptions,
};
return weasel.select(obs, optionArray, selectOptions, (op) =>
cssOptionRow(
op.icon ? cssOptionRowIcon(op.icon) : null,
cssOptionLabel(op.label),
testId('select-row')
)
) as HTMLElement; // TODO: should be changed in weasel
}
/**
* Same as select(), but the main element looks like a link rather than a button.
*/
export function linkSelect<T>(obs: Observable<T>, optionArray: MaybeObsArray<IOption<T>>,
options: weasel.ISelectUserOptions = {}) {
const _btn = cssSelectBtnLink(testId('select-open'));
const elem = select(obs, optionArray, {buttonCssClass: _btn.className, ...options});
// It feels strange to have focus stay on this link; remove tabIndex that makes it focusable.
elem.removeAttribute('tabIndex');
return elem;
}
export interface IMultiSelectUserOptions {
placeholder?: string;
error?: Observable<boolean>;
}
/**
* Creates a select dropdown widget that supports selecting multiple options.
*
* The observable array `selectedOptions` reflects the selected options, and
* `availableOptions` is an array (normal or observable) of selectable options.
* These may either be strings, or {label, value} objects.
*/
export function multiSelect<T>(selectedOptions: MutableObsArray<T>,
availableOptions: MaybeObsArray<IOption<T>>,
options: IMultiSelectUserOptions = {},
...domArgs: DomElementArg[]) {
const selectedOptionsSet = Computed.create(null, selectedOptions, (_use, opts) => new Set(opts));
const selectedOptionsText = Computed.create(null, selectedOptionsSet, (use, selectedOpts) => {
if (selectedOpts.size === 0) {
return options.placeholder ?? 'Select fields';
}
const optionArray = Array.isArray(availableOptions) ? availableOptions : use(availableOptions);
return optionArray
.filter(opt => selectedOpts.has(weasel.getOptionFull(opt).value))
.map(opt => weasel.getOptionFull(opt).label)
.join(', ');
});
function buildMultiSelectMenu(ctl: weasel.IOpenController) {
return cssMultiSelectMenu(
{ tabindex: '-1' }, // Allow menu to be focused.
dom.cls(menuCssClass),
dom.onKeyDown({
Enter: () => ctl.close(),
Escape: () => ctl.close()
}),
elem => {
// Set focus on open, so that keyboard events work.
setTimeout(() => elem.focus(), 0);
// Sets menu width to match parent container (button) width.
const style = elem.style;
style.minWidth = ctl.getTriggerElem().getBoundingClientRect().width + 'px';
style.marginLeft = style.marginRight = '0';
},
dom.domComputed(selectedOptionsSet, selectedOpts => {
return dom.forEach(availableOptions, option => {
const fullOption = weasel.getOptionFull(option);
return cssCheckboxLabel(
cssCheckboxSquare(
{type: 'checkbox'},
dom.prop('checked', selectedOpts.has(fullOption.value)),
dom.on('change', (_ev, elem) => {
if (elem.checked) {
selectedOptions.push(fullOption.value);
} else {
selectedOpts.delete(fullOption.value);
selectedOptions.set([...selectedOpts]);
}
}),
dom.style('position', 'relative'),
testId('multi-select-menu-option-checkbox')
),
cssCheckboxText(fullOption.label, testId('multi-select-menu-option-text')),
testId('multi-select-menu-option')
);
});
}),
testId('multi-select-menu')
);
}
return cssSelectBtn(
dom.autoDispose(selectedOptionsSet),
dom.autoDispose(selectedOptionsText),
cssMultiSelectSummary(dom.text(selectedOptionsText)),
icon('Dropdown'),
elem => {
weasel.setPopupToCreateDom(elem, ctl => buildMultiSelectMenu(ctl), weasel.defaultMenuOptions);
},
dom.style('border', use => {
return options.error && use(options.error) ? '1px solid red' : `1px solid ${colors.darkGrey}`;
}),
...domArgs
);
}
/**
* Creates a select dropdown widget that is more ideal for forms. Implemented using the <select>
* element to work with browser form autofill and typing in the desired value to quickly set it.
* The appearance of the opened menu is OS dependent.
*
* The observable `obs` reflects the value of the selected option, and `optionArray` is an
* array (regular or observable) of option values and labels. These may be either strings,
* or {label, value} objects.
*
* If obs is set to an empty string value, then defLabel option is used to determine the
* label that the select box will show, blank by default.
*
* Usage:
* const fruit = observable("");
* formSelect(fruit, ["apple", "banana", "mango"], {defLabel: "Select fruit:"});
*/
export function formSelect(obs: Observable<string>, optionArray: MaybeObsArray<IOption<string>>,
options: {defaultLabel?: string} = {}) {
const {defaultLabel = ""} = options;
const container: Element = cssSelectBtnContainer(
dom('select', {class: cssSelectBtn.className, style: 'height: 42px; padding: 12px 30px 12px 12px;'},
dom.prop('value', obs),
dom.on('change', (_, elem) => { obs.set(elem.value); }),
dom('option', {value: '', hidden: 'hidden'}, defaultLabel),
dom.forEach(optionArray, (option) => {
const obj: weasel.IOptionFull<string> = weasel.getOptionFull(option);
return dom('option', {value: obj.value}, obj.label);
})
),
cssCollapseIcon('Collapse')
);
return container;
}
export function inputMenu(createFunc: weasel.MenuCreateFunc, options?: weasel.IMenuOptions): DomElementMethod {
// Triggers the input menu on 'input' events, if the input has text inside.
function inputTrigger(triggerElem: Element, ctl: weasel.PopupControl): void {
dom.onElem(triggerElem, 'input', () => {
(triggerElem as HTMLInputElement).value.length > 0 ? ctl.open() : ctl.close();
});
}
return weasel.inputMenu(createFunc, {
trigger: [inputTrigger],
menuCssClass: `${cssMenuElem.className} ${cssInputButtonMenuElem.className}`,
...options
});
}
// A menu item that leads to the billing page if the desired operation requires an upgrade.
// Such menu items are marked with a little sparkle unicode.
export function upgradableMenuItem(needUpgrade: boolean, action: () => void, ...rem: any[]) {
if (needUpgrade) {
return menuItem(() => reportError(new NeedUpgradeError()), ...rem, " *");
} else {
return menuItem(action, ...rem);
}
}
export function upgradeText(needUpgrade: boolean) {
if (!needUpgrade) { return null; }
return menuText(dom('span', '* Workspaces are available on team plans. ',
dom('a', {href: commonUrls.plans}, 'Upgrade now')));
}
/**
* Create an autocomplete element and tie it to an input or textarea element.
*
* Usage:
* const employees = ['Thomas', 'June', 'Bethany', 'Mark', 'Marjorey', 'Zachary'];
* const inputElem = input(...);
* autocomplete(inputElem, employees);
*/
export function autocomplete(
inputElem: HTMLInputElement,
choices: MaybeObsArray<string>,
options: weasel.IAutocompleteOptions = {}
) {
return weasel.autocomplete(inputElem, choices, {
...defaults, ...options,
menuCssClass: defaults.menuCssClass + ' ' + cssSelectMenuElem.className + ' ' + (options.menuCssClass || '')
});
}
export const menuSubHeader = styled('div', `
font-size: ${vars.xsmallFontSize};
text-transform: uppercase;
font-weight: ${vars.bigControlTextWeight};
padding: 8px 24px 16px 24px;
cursor: default;
`);
export const menuText = styled('div', `
display: flex;
align-items: center;
font-size: ${vars.smallFontSize};
color: ${colors.slate};
padding: 8px 24px 4px 24px;
max-width: 250px;
cursor: default;
`);
export const menuItem = styled(weasel.menuItem, menuItemStyle);
export const menuItemLink = styled(weasel.menuItemLink, menuItemStyle);
/**
* A version of menuItem which runs the action on next tick, allowing the menu to close even when
* the action causes the disabling of the element being clicked.
* TODO disabling the element should not prevent the menu from closing; once fixed in weasel, this
* can be removed.
*/
export const menuItemAsync: typeof weasel.menuItem = function(action, ...args) {
return menuItem(() => setTimeout(action, 0), ...args);
};
export function menuItemCmd(cmd: Command, label: string, ...args: DomElementArg[]) {
return menuItem(
cmd.run,
dom('span', label, testId('cmd-name')),
cmd.humanKeys.length ? cssCmdKey(cmd.humanKeys[0]) : null,
cssMenuItemCmd.cls(''), // overrides some menu item styles
...args
);
}
export function menuAnnotate(text: string, ...args: DomElementArg[]) {
return cssAnnotateMenuItem(text, ...args);
}
export const menuDivider = styled(weasel.cssMenuDivider, `
margin: 8px 0;
`);
export const menuIcon = styled(icon, `
flex: none;
margin-right: 8px;
`);
const cssSelectMenuElem = styled(cssMenuElem, `
max-height: 400px;
overflow-y: auto;
--weaseljs-menu-item-padding: 8px 16px;
`);
const cssSelectBtnContainer = styled('div', `
position: relative;
width: 100%;
`);
const cssSelectBtnLink = styled('div', `
display: flex;
align-items: center;
font-size: ${vars.mediumFontSize};
color: ${colors.lightGreen};
--icon-color: ${colors.lightGreen};
width: initial;
height: initial;
line-height: inherit;
background-color: initial;
padding: initial;
border: initial;
border-radius: initial;
box-shadow: initial;
cursor: pointer;
outline: none;
-webkit-appearance: none;
-moz-appearance: none;
&:hover, &:focus, &:active {
color: ${colors.darkGreen};
--icon-color: ${colors.darkGreen};
box-shadow: initial;
}
`);
const cssOptionIcon = styled(icon, `
height: 16px;
width: 16px;
background-color: ${colors.slate};
margin: -3px 8px 0 2px;
`);
const cssOptionRow = styled('span', `
display: flex;
align-items: center;
width: 100%;
`);
const cssOptionRowIcon = styled(cssOptionIcon, `
margin: 0 8px 0 0;
flex: none;
.${weasel.cssMenuItem.className}-sel & {
background-color: white;
}
`);
const cssOptionLabel = styled('div', `
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`);
const cssInlineCollapseIcon = styled(icon, `
margin: 0 2px;
pointer-events: none;
`);
const cssCollapseIcon = styled(icon, `
position: absolute;
right: 12px;
top: calc(50% - 8px);
pointer-events: none;
background-color: ${colors.dark};
`);
const cssInputButtonMenuElem = styled(cssMenuElem, `
padding: 4px 0px;
`);
const cssMenuItemCmd = styled('div', `
justify-content: space-between;
`);
const cssCmdKey = styled('span', `
margin-left: 16px;
color: ${colors.slate};
margin-right: -12px;
`);
const cssAnnotateMenuItem = styled('span', `
color: ${colors.lightGreen};
text-transform: uppercase;
font-size: 8px;
vertical-align: super;
margin-top: -4px;
margin-left: 4px;
font-weight: bold;
.${weasel.cssMenuItem.className}-sel > & {
color: white;
}
`);
const cssMultiSelectSummary = styled('div', `
flex: 1 1 0px;
overflow: hidden;
text-overflow: ellipsis;
`);
const cssMultiSelectMenu = styled(weasel.cssMenu, `
display: flex;
flex-direction: column;
max-height: calc(max(300px, 95vh - 300px));
max-width: 400px;
padding-bottom: 0px;
`);
const cssCheckboxLabel = styled(cssLabel, `
padding: 8px 16px;
`);
const cssCheckboxText = styled(cssLabelText, `
margin-right: 12px;
color: ${colors.dark};
white-space: pre;
`); | the_stack |
import {expect} from 'chai';
import path = require('path');
import Sinon = require('sinon');
import {Controller} from '../../src/Controller';
import {Rule, RuleGroup, RuleTarget} from '../../src/types';
import {CategoryFilter, EngineFilter, LanguageFilter, RuleFilter, RulesetFilter} from '../../src/lib/RuleFilter';
import {DefaultRuleManager} from '../../src/lib/DefaultRuleManager';
import {OUTPUT_FORMAT, RuleManager} from '../../src/lib/RuleManager';
import {uxEvents} from '../../src/lib/ScannerEvents';
import {RuleCatalog} from '../../src/lib/services/RuleCatalog';
import {RuleEngine} from '../../src/lib/services/RuleEngine';
import {RetireJsEngine} from '../../src/lib/retire-js/RetireJsEngine';
import * as TestOverrides from '../test-related-lib/TestOverrides';
import * as TestUtils from '../TestUtils';
TestOverrides.initializeTestSetup();
let ruleManager: RuleManager = null;
const EMPTY_ENGINE_OPTIONS = new Map<string, string>();
describe('RuleManager', () => {
let uxSpy;
beforeEach(() => {
Sinon.createSandbox();
uxSpy = Sinon.spy(uxEvents, 'emit');
});
afterEach(() => {
Sinon.restore();
});
before(async () => {
TestUtils.stubCatalogFixture();
// Declare our rule manager.
ruleManager = await Controller.createRuleManager();
});
describe('getRulesMatchingCriteria()', () => {
describe('Test Case: No filters provided', () => {
it('When no filters are provided, all default-enabled rules are returned', async () => {
// If we pass an empty list into the method, that's treated as the absence of filter criteria.
const allRules = await ruleManager.getRulesMatchingCriteria([]);
// Expect all default-enabled rules to have been returned.
expect(allRules).to.have.lengthOf(TestUtils.CATALOG_FIXTURE_DEFAULT_ENABLED_RULE_COUNT, 'All rules should have been returned');
});
});
describe('Test Case: Filtering by category only', () => {
it('Filtering by one category returns only rules in that category', async () => {
// Set up our filter array.
const category = 'Best Practices';
const filters = [
new CategoryFilter([category]),
new EngineFilter(['pmd'])];
// Pass the filter array into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(filters);
// Expect the right number of rules to be returned.
expect(matchingRules).to.have.lengthOf(2, 'Exactly 2 pmd rules are categorized as "Best Practices".');
for (const rule of matchingRules) {
expect(rule.categories).to.contain(category);
}
});
it('Filtering by multiple categories returns any rule in either category', async () => {
// Set up our filter array.
const categories = ['Best Practices', 'Design'];
const filters = [new CategoryFilter(categories)];
// Pass the filter array into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(filters);
// Expect the right number of rules to be returned.
expect(matchingRules).to.have.lengthOf(7, 'Exactly 7 rules in enabled engines are categorized as "Best Practices" or "Design"');
for (const rule of matchingRules) {
for (const category of rule.categories) {
expect(categories, JSON.stringify(matchingRules)).to.contain(category);
}
}
});
});
describe('Test Case: Filtering by ruleset only', () => {
it('Filtering by a single ruleset returns only the rules in that ruleset', async () => {
// Set up our filter array.
const filters = [new RulesetFilter(['Braces'])];
// Pass the filter array into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(filters);
// Expect the right number of rules to be returned.
expect(matchingRules).to.have.lengthOf(3, 'Exactly 8 rules are in the "Braces" ruleset');
});
it('Filtering by multiple rulesets returns any rule in either ruleset', async () => {
// Set up our filter array.
const filters = [new RulesetFilter(['Braces', 'Best Practices'])];
// Pass the filter array into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(filters);
// Expect the right number of rules to be returned.
expect(matchingRules).to.have.lengthOf(6, 'Exactly 6 rules in enabled engines are in the "Braces" or "Best Practices" rulesets');
});
});
describe('Test Case: Filtering by language', () => {
it('Filtering by a single language returns only rules targeting that language', async () => {
// Set up our filter array.
const filters = [new LanguageFilter(['apex'])];
// Pass the filter array into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(filters);
// Expect the right number of rules to be returned.
expect(matchingRules).to.have.lengthOf(2, 'There are 2 rules that target Apex');
});
it('Filtering by multiple languages returns any rule targeting either language', async () => {
// Set up our filter array.
const filters = [new LanguageFilter(['apex', 'javascript'])];
// Pass the filter array into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(filters);
// Expect the right number of rules to be returned.
expect(matchingRules).to.have.lengthOf(11, 'There are 11 rules targeting either Apex or JS');
});
});
describe('Test Case: Mixing filter types', () => {
it('Filtering on multiple columns at once returns only rules that satisfy ALL filters', async () => {
// Set up our filter array.
const category = 'Best Practices';
const filters = [
new LanguageFilter(['javascript']),
new CategoryFilter([category])
];
// Pass the filter array into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(filters);
// Expect the right number of rules to be returned.
expect(matchingRules).to.have.lengthOf(4, 'Exactly 4 rules target Apex and are categorized as "Best Practices".');
for (const rule of matchingRules) {
expect(rule.categories).to.contain(category);
}
});
});
describe('Edge Case: No rules match criteria', () => {
it('When no rules match the given criteria, an empty list is returned', async () => {
// Define our preposterous filter array.
const impossibleFilters = [new CategoryFilter(['beebleborp'])];
// Pass our filters into the manager.
const matchingRules = await ruleManager.getRulesMatchingCriteria(impossibleFilters);
// There shouldn't be anything in the array.
expect(matchingRules).to.have.lengthOf(0, 'Should be no matching rules');
});
});
});
describe('runRulesMatchingCriteria()', () => {
describe('Test Case: Run against test projects', () => {
before(() => {
process.chdir(path.join('test', 'code-fixtures', 'projects'));
});
after(() => {
process.chdir("../../..");
});
describe('Test Case: Run without filters', () => {
it('JS project files', async () => {
// If we pass an empty list into the method, that's treated as the absence of filter criteria.
const {results} = await ruleManager.runRulesMatchingCriteria([], ['js'], {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
let parsedRes = null;
if (typeof results !== "string") {
expect(false, `Invalid output: ${results}`);
} else {
parsedRes = JSON.parse(results);
}
expect(parsedRes, '' + results).to.be.an("array").that.has.length(1);
for (const res of parsedRes) {
expect(res.violations[0], `Message is ${res.violations[0].message}`).to.have.property("ruleName").that.is.not.null;
}
});
it('TS project files', async () => {
// If we pass an empty list into the method, that's treated as the absence of filter criteria.
const {results} = await ruleManager.runRulesMatchingCriteria([], ['ts'], {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
let parsedRes = null;
if (typeof results !== "string") {
expect(false, `Invalid output: ${results}`);
} else {
parsedRes = JSON.parse(results);
}
expect(parsedRes).to.be.an("array").that.has.length(1);
for (const res of parsedRes) {
expect(res.violations[0], `Message is ${res.violations[0].message}`).to.have.property("ruleName").that.is.not.null;
}
});
it('App project files', async () => {
// If we pass an empty list into the method, that's treated as the absence of filter criteria.
const {results} = await ruleManager.runRulesMatchingCriteria([], ['app'], {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
let parsedRes = null;
if (typeof results !== "string") {
expect(false, `Invalid output: ${results}`);
} else {
parsedRes = JSON.parse(results);
}
expect(parsedRes).to.be.an("array").that.has.length(8);
for (const res of parsedRes) {
expect(res.violations[0], `Message is ${res.violations[0]['message']}`).to.have.property("ruleName").that.is.not.null;
}
});
it('All targets match', async () => {
const validTargets = ['js/**/*.js', 'app/force-app/main/default/classes', '!**/negative-filter-does-not-exist/**'];
// Set up our filter array.
const categories = ['Possible Errors'];
const filters = [new CategoryFilter(categories)];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, validTargets, {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
let parsedRes = null;
if (typeof results !== "string") {
expect(false, `Invalid output: ${results}`);
} else {
parsedRes = JSON.parse(results);
}
expect(parsedRes).to.be.an("array").that.has.length(1);
Sinon.assert.callCount(uxSpy, 0);
});
it('Single target file does not match', async () => {
const invalidTarget = ['does-not-exist.js'];
// No filters
const filters = [];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, invalidTarget, {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
expect(results).to.equal('');
Sinon.assert.calledWith(uxSpy, 'warning-always', `Target: '${invalidTarget.join(', ')}' was not processed by any engines.`);
});
});
describe('Test Case: Run by category', () => {
it('Filtering by one category runs only rules in that category', async () => {
// Set up our filter array.
const category = 'Best Practices';
const filters = [
new CategoryFilter([category])];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, ['app'], {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
let parsedRes = null;
if (typeof results !== "string") {
expect(false, `Invalid output: ${results}`);
} else {
parsedRes = JSON.parse(results);
}
expect(parsedRes, JSON.stringify(parsedRes)).to.be.an("array").that.has.length(3);
for (const res of parsedRes) {
for (const violation of res.violations) {
expect(violation, `Message is ${violation['message']}`).to.have.property("ruleName").that.is.not.null;
expect(violation.category).to.equal(category);
}
}
});
it('Filtering by multiple categories runs any rule in either category', async () => {
// Set up our filter array.
const categories = ['Best Practices', 'Error Prone'];
const filters = [new CategoryFilter(categories)];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, ['app'], {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
let parsedRes = null;
if (typeof results !== "string") {
expect(false, `Invalid output: ${results}`);
} else {
parsedRes = JSON.parse(results);
}
expect(parsedRes).to.be.an("array").that.has.length(6);
for (const res of parsedRes) {
expect(res.violations[0], `Message is ${res.violations[0]['message']}`).to.have.property("ruleName").that.is.not.null;
expect(res.violations[0].category).to.be.oneOf(categories);
}
});
});
describe('Edge Cases', () => {
it('When no rules match the given criteria, an empty string is returned', async () => {
// Define our preposterous filter array.
const filters = [new CategoryFilter(['beebleborp'])];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, ['app'], {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
expect(typeof results).to.equal('string', `Output ${results} should have been a string`);
expect(results).to.equal('', `Output ${results} should have been an empty string`);
});
it('Single target file does not match', async () => {
const invalidTarget = ['does-not-exist.js'];
// Set up our filter array.
const categories = ['Best Practices', 'Error Prone'];
const filters = [new CategoryFilter(categories)];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, invalidTarget, {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
expect(results).to.equal('');
Sinon.assert.callCount(uxSpy, 1);
Sinon.assert.calledWith(uxSpy, 'warning-always', `Target: '${invalidTarget.join(', ')}' was not processed by any engines.`);
});
it('Single target directory does not match', async () => {
const invalidTarget = ['app/force-app/main/default/no-such-directory'];
// Set up our filter array.
const categories = ['Best Practices', 'Error Prone'];
const filters = [new CategoryFilter(categories)];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, invalidTarget, {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
expect(results).to.equal('');
Sinon.assert.callCount(uxSpy, 1);
Sinon.assert.calledWith(uxSpy, 'warning-always', `Target: '${invalidTarget.join(', ')}' was not processed by any engines.`);
});
it('Multiple targets do not match', async () => {
const invalidTargets = ['does-not-exist-1.js', 'does-not-exist-2.js', 'app/force-app/main/default/no-such-directory'];
// Set up our filter array.
const categories = ['Best Practices', 'Error Prone'];
const filters = [new CategoryFilter(categories)];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, invalidTargets, {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
expect(results).to.equal('');
Sinon.assert.callCount(uxSpy, 1);
Sinon.assert.calledWith(uxSpy, 'warning-always', `Targets: '${invalidTargets.join(', ')}' were not processed by any engines.`);
});
it('Some targets do not match', async () => {
const invalidTargets = ['does-not-exist-1.js', 'does-not-exist-2.js', '**/non-existent/**/*.js', 'app/force-app/main/default/no-such-directory'];
const validTargets = ['js/**/*.js', '!**/negative-filter-does-not-exist/**'];
// Set up our filter array.
const categories = ['Possible Errors'];
const filters = [new CategoryFilter(categories)];
const {results} = await ruleManager.runRulesMatchingCriteria(filters, [...invalidTargets, ...validTargets], {format: OUTPUT_FORMAT.JSON, normalizeSeverity: false}, EMPTY_ENGINE_OPTIONS);
let parsedRes = null;
if (typeof results !== "string") {
expect(false, `Invalid output: ${results}`);
} else {
parsedRes = JSON.parse(results);
}
expect(parsedRes).to.be.an("array").that.has.length(1);
Sinon.assert.callCount(uxSpy, 1);
Sinon.assert.calledWith(uxSpy, 'warning-always', `Targets: '${invalidTargets.join(', ')}' were not processed by any engines.`);
});
});
});
});
describe('unpackTargets()', () => {
// We want to create a subclass of DefaultRuleManager that exposes the protected method `unpackTargets()`.
// In order to do that, we'll also need a very basic implementation of RuleCatalog to give to the constructor.
// That way, we can sidestep any need to mess with the controller or IoC.
class DummyCatalog implements RuleCatalog {
getRule(engine: string, ruleName: string): Rule {
throw new Error('Method not implemented.');
}
getRuleGroupsMatchingFilters(filters: RuleFilter[]): RuleGroup[] {
return [];
}
getRulesMatchingFilters(filters: RuleFilter[]): Rule[] {
return [];
}
init(): Promise<void> {
return;
}
}
class UnpackTargetsDRM extends DefaultRuleManager {
constructor() {
super(new DummyCatalog());
}
public async unpackTargets(engine: RuleEngine, targets: string[], matchedTargets: Set<string>): Promise<RuleTarget[]> {
return super.unpackTargets(engine, targets, matchedTargets);
}
}
describe('Positive matching', () => {
it('File-type targets are properly matched', async () => {
// All of the tests will use the RetireJS engine, since it's got the most straightforward inclusion/exclusion rules.
const engine = new RetireJsEngine();
await engine.init();
// Targets are all going to be normalized to Unix paths.
const targets = [
'test/code-fixtures/projects/dep-test-app/folder-a/SomeGenericFile.js', // This file is real and should be included.
'test/code-fixtures/projects/dep-test-app/folder-e/JsStaticResource1.resource', // This file is also real and should be included.
'test/code-fixtures/apex/SomeTestClass.cls', // This file is real, but should be excluded since it's Apex.
'test/beep/boop/not/real.js' // This file isn't real, and shouldn't be included.
];
const testRuleManager: UnpackTargetsDRM = new UnpackTargetsDRM();
await testRuleManager.init();
// THIS IS THE INVOCATION OF THE TARGET METHOD!
const results: RuleTarget[] = await testRuleManager.unpackTargets(engine, targets, new Set());
// Validate the results.
expect(results.length).to.equal(2, 'Wrong number of targets matched');
expect(results[0].target).to.equal(targets[0], 'Wrong file matched');
expect(results[0].isDirectory).to.not.equal(true, 'Should not be flagged as directory');
expect(results[0].paths.length).to.equal(1, 'Wrong number of paths matched');
expect(results[1].target).to.equal(targets[1], 'Wrong file matched');
expect(results[1].isDirectory).to.not.equal(true, 'Should not be flagged as directory');
expect(results[1].paths.length).to.equal(1, 'Wrong number of paths matched');
});
it('Directory-type targets are properly matched', async () => {
// All of the tests will use the RetireJS engine, since it's got the most straightforward inclusion/exclusion rules.
const engine = new RetireJsEngine();
await engine.init();
// Targets are all going to be normalized to Unix paths.
const targets = [
'test/code-fixtures/projects/dep-test-app/folder-a', // This directory is real and contains JS files, so it should be included.
'test/code-fixtures/apex', // This directory is real, but contains only Apex, so should be excluded.
'test/beep/boop/not/real' // This directory doesn't exist at all, and should be excluded.
];
const testRuleManager: UnpackTargetsDRM = new UnpackTargetsDRM();
await testRuleManager.init();
// THIS IS THE INVOCATION OF THE TARGET METHOD!
const results: RuleTarget[] = await testRuleManager.unpackTargets(engine, targets, new Set());
// Validate the results.
expect(results.length).to.equal(1, 'Wrong number of targets matched');
expect(results[0].target).to.equal(targets[0], 'Wrong directory matched');
expect(results[0].isDirectory).to.equal(true, 'Should be flagged as directory');
expect(results[0].paths.length).to.equal(2, 'Wrong number of paths matched');
});
it('Positive glob-type targets are properly matched', async () => {
// All of the tests will use the RetireJS engine, since it's got the most straightforward inclusion/exclusion rules.
const engine = new RetireJsEngine();
await engine.init();
// Targets are all going to be normalized to Unix paths.
const targets = [
'test/code-fixtures/projects/dep-test-app/**/*Generic*.js', // This glob matches some JS files, and should be included.
'test/code-fixtures/apex/**/*.cls', // This glob only matches Apex files, so it should be excluded.
'test/code-fixtures/beep/boop/**/*' // This glob won't match anything at all, so it should be excluded.
];
const testRuleManager: UnpackTargetsDRM = new UnpackTargetsDRM();
await testRuleManager.init();
// THIS IS THE INVOCATION OF THE TARGET METHOD!
const results: RuleTarget[] = await testRuleManager.unpackTargets(engine, targets, new Set());
// Validate the results.
expect(results.length).to.equal(1, 'Wrong number of targets matched');
expect(results[0].target).to.equal(targets[0], 'Wrong glob matched');
expect(results[0].isDirectory).to.not.equal(true, 'Should not be flagged as directory');
expect(results[0].paths.length).to.equal(2, 'Wrong number of paths matched');
});
});
describe('Negative matching', () => {
it('Negative globs properly interact with file targets', async () => {
// All of the tests will use the RetireJS engine, since it's got the most straightforward inclusion/exclusion rules.
const engine = new RetireJsEngine();
await engine.init();
// Targets are all going to be normalized to Unix paths.
const targets = [
'!**/folder-b/**/*', // This is our negative glob.
'test/code-fixtures/projects/dep-test-app/folder-a/SomeGenericFile.js', // This file is real and should be included.
'test/code-fixtures/projects/dep-test-app/folder-b/AnotherGenericFile.js' // This file is real, but matches the negative glob and should be excluded.
];
const testRuleManager: UnpackTargetsDRM = new UnpackTargetsDRM();
await testRuleManager.init();
// THIS IS THE INVOCATION OF THE TARGET METHOD!
const results: RuleTarget[] = await testRuleManager.unpackTargets(engine, targets, new Set());
// Validate the results.
expect(results.length).to.equal(1, 'Wrong number of targets matched');
expect(results[0].target).to.equal(targets[1], 'Wrong file matched');
expect(results[0].isDirectory).to.not.equal(true, 'Should not be flagged as directory');
expect(results[0].paths.length).to.equal(1, 'Wrong number of paths matched');
});
it('Negative globs properly interact with directory targets', async () => {
// All of the tests will use the RetireJS engine, since it's got the most straightforward inclusion/exclusion rules.
const engine = new RetireJsEngine();
await engine.init();
// Targets are all going to be normalized to Unix paths.
const targets = [
'!**/*Static*', // Negative Glob #1
'!**/*3.5.1.js', // Negative Glob #2
'test/code-fixtures/projects/dep-test-app/folder-a', // This real directory should be included since no files match negative globs.
'test/code-fixtures/projects/dep-test-app/folder-b', // This real directory should be included since only some files match negative globs.
'test/code-fixtures/projects/dep-test-app/folder-e' // This real directory should be excluded since all files match negative globs.
];
const testRuleManager: UnpackTargetsDRM = new UnpackTargetsDRM();
await testRuleManager.init();
// THIS IS THE INVOCATION OF THE TARGET METHOD!
const results: RuleTarget[] = await testRuleManager.unpackTargets(engine, targets, new Set());
// Validate the results.
expect(results.length).to.equal(2, 'Wrong number of targets matched');
expect(results[0].target).to.equal(targets[2], 'Wrong directory matched');
expect(results[0].isDirectory).to.equal(true, 'Should be flagged as directory');
expect(results[0].paths.length).to.equal(2, 'Wrong number of paths matched');
expect(results[1].target).to.equal(targets[3], 'Wrong directory matched');
expect(results[1].isDirectory).to.equal(true, 'Should be flagged as directory');
expect(results[1].paths.length).to.equal(1, 'Wrong number of paths matched');
});
it('Negative globs properly interact with positive glob targets', async () => {
// All of the tests will use the RetireJS engine, since it's got the most straightforward inclusion/exclusion rules.
const engine = new RetireJsEngine();
await engine.init();
// Targets are all going to be normalized to Unix paths.
const targets = [
'!**/*-3.5.1.js', // Negative Glob #1
'!**/folder-e/**', // Negative Glob #2
'test/code-fixtures/projects/dep-test-app/**/*Generic*.js', // This glob should be included since none of its files are excluded by negative globs.
'test/code-fixtures/projects/dep-test-app/**/jquery*.js', // This glob should be included since only some of its files are excluded by negative globs.
'test/code-fixtures/projects/dep-test-app/**/*Static*' // This glob should be excluded since all of its files are excluded by negative globs.
];
const testRuleManager: UnpackTargetsDRM = new UnpackTargetsDRM();
await testRuleManager.init();
// THIS IS THE INVOCATION OF THE TARGET METHOD!
const results: RuleTarget[] = await testRuleManager.unpackTargets(engine, targets, new Set());
// Validate the results.
expect(results.length).to.equal(2, 'Wrong number of targets matched');
expect(results[0].target).to.equal(targets[2], 'Wrong glob matched');
expect(results[0].isDirectory).to.not.equal(true, 'Should not be flagged as directory');
expect(results[0].paths.length).to.equal(2, 'Wrong number of paths matched');
expect(results[1].target).to.equal(targets[3], 'Wrong glob matched');
expect(results[1].isDirectory).to.not.equal(true, 'Should not be flagged as directory');
expect(results[1].paths.length).to.equal(1, 'Wrong number of paths matched');
});
});
});
}); | the_stack |
import Component from 'vue-class-component';
import Vue from 'vue';
import { log, getLogger } from "extraterm-logging";
import { KeybindingsKeyInput, EVENT_SELECTED, EVENT_CANCELED } from './KeyInputUi';
import { KeybindingsSet, KeybindingsBinding, CustomKeybindingsSet, CustomKeybinding } from '../../../keybindings/KeybindingsTypes';
import { TermKeyStroke } from '../../keybindings/KeyBindingsManager';
import { Emulator, Platform } from '../../emulator/Term';
import { trimBetweenTags } from 'extraterm-trim-between-tags';
import { Category, ExtensionCommandContribution } from '../../../ExtensionMetadata';
export const EVENT_START_KEY_INPUT = "start-key-input";
export const EVENT_END_KEY_INPUT = "end-key-input";
type KeybindingsKeyInputState = "read" | "edit" | "conflict" | "revert_conflict";
interface CommandKeybindingInfo {
command: string;
commandTitle: string;
baseKeybindingsList: string[];
baseKeyStrokeList: TermKeyStroke[];
customKeybinding: CustomKeybinding | null;
customKeyStrokeList: TermKeyStroke[] | null;
}
const _log = getLogger("KeybindingsCategoryUi");
@Component({
components: {
"keybindings-key-input": KeybindingsKeyInput
},
props: {
category: String,
categoryName: String,
baseKeybindingsSet: Object, // KeybindingsSet,
customKeybindingsSet: Object, // CustomKeybindingsSet
commands: Array, // ExtensionCommandContribution[]
searchText: String,
},
watch: {
keybindings: {
deep: true,
handler: () => {},
}
},
template: trimBetweenTags(`
<div>
<h3>{{categoryName}}
<span v-if="commands.length !== filteredCommands.length" class="badge">{{filteredCommands.length}} / {{commands.length}}</span>
</h3>
<table v-if="filteredCommands.length !== 0" class="width-100pc table-hover">
<thead>
<tr>
<th width="50%">Command</th>
<th width="50%">Key</th>
</tr>
</thead>
<tbody>
<tr v-for="command in filteredCommands" v-bind:key="command.command" class="command-row">
<td :title="'Command code: ' + command.command">{{command.title}}</td>
<td class="keybindings-key-colomn">
<button
v-if="hasCommandCustomKeystrokes(command.command)"
class="microtool warning"
:title="revertWarningText(command.command)"
v-on:click="revertKeys(command.command)"
>
<i class="fas fa-undo"></i>
</button>
<template v-for="(keybinding, index) in getKeystrokesForCommand(command.command)">
<br v-if="index !== 0" />
<div class="keycap">
<span>{{keybinding.formatHumanReadable()}}</span>
</div>
<i
v-if="termConflict(keybinding)"
title="This may override the terminal emulation"
class="fas fa-exclamation-triangle"
></i>
<button
v-on:click="deleteKey(command.command, keybinding)"
class="microtool danger hover"
title="Remove keybinding"
>
<i class="fas fa-times"></i>
</button>
</template>
<button
v-if="! (command.command === selectedCommand && inputState !== 'read')"
v-on:click="addKey(command.command)"
class="microtool success hover"
title="Add keybinding"
>
<i class="fas fa-plus"></i>
</button>
<keybindings-key-input
v-if="command.command === selectedCommand && inputState === 'edit'"
v-on:${EVENT_SELECTED}="onKeyInputSelected"
v-on:${EVENT_CANCELED}="onKeyInputCancelled">
</keybindings-key-input>
<template v-if="command.command === selectedCommand && ['conflict', 'revert_conflict'].includes(inputState)">
<br v-if="getKeystrokesForCommand(command.command).length !== 0"/>
<div class="keycap">
<span>{{conflictKeyHumanReadable}}</span>
</div>
conflicts with command "{{conflictCommandName}}".
<button title="Replace" class="inline" v-on:click="onReplaceConflict">Replace</button>
<button title="Cancel" class="inline" v-on:click="onCancelConflict">Cancel</button>
</template>
</td>
</tr>
</tbody>
</table>
</div>`),
})
export class KeybindingsCategory extends Vue {
// Props
category: Category;
categoryName: string;
baseKeybindingsSet: KeybindingsSet;
customKeybindingsSet: CustomKeybindingsSet;
searchText: string;
commands: ExtensionCommandContribution[];
inputState: KeybindingsKeyInputState = "read";
selectedCommand = "";
conflictKey = "";
conflictCommand = "";
conflictCommandName = "";
get filteredCommands(): ExtensionCommandContribution[] {
const commands = this.commands;
if (this.searchText.trim() !== "") {
const searchString = this.searchText.toLowerCase().trim();
const filteredCommands = commands.filter((commandContribution): boolean => {
if (commandContribution.title.toLowerCase().indexOf(searchString) !== -1) {
return true;
}
const commandToKeybindingsMapping = this.commandToKeybindingsMapping;
// Also match the search string against the current bindings for the command.
if ( ! commandToKeybindingsMapping.has(commandContribution.command)) {
return false;
}
const keybindingInfo = commandToKeybindingsMapping.get(commandContribution.command);
const keyStrokeList = keybindingInfo.customKeyStrokeList == null
? keybindingInfo.baseKeyStrokeList
: keybindingInfo.customKeyStrokeList;
for (const keybinding of keyStrokeList) {
if (keybinding.formatHumanReadable().toLowerCase().indexOf(searchString) !== -1) {
return true;
}
}
return false;
});
return filteredCommands;
} else {
return commands;
}
}
get commandToKeybindingsMapping(): Map<string, CommandKeybindingInfo> {
const result = new Map<string, CommandKeybindingInfo>();
for (const commandContribution of this.commands) {
if (commandContribution.category === this.category) {
result.set(commandContribution.command, {
command: commandContribution.command,
commandTitle: commandContribution.title,
baseKeybindingsList: [],
baseKeyStrokeList: [],
customKeybinding: null,
customKeyStrokeList: null
});
}
}
for (const keybinding of this.baseKeybindingsSet.bindings) {
const commandKeybindingsInfo = result.get(keybinding.command);
if (commandKeybindingsInfo != null) {
commandKeybindingsInfo.baseKeybindingsList = keybinding.keys;
commandKeybindingsInfo.baseKeyStrokeList = keybinding.keys.map(TermKeyStroke.parseConfigString);
}
}
for (const customKeybinding of this.customKeybindingsSet.customBindings) {
const commandKeybindingInfo = result.get(customKeybinding.command);
if (commandKeybindingInfo != null) {
commandKeybindingInfo.customKeybinding = customKeybinding;
commandKeybindingInfo.customKeyStrokeList = customKeybinding.keys.map(TermKeyStroke.parseConfigString);
}
}
return result;
}
getKeystrokesForCommand(command: string): TermKeyStroke[] {
const info = this.commandToKeybindingsMapping.get(command);
return info.customKeyStrokeList == null ? info.baseKeyStrokeList : info.customKeyStrokeList;
}
hasCommandCustomKeystrokes(command: string): boolean {
const info = this.commandToKeybindingsMapping.get(command);
if (info == null) {
_log.warn(`hasCommandCustomKeystrokes() Unknown command '${command}'`);
return false;
}
return info.customKeyStrokeList != null;
}
termConflict(keybinding: TermKeyStroke): boolean {
if (["application", "window", "terminal", "viewer"].indexOf(this.category) === -1) {
return false;
}
return Emulator.isKeySupported(<Platform> process.platform, keybinding);
}
deleteKey(command: string, keyStroke: TermKeyStroke): void {
const commandKeybindingInfo = this.commandToKeybindingsMapping.get(command);
if (commandKeybindingInfo.customKeyStrokeList == null) {
const newKeybinding: CustomKeybinding = {
command,
keys: commandKeybindingInfo.baseKeybindingsList.filter(
keybinding=> ! TermKeyStroke.parseConfigString(keybinding).equals(keyStroke))
};
Vue.set(this.customKeybindingsSet, "customBindings", [...this.customKeybindingsSet.customBindings, newKeybinding]);
} else {
const newKeyStrokes = commandKeybindingInfo.customKeybinding.keys.filter(
keybinding=> ! TermKeyStroke.parseConfigString(keybinding).equals(keyStroke));
Vue.set(commandKeybindingInfo.customKeybinding, "keys", newKeyStrokes);
}
}
addKey(command: string): void {
this.inputState = "edit";
this.selectedCommand = command;
this.$emit(EVENT_START_KEY_INPUT);
}
revertWarningText(command: string): string {
const info = this.commandToKeybindingsMapping.get(command);
if (info == null) {
return "Revert to default";
}
return `Revert to default: ${info.baseKeyStrokeList.map(ks => ks.formatHumanReadable()).join(", ")}`;
}
revertKeys(command: string): void {
const commandKeybindingInfo = this.commandToKeybindingsMapping.get(command);
if (commandKeybindingInfo.baseKeybindingsList.length !== 0) {
const keyStrokeString = commandKeybindingInfo.baseKeybindingsList[0];
const conflictingKeybindingCommand = this._findCommandByKeyStrokeString(keyStrokeString);
if (conflictingKeybindingCommand != null && conflictingKeybindingCommand !== command) {
this.selectedCommand = command;
this.conflictKey = keyStrokeString;
this.conflictCommand = conflictingKeybindingCommand;
this.conflictCommandName = this.commandToKeybindingsMapping.get(conflictingKeybindingCommand).commandTitle;
this.inputState = "revert_conflict";
return;
}
}
Vue.set(this.customKeybindingsSet, "customBindings",
this.customKeybindingsSet.customBindings.filter(ck => ck.command !== command));
}
private _findCommandByKeyStrokeString(keyStrokeStroke: string): string {
const keyStroke = TermKeyStroke.parseConfigString(keyStrokeStroke);
const commandToKeybindingsMapping = this.commandToKeybindingsMapping;
for (const key of commandToKeybindingsMapping.keys()) {
const info = commandToKeybindingsMapping.get(key);
if (info.customKeyStrokeList == null) {
if (info.baseKeyStrokeList.some(value => value.equals(keyStroke))) {
return info.command;
}
} else {
if (info.customKeyStrokeList.some(value => value.equals(keyStroke))) {
return info.command;
}
}
}
return null;
}
onKeyInputSelected(keyStrokeString: string): void {
const conflictingKeybindingCommand = this._findCommandByKeyStrokeString(keyStrokeString);
if (conflictingKeybindingCommand == null) {
this._addKeyStrokeToCommandNoConflict(this.selectedCommand, keyStrokeString);
this.inputState = "read";
} else {
this.conflictKey = keyStrokeString;
this.conflictCommand = conflictingKeybindingCommand;
this.conflictCommandName = this.commandToKeybindingsMapping.get(conflictingKeybindingCommand).commandTitle;
this.inputState = "conflict";
}
this.$emit(EVENT_END_KEY_INPUT);
}
private _addKeyStrokeToCommandNoConflict(command: string, keyStrokeString: string): void {
const commandKeybindingInfo = this.commandToKeybindingsMapping.get(command);
if (commandKeybindingInfo.customKeybinding == null) {
const newKeybinding: CustomKeybinding = {
command,
keys: [...commandKeybindingInfo.baseKeybindingsList, keyStrokeString]
};
Vue.set(this.customKeybindingsSet, "customBindings", [...this.customKeybindingsSet.customBindings, newKeybinding]);
} else {
const newKeyStrokes = [...commandKeybindingInfo.customKeybinding.keys, keyStrokeString];
Vue.set(commandKeybindingInfo.customKeybinding, "keys", newKeyStrokes);
}
}
onKeyInputCancelled(): void {
this.inputState = "read";
this.$emit(EVENT_END_KEY_INPUT);
}
get conflictKeyHumanReadable(): string {
return TermKeyStroke.parseConfigString(this.conflictKey).formatHumanReadable();
}
onReplaceConflict(): void {
this.deleteKey(this.conflictCommand, TermKeyStroke.parseConfigString(this.conflictKey));
if (this.inputState === 'conflict') {
this._addKeyStrokeToCommandNoConflict(this.selectedCommand, this.conflictKey);
} else {
// revert_conflict
Vue.set(this.customKeybindingsSet, "customBindings",
this.customKeybindingsSet.customBindings.filter(ck => ck.command !== this.selectedCommand));
}
this.selectedCommand = "";
this.conflictKey = "";
this.inputState = "read";
}
onCancelConflict(): void {
this.selectedCommand = "";
this.conflictKey = "";
this.inputState = "read";
}
} | the_stack |
let native: any
/**
* @ignore
*/
export function setNative(newNative: any) {
native = newNative
}
/**
* This identifies the task a model performs.
*/
export enum Task {
Regression = "regression",
BinaryClassification = "binary_classification",
MulticlassClassification = "multiclass_classification",
}
/**
* These are the options passed to the constructor of the [[`Model`]] class.
*/
export type LoadModelOptions = {
/**
* If you are running the app locally or on your own server, use this field to provide a url that points to it. If not specified, the default value is https://app.tangram.dev.
*/
tangramUrl?: string
}
/**
* This is the input type of [[`Model.predict`]]. A predict input is an object whose keys are the same as the column names in the CSV the model was trained with, and whose values match the type for each column.
*/
export type PredictInput = {
[key: string]: string | number | null | undefined
}
/**
* These are the options passed to [[`Model.predict`]].
*/
export type PredictOptions = {
/**
* If your model is a binary classifier, use this field to make predictions using a threshold chosen on the tuning page of the app. The default value is `0.5`.
*/
threshold?: number
/**
* Computing feature contributions is disabled by default. If you set this field to `true`, you will be able to access the feature contributions with the `featureContributions` field of the predict output.
*/
computeFeatureContributions?: boolean
}
/**
* This is the output of `predict`. You can use the `task` field to determine which variant it is.
*/
export type PredictOutput<TaskType extends Task> = {
[Task.Regression]: RegressionPredictOutput
[Task.BinaryClassification]: BinaryClassificationPredictOutput
[Task.MulticlassClassification]: MulticlassClassificationPredictOutput
}[TaskType]
/**
* This is the output of calling [[`Model.predict`]] on a [[`Model`]] whose [[`Task`]] is [[`Task.Regression`]].
*/
export type RegressionPredictOutput = {
type: Task.Regression
/**
* This is the predicted value.
*/
value: number
/**
* If computing feature contributions was enabled in the predict options, this value will explain the model's output, showing how much each feature contributed to the output.
*/
featureContributions?: FeatureContributions
}
/**
* This is the output of calling [[`Model.predict`]] on a `Model` whose `Task` is `Task.BinaryClassification`.
*/
export type BinaryClassificationPredictOutput<Classes = string> = {
type: Task.BinaryClassification
/**
* This is the name of the predicted class.
*/
className: Classes
/**
* This is the probability the model assigned to the predicted class.
*/
probability: number
/**
* If computing feature contributions was enabled in the predict options, this value will explain the model's output, showing how much each feature contributed to the output.
*/
featureContributions?: FeatureContributions
}
/**
* This is the output of calling [[`Model.predict`]] on a `Model` whose `Task` is `Task.MulticlassClassification`.
*/
export type MulticlassClassificationPredictOutput<Classes = string> = {
type: Task.MulticlassClassification
/**
* This is the name of the predicted class.
*/
className: Classes
/**
* This is the probability the model assigned to the predicted class.
*/
probability: number
/**
* This value maps from class names to the probability the model assigned to each class.
*/
probabilities: { [K in keyof Classes]: number }
/**
* If computing feature contributions was enabled in the predict options, this value will explain the model's output, showing how much each feature contributed to the output. This value maps from class names to `FeatureContributions` values for each class. The class with the `FeatureContributions` value with the highest `outputValue` is the predicted class.
*/
featureContributions?: { [K in keyof Classes]: FeatureContributions }
}
/**
* This is a description of the feature contributions for the prediction if the task is regression or binary classification, or for a single class if the task is multiclass classification.
*/
export type FeatureContributions = {
/**
* This is the value the model would output if all features had baseline values.
*/
baselineValue: number
/**
* This is the value the model output. Any difference from the `baselineValue` is because of the deviation of the features from their baseline values.
*/
outputValue: number
/**
* This array will contain one entry for each of the model's features. Note that features are computed from columns, so there will likely be more features than columns.
*/
entries: Array<FeatureContributionEntry>
}
export type FeatureContributionEntry =
| IdentityFeatureContribution
| NormalizedFeatureContribution
| OneHotEncodedFeatureContribution
| BagOfWordsFeatureContribution
| BagOfWordsCosineSimilarityFeatureContribution
| WordEmbeddingFeatureContribution
/**
* This identifies the type of a feature contribution.
*/
export enum FeatureContributionType {
Identity = "identity",
Normalized = "normalized",
OneHotEncoded = "one_hot_encoded",
BagOfWords = "bag_of_words",
BagOfWordsCosineSimilarity = "bag_of_words_cosine_similarity",
WordEmbedding = "word_embedding",
}
/**
* This describes the contribution of a feature from an identity feature group.
*/
export type IdentityFeatureContribution = {
type: FeatureContributionType.Identity
/**
* This is the name of the source column for the feature group.
*/
columnName: string
/**
* This is the value of the feature.
*/
featureValue: number
/**
* This is the amount that the feature contributed to the output.
*/
featureContributionValue: number
}
/**
* This describes the contribution of a feature from a normalized feature group.
*/
export type NormalizedFeatureContribution = {
type: FeatureContributionType.Normalized
/**
* This is the name of the source column for the feature group.
*/
columnName: string
/**
* This is the value of the feature.
*/
featureValue: number
/**
* This is the amount that the feature contributed to the output.
*/
featureContributionValue: number
}
/**
* This describes the contribution of a feature from a one hot encoded feature group.
*/
export type OneHotEncodedFeatureContribution = {
type: FeatureContributionType.OneHotEncoded
/**
* This is the name of the source column for the feature group.
*/
columnName: string
/**
* This is the enum variant the feature indicates the presence of.
*/
variant: string | null
/**
* This is the value of the feature.
*/
featureValue: number
/**
* This is the amount that the feature contributed to the output.
*/
featureContributionValue: number
}
/**
* This describes the contribution of a feature from a bag of words feature group.
*/
export type BagOfWordsFeatureContribution = {
type: FeatureContributionType.BagOfWords
/**
* This is the name of the source column for the feature group.
*/
columnName: string
/**
* This is the ngram for the feature.
*/
nGram: NGram
/**
* This is the value of the feature.
*/
featureValue: number
/**
* This is the amount that the feature contributed to the output.
*/
featureContributionValue: number
}
/**
* This is a sequence of `n` tokens. Tangram currently supports unigrams and bigrams.
*/
export type NGram = string | [string, string]
/**
* This describes the contribution of a feature from a bag of words feature group.
*/
export type BagOfWordsCosineSimilarityFeatureContribution = {
type: FeatureContributionType.BagOfWordsCosineSimilarity
/**
* This is the name of the source column a for the feature group.
*/
columnNameA: string
/**
* This is the name of the source column b for the feature group.
*/
columnNameB: string
/**
* This is the value of the feature.
*/
featureValue: number
/**
* This is the amount that the feature contributed to the output.
*/
featureContributionValue: number
}
/**
* This describes the contribution of a feature from a word vector feature group.
*/
export type WordEmbeddingFeatureContribution = {
type: FeatureContributionType.WordEmbedding
/**
* This is the name of the source column for the feature group.
*/
columnName: string
/**
* This is the index of the feature in the word embedding.
*/
valueIndex: string
/**
* This is the amount that the feature contributed to the output.
*/
featureContributionValue: number
}
/**
* This is the type of the argument to [[`Model.logPrediction`]] and [[`Model.enqueueLogPrediction`]] which specifies the details of the prediction to log.
*/
export type LogPredictionArgs<
TaskType extends Task,
InputType extends PredictInput,
> = {
/**
* This is a unique identifier for the prediction, which will associate it with a true value event and allow you to look it up in the app.
*/
identifier?: string
/**
* This is the same `PredictInput` value that you passed to [[`Model.predict`]].
*/
input: InputType
/**
* This is the same `PredictOptions` value that you passed to [[`Model.predict`]].
*/
options?: PredictOptions
/**
* This is the output returned by [[`Model.predict`]].
*/
output: PredictOutput<TaskType>
}
/**
* This is the type of the argument to `logTrueValue` and `enqueueLogTrueValue` which specifies the details of the true value to log.
*/
export type LogTrueValueArgs = {
/**
* This is a unique identifier for the true value, which will associate it with a prediction event and allow you to look it up in the app.
*/
identifier: string
/**
* This is the true value for the prediction.
*/
trueValue: number | string
}
type Event<TaskType extends Task, InputType extends PredictInput> =
| PredictionEvent<TaskType, InputType>
| TrueValueEvent
type PredictionEvent<TaskType extends Task, InputType extends PredictInput> = {
date: String
identifier?: number | string
input: InputType
modelId: string
options?: PredictOptions
output: PredictOutput<TaskType>
type: "prediction"
}
type TrueValueEvent = {
date: String
identifier: number | string
modelId: string
trueValue: number | string
type: "true_value"
}
/**
* Use this class to load a model, make predictions, and log events to the app.
*/
export class Model<
TaskType extends Task,
InputType extends PredictInput,
OutputType extends PredictOutput<TaskType>,
> {
private model: unknown
private tangramUrl: string
private logQueue: Event<TaskType, InputType>[] = []
/**
* Load a model from the `.tangram` file at `path`. This only works in Node.js. In other JavaScript environments, you should use the constructor with an `ArrayBuffer`.
* @param path The path to the `.tangram` file.
* @param options The options to use when loading the model.
*/
constructor(path: string, options?: LoadModelOptions)
/**
* Load a model from the contents of a `.tangram` file as an `ArrayBuffer`.
* @param data
* @param options
*/
constructor(data: ArrayBuffer, options?: LoadModelOptions)
constructor(input: string | ArrayBuffer, options?: LoadModelOptions) {
if (typeof input === "string") {
this.model = native.loadModelFromPath(input)
} else {
this.model = native.loadModelFromArrayBuffer(input)
}
this.tangramUrl = options?.tangramUrl ?? "https://app.tangram.dev"
}
/**
* Retrieve the model's id.
* @returns The model's id.
*/
public id(): string {
return native.modelId(this.model)
}
/**
* Make a prediction!
* @param input The input to the prediction, either a single `PredictInput` or an array of `PredictInput`s.
* @param options An optional [[`PredictOptions`]] value to set options for the prediction.
* @returns A single [[`PredictOutput`]] if `input` was a single [[`PredictInput`]], or an array of [[`PredictOutput`]]s if `input` was an array of [[`PredictInput`]]s.
*/
public predict<PredictInput extends InputType | InputType[]>(
input: PredictInput,
options?: PredictOptions,
): PredictInput extends InputType[] ? OutputType[] : OutputType {
return native.predict(this.model, input, options)
}
/**
* Send a prediction event to the app. If you want to batch events, you can use [[`Model.enqueueLogTrueValue`]] instead.
* @param args The arguments to use to produce the prediction event.
*/
public async logPrediction(
args: LogPredictionArgs<TaskType, InputType>,
): Promise<void> {
this.logEvent(this.predictionEvent(args))
}
/**
* Send a true value event to the app. If you want to batch events, you can use [[`Model.enqueueLogTrueValue`]] instead.
* @param args The arguments to use to produce the true value event.
*/
public async logTrueValue(args: LogTrueValueArgs): Promise<void> {
this.logEvent(this.trueValueEvent(args))
}
/**
* Add a prediction event to the queue. Remember to call [[`Model.flushLogQueue`]] at a later point to send the event to the app.
* @param args The arguments to use to produce the prediction event.
*/
public enqueueLogPrediction(args: LogPredictionArgs<TaskType, InputType>) {
this.logQueue.push(this.predictionEvent(args))
}
/**
* Add a true value event to the queue. Remember to call [[`Model.flushLogQueue`]] at a later point to send the event to the app.
* @param args The arguments to use to produce the true value event.
*/
public enqueueLogTrueValue(args: LogTrueValueArgs) {
this.logQueue.push(this.trueValueEvent(args))
}
/**
* Send all events in the queue to the app.
*/
public async flushLogQueue(): Promise<void> {
await this.logEvents(this.logQueue)
this.logQueue = []
}
private async logEvent(event: Event<TaskType, InputType>): Promise<void> {
await this.logEvents([event])
}
private async logEvents(events: Event<TaskType, InputType>[]): Promise<void> {
let url = this.tangramUrl + "/track"
let body = JSON.stringify(events)
if (typeof fetch === "undefined") {
throw Error("Tangram cannot find the fetch function.")
}
let response = await fetch(url, {
body,
headers: {
"Content-Type": "application/json",
},
method: "POST",
})
if (!response.ok) {
throw Error(await response.text())
}
}
private predictionEvent(
args: LogPredictionArgs<TaskType, InputType>,
): PredictionEvent<TaskType, InputType> {
return {
modelId: this.id(),
type: "prediction" as const,
date: new Date().toISOString(),
identifier: args.identifier,
input: args.input,
output: {
...args.output,
featureContributions: null,
},
options: args.options,
}
}
private trueValueEvent(args: LogTrueValueArgs): TrueValueEvent {
return {
modelId: this.id(),
type: "true_value" as const,
date: new Date().toISOString(),
identifier: args.identifier,
trueValue: args.trueValue,
}
}
} | the_stack |
export as namespace intlTelInput;
export = intlTelInput;
/**
* initialise the plugin with optional options.
* @param options options that can be provided during initialization.
*/
declare function intlTelInput(node: Element, options?: intlTelInput.Options): intlTelInput.Plugin;
declare namespace intlTelInput {
interface Static {
/**
* Default options for all instances
*/
defaults: Options;
/**
* Get all of the plugin's country data - either to re-use elsewhere
* e.g. to populate a country dropdown.
*/
getCountryData(): CountryData[];
/**
* Load the utils.js script (included in the lib directory) to enable
* formatting/validation etc.
*/
loadUtils(path: string, utilsScriptDeferred?: boolean): void;
/**
* After initialising the plugin, you can always access the instance again using this method,
* by just passing in the relevant input element.
*/
getInstance(node: Element): Plugin;
}
interface Plugin {
promise: Promise<void>;
/**
* Remove the plugin from the input, and unbind any event listeners.
*/
destroy(): void;
/**
* Get the extension from the current number.
* Requires the utilsScript option.
* e.g. if the input value was "(702) 555-5555 ext. 1234", this would
* return "1234".
*/
getExtension(): string;
/**
* Get the current number in the given format (defaults to E.164 standard).
* The different formats are available in the enum
* intlTelInputUtils.numberFormat - taken from here.
* Requires the utilsScript option.
* Note that even if nationalMode is enabled, this can still return a full
* international number.
* @param numberFormat the format in which the number will be returned.
*/
getNumber(numberFormat?: intlTelInputUtils.numberFormat): string;
/**
* Get the type (fixed-line/mobile/toll-free etc) of the current number.
* Requires the utilsScript option.
* Returns an integer, which you can match against the various options in the
* global enum intlTelInputUtils.numberType.
* Note that in the US there's no way to differentiate between fixed-line and
* mobile numbers, so instead it will return FIXED_LINE_OR_MOBILE.
*/
getNumberType(): intlTelInputUtils.numberType;
/**
* Get the country data for the currently selected flag.
*/
getSelectedCountryData(): CountryData;
/**
* Get more information about a validation error.
* Requires the utilsScript option.
* Returns an integer, which you can match against the various options in the
* global enum ValidationError
*/
getValidationError(): intlTelInputUtils.validationError;
/**
* Validate the current number. Expects an internationally formatted number
* (unless nationalMode is enabled). If validation fails, you can use
* getValidationError to get more information.
* Requires the utilsScript option.
* Also see getNumberType if you want to make sure the user enters a certain
* type of number e.g. a mobile number.
*/
isValidNumber(): boolean;
/**
* Change the country selection (e.g. when the user is entering their address).
* @param countryCode country code of the country to be set.
*/
setCountry(countryCode: string): void;
/**
* Insert a number, and update the selected flag accordingly.
* Note that by default, if nationalMode is enabled it will try to use
* national formatting.
* @param aNumber number to be set.
*/
setNumber(aNumber: string): void;
/**
* Set the type of the placeholder number
* @param type Placeholder number type to be set
*/
setPlaceholderNumberType(type: placeholderNumberType): void;
}
interface Options {
/**
* Whether or not to allow the dropdown. If disabled, there is no dropdown
* arrow, and the selected flag is not clickable. Also we display the
* selected flag on the right instead because it is just a marker of state.
* Default = true
*/
allowDropdown?: boolean | undefined;
/**
* If there is just a dial code in the input: remove it on blur or submit,
* and re-add it on focus. This is to prevent just a dial code getting
* submitted with the form. Requires nationalMode to be set to false.
* Default = true
*/
autoHideDialCode?: boolean | undefined;
/**
* Set the input's placeholder to an example number for the selected country, and update it if the country changes.
* You can specify the number type using the placeholderNumberType option.
* By default it is set to "polite", which means it will only set the placeholder if the input doesn't already have one.
* You can also set it to "aggressive", which will replace any existing placeholder, or "off".
* Requires the utilsScript option.
* Default = "polite"
*/
autoPlaceholder?: 'off' | 'polite' | 'aggressive' | undefined;
/**
* Change the placeholder generated by autoPlaceholder. Must return a string.
* Default = null
*/
customPlaceholder?: ((selectedCountryPlaceholder: string, selectedCountryData: CountryData) => string) | undefined;
/**
* Additional classes to add to the parent div..
* @default ''
*/
customContainer?: string | undefined;
/**
* Expects a node e.g. document.body. Instead of putting the country dropdown next to the input,
* append it to the specified node, and it will then be positioned absolutely next to the input using JavaScript.
* This is useful when the input is inside a container with overflow: hidden.
* Note that the absolute positioning can be broken by scrolling, so it will automatically close on the window scroll event.
* Default = null
*/
dropdownContainer?: Node | undefined;
/**
* In the dropdown, display all countries except the ones you specify here.
* Default = null
*/
excludeCountries?: string[] | undefined;
/**
* Format the input value (according to the nationalMode option) during initialisation, and on setNumber.
* Requires the utilsScript option.
* Default = true
*/
formatOnDisplay?: boolean | undefined;
/**
* When setting initialCountry to "auto", you must use this option to
* specify a custom function that looks up the user's location,
* and then calls the success callback with the relevant country code.
* Also note that when instantiating the plugin, if the Promise object is defined,
* one of those is returned under the promise instance property, so you can
* do something like iti.promise.then(callback) to know when initialisation requests like this have completed.
* Default = null
*/
geoIpLookup?: ((callback: (countryCode: string) => void) => void) | undefined;
/**
* Add a hidden input with the given name (or if your input name contains square brackets then it will give the hidden input the same name,
* replacing the contents of the brackets with the given name). On submit, populate it with the full international number (using getNumber).
* This is a quick way for people using non-ajax forms to get the full international number, even when nationalMode is enabled.
* Note: requires the input to be inside a form element, as this feature works by listening for the submit event on the closest form element.
* Also note that since this uses getNumber internally, it expects a valid number, and so should only be used after validation.
* Default = ""
*/
hiddenInput?: string | undefined;
/**
* Set the initial country selection by specifying it's country code.
* You can also set it to "auto", which will lookup the user's country based
* on their IP address (requires the geoIpLookup option).
* Note that the "auto" option will not update the country selection if the
* input already contains a number. If you leave initialCountry blank,
* it will default to the first country in the list.
*/
initialCountry?: string | undefined;
/**
* Allows to translate the countries by its given iso code e.g.: { 'de': 'Deutschland' }
* Default = {}
*/
localizedCountries?: object | undefined;
/**
* Allow users to enter national numbers (and not have to think about
* international dial codes). Formatting, validation and placeholders still
* work. Then you can use getNumber to extract a full international number.
* This option now defaults to true, and it is recommended that you leave it
* that way as it provides a better experience for the user.
* Default = true
*/
nationalMode?: boolean | undefined;
/**
* In the dropdown, display only the countries you specify.
* Default = undefined
*/
onlyCountries?: string[] | undefined;
/**
* Specify one of the keys from the global enum intlTelInputUtils.numberType
* e.g. "FIXED_LINE" to set the number type to use for the placeholder.
* Default = MOBILE
*/
placeholderNumberType?: placeholderNumberType | undefined;
/**
* Specify the countries to appear at the top of the list.
* Default = ["us", "gb"]
*/
preferredCountries?: string[] | undefined;
/**
* Display the country dial code next to the selected flag so it's not part
* of the typed number. Note that this will disable nationalMode because
* technically we are dealing with international numbers, but with the
* dial code separated.
* Default = false
*/
separateDialCode?: boolean | undefined;
/**
* Enable formatting/validation etc. by specifying the URL of the included utils.js script
* (or alternatively just point it to the file on cdnjs.com). The script is fetched when the page has finished loading (on the window load event)
* to prevent blocking (the script is ~215KB). When instantiating the plugin, if the Promise object is defined,
* one of those is returned under the promise instance property, so you can do something like
* iti.promise.then(callback) to know when initialisation requests like this have finished.
* Note that if you're lazy loading the plugin script itself (intlTelInput.js)
* this will not work and you will need to use the loadUtils method instead.
* Example: "build/js/utils.js"
* Default = ""
*/
utilsScript?: string | undefined;
}
interface CountryData {
name: string;
iso2: string;
dialCode: string;
}
type placeholderNumberType =
| 'FIXED_LINE_OR_MOBILE'
| 'FIXED_LINE'
| 'MOBILE'
| 'PAGER'
| 'PERSONAL_NUMBER'
| 'PREMIUM_RATE'
| 'SHARED_COST'
| 'TOLL_FREE'
| 'UAN'
| 'UNKNOWN'
| 'VOICEMAIL'
| 'VOIP';
}
declare namespace intlTelInputUtils {
enum numberFormat {
E164 = 0,
INTERNATIONAL = 1,
NATIONAL = 2,
RFC3966 = 3,
}
enum numberType {
FIXED_LINE = 0,
MOBILE = 1,
FIXED_LINE_OR_MOBILE = 2,
TOLL_FREE = 3,
PREMIUM_RATE = 4,
SHARED_COST = 5,
VOIP = 6,
PERSONAL_NUMBER = 7,
PAGER = 8,
UAN = 9,
VOICEMAIL = 10,
UNKNOWN = -1,
}
enum validationError {
IS_POSSIBLE = 0,
INVALID_COUNTRY_CODE = 1,
TOO_SHORT = 2,
TOO_LONG = 3,
NOT_A_NUMBER = 4,
}
}
declare global {
namespace intlTelInputUtils {
function formatNumber(number: string, countryCode: string, format: numberFormat): string;
function getExampleNumber(countryCode: string, isNational: boolean, numberType: numberType): string;
function getNumberType(number: string, countryCode: string): numberType;
function getValidationError(number: string, countryCode: string): string;
function isValidNumber(number: string, countryCode: string): string;
enum numberFormat {
E164 = 0,
INTERNATIONAL = 1,
NATIONAL = 2,
RFC3966 = 3,
}
enum numberType {
FIXED_LINE = 0,
MOBILE = 1,
FIXED_LINE_OR_MOBILE = 2,
TOLL_FREE = 3,
PREMIUM_RATE = 4,
SHARED_COST = 5,
VOIP = 6,
PERSONAL_NUMBER = 7,
PAGER = 8,
UAN = 9,
VOICEMAIL = 10,
UNKNOWN = -1,
}
enum validationError {
IS_POSSIBLE = 0,
INVALID_COUNTRY_CODE = 1,
TOO_SHORT = 2,
TOO_LONG = 3,
NOT_A_NUMBER = 4,
}
}
interface Window {
intlTelInputGlobals: intlTelInput.Static;
/**
* initialise the plugin with optional options.
* @param options options that can be provided during initialization.
*/
intlTelInput(node: Element, options?: intlTelInput.Options): intlTelInput.Plugin;
}
} | the_stack |
import {
state,
derivedState,
syncedState,
setSyncAdapter,
combinedState,
} from './core'
import { Patch } from 'immer'
test('state.get()', () => {
const s = state({ x: 1 })
expect(s.get()).toStrictEqual({ x: 1 })
})
test('state.get(selector)', () => {
const s = state({ x: 1 })
expect(s.get(s => s.x)).toStrictEqual(1)
})
test('state.set()', () => {
const s = state({ x: 1 })
s.set(s => {
s.x += 1
})
expect(s.get()).toStrictEqual({ x: 2 })
})
test('state.set(partial)', () => {
const s = state({ x: 1, y: 2 })
s.set({ x: 5 })
expect(s.get()).toStrictEqual({ x: 5, y: 2 })
})
test('state.undo()', () => {
const s = state({ x: 1 })
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
s.undo()
expect(s.get()).toStrictEqual({ x: 2 })
s.set(s => {
s.x += 1
})
expect(s.get()).toStrictEqual({ x: 3 })
s.undo()
expect(s.get()).toStrictEqual({ x: 2 })
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
})
test('state.redo()', () => {
const s = state({ x: 1 })
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
expect(s.get()).toStrictEqual({ x: 4 })
s.undo()
expect(s.get()).toStrictEqual({ x: 3 })
s.undo()
expect(s.get()).toStrictEqual({ x: 2 })
s.redo()
expect(s.get()).toStrictEqual({ x: 3 })
s.redo()
expect(s.get()).toStrictEqual({ x: 4 })
})
test('state.transaction()', () => {
const s = state({ x: 1 })
s.transaction(() => {
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
})
s.set(s => {
s.x += 1
})
expect(s.get()).toStrictEqual({ x: 4 })
s.undo()
expect(s.get()).toStrictEqual({ x: 3 })
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
s.redo()
expect(s.get()).toStrictEqual({ x: 3 })
})
test('derivedState.get()', () => {
const s = derivedState(state({ x: 1 }), s => s.x)
expect(s.get()).toStrictEqual(1)
})
test('derivedState.get(selector)', () => {
const s = derivedState(state({ x: 1 }), s => s.x)
expect(s.get(s => s * 100)).toStrictEqual(100)
})
test('doubleDerivedState.get()', () => {
const s = state({ x: 1 })
const s2 = derivedState(s, s => s.x)
const s3 = derivedState(s2, s => s * 100)
expect(s3.get()).toStrictEqual(100)
})
test('syncedState.set()', () => {
const s = syncedState('test', { x: 1 })
let key: string | undefined
let patches: Patch[] | undefined
setSyncAdapter(() => {
return (k, p) => {
key = k
patches = p
}
})
s.set(s => {
s.x = 2
})
expect(s.get()).toStrictEqual({ x: 2 })
expect(key).toBe('test')
expect(patches).toStrictEqual([{ op: 'replace', path: ['x'], value: 2 }])
})
test('syncedState.applyPatches()', () => {
const s = syncedState('test', { x: 1 })
setSyncAdapter(applyPatches => {
applyPatches('test', [{ op: 'replace', path: ['x'], value: 2 }])
return () => {}
})
expect(s.get()).toStrictEqual({ x: 2 })
})
test('syncedState.setState()', () => {
const s = syncedState('test', { x: 1 })
setSyncAdapter((applyPatches, setState) => {
setState('test', { x: 2, y: 3 })
return () => {}
})
expect(s.get()).toStrictEqual({ x: 2, y: 3 })
})
test('syncedState.undo()', () => {
const s = syncedState('test', { x: 1 })
const changes: Array<{ key: string; patches: Patch[] }> = []
setSyncAdapter(() => {
return (key, patches) => {
changes.push({ key, patches })
}
})
s.set(s => {
s.x = 2
})
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
expect(changes.length).toStrictEqual(2)
expect(changes[0].key).toStrictEqual('test')
expect(changes[0].patches).toStrictEqual([
{ op: 'replace', path: ['x'], value: 2 },
])
expect(changes[1].key).toStrictEqual('test')
expect(changes[1].patches).toStrictEqual([
{ op: 'replace', path: ['x'], value: 1 },
])
})
test('combinedState.get()', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
expect(xy.get()).toStrictEqual({ x: { x: 1 }, y: { y: 2 } })
})
test('combinedState.get(selector)', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
expect(xy.get(s => s.x.x)).toStrictEqual(1)
})
test('combinedState.undo().redo()', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
xy.set(({ x, y }) => {
x.x = 10
y.y = 20
})
expect(x.get()).toStrictEqual({ x: 10 })
expect(y.get()).toStrictEqual({ y: 20 })
xy.undo()
expect(x.get()).toStrictEqual({ x: 1 })
expect(y.get()).toStrictEqual({ y: 2 })
xy.redo()
expect(x.get()).toStrictEqual({ x: 10 })
expect(y.get()).toStrictEqual({ y: 20 })
})
test('combinedState({synced, unsynced}).set()', () => {
const x = syncedState('test', { x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
const changes: Array<{ key: string; patches: Patch[] }> = []
setSyncAdapter(() => {
return (key, patches) => {
changes.push({ key, patches })
}
})
xy.set(({ x, y }) => {
x.x = 10
y.y = 20
})
expect(changes.length).toStrictEqual(1)
expect(changes[0].key).toStrictEqual('test')
expect(changes[0].patches).toStrictEqual([
{ op: 'replace', path: ['x'], value: 10 },
])
})
test('combinedState.transaction()', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
xy.transaction(() => {
xy.set(({ x }) => {
x.x += 1
})
xy.set(({ x }) => {
x.x += 1
})
xy.set(({ y }) => {
y.y += 1
})
})
xy.set(({ y }) => {
y.y += 1
})
expect(x.get()).toStrictEqual({ x: 3 })
expect(y.get()).toStrictEqual({ y: 4 })
xy.undo()
expect(x.get()).toStrictEqual({ x: 3 })
expect(y.get()).toStrictEqual({ y: 3 })
xy.undo()
expect(x.get()).toStrictEqual({ x: 1 })
expect(y.get()).toStrictEqual({ y: 2 })
xy.redo()
expect(x.get()).toStrictEqual({ x: 3 })
expect(y.get()).toStrictEqual({ y: 3 })
})
test('move objects between combined states', () => {
const x = state({ value: { x: 1 } })
const y = state({ values: [{ x: 0 }] })
const xy = combinedState({ x, y })
xy.set(({ x, y }) => {
y.values.push(x.value)
})
expect(x.get()).toStrictEqual({ value: { x: 1 } })
expect(y.get()).toStrictEqual({ values: [{ x: 0 }, { x: 1 }] })
})
test('combined.set()', () => {
const s = combinedState({ a: state({ x: 1 }) })
s.set(s => {
s.a.x += 1
})
expect(s.get()).toStrictEqual({ a: { x: 2 } })
})
test('combined.set(partial)', () => {
const s = combinedState({ a: state({ x: 1 }), b: state({ y: 2 }) })
s.set({ a: { x: 5 } })
expect(s.get()).toStrictEqual({ a: { x: 5 }, b: { y: 2 } })
})
test('derivedState(combinedState).get()', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
const xy2 = derivedState(xy, s => ({
x: s.x.x * 100,
y: s.y.y * 100,
}))
expect(xy2.get()).toStrictEqual({ x: 100, y: 200 })
})
test('derivedState(combinedState).get(selector)', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
const xy2 = derivedState(xy, s => ({
x: s.x.x * 100,
y: s.y.y * 100,
}))
expect(xy2.get(s => s.x)).toStrictEqual(100)
})
test('transaction throws error', () => {
const x = state({ x: 1 })
try {
x.transaction(() => {
x.set(s => {
s.x += 1
})
x.set(s => {
s.x += 1
})
x.set(() => {
throw new Error()
})
})
} catch {
// empty
}
expect(x.get()).toStrictEqual({ x: 1 })
})
test('combined transaction throws error', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
try {
xy.transaction(() => {
xy.set(s => {
s.x.x += 1
})
xy.set(s => {
s.y.y += 1
})
xy.set(() => {
throw new Error()
})
})
} catch {
// empty
}
expect(x.get()).toStrictEqual({ x: 1 })
expect(y.get()).toStrictEqual({ y: 2 })
})
test('syncedState.transaction()', () => {
const x = syncedState('test', { x: 1, y: 1 })
const changes: Array<Patch[]> = []
setSyncAdapter(() => {
return (key, patches) => {
changes.push(patches)
}
})
x.transaction(() => {
x.set(s => {
s.x += 1
})
x.set(s => {
s.y += 2
})
})
expect(x.get()).toStrictEqual({ x: 2, y: 3 })
expect(changes.length).toStrictEqual(1)
expect(changes[0]).toStrictEqual([
{ op: 'replace', path: ['x'], value: 2 },
{ op: 'replace', path: ['y'], value: 3 },
])
})
test('syncedState.transaction() throws', () => {
const x = syncedState('test', { x: 1, y: 1 })
const changes: Array<Patch[]> = []
setSyncAdapter(() => {
return (key, patches) => {
changes.push(patches)
}
})
try {
x.transaction(() => {
x.set(s => {
s.x += 1
})
x.set(s => {
s.y += 2
})
x.set(() => {
throw new Error()
})
})
} catch {
// empty
}
expect(changes.length).toStrictEqual(0)
})
test('subscription notified at end of transaction', () => {
const s = state({ x: 1 })
const notifications = []
s.subscribe(v => {
notifications.push(v)
})
s.transaction(() => {
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
})
s.set(s => {
s.x += 1
})
expect(notifications.length).toStrictEqual(2)
})
test('nested transaction', () => {
const s = state({ x: 1 })
const notifications = []
s.subscribe(v => {
notifications.push(v)
})
s.transaction(() => {
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
s.transaction(() => {
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
})
})
expect(s.get()).toStrictEqual({ x: 5 })
expect(notifications.length).toStrictEqual(1)
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
expect(notifications.length).toStrictEqual(2)
})
test('nested transaction throws', () => {
const s = state({ x: 1 })
s.transaction(() => {
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
try {
s.transaction(() => {
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
s.set(() => {
throw new Error()
})
})
} catch {
// empty
}
})
expect(s.get()).toStrictEqual({ x: 3 })
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
})
test('undo within transaction', () => {
const s = state({ x: 1 })
s.transaction(() => {
s.set(s => {
s.x += 1
})
s.set(s => {
s.x += 1
})
s.undo()
})
expect(s.get()).toStrictEqual({ x: 2 })
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
})
test('subscriptions on combined statex', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
const xnotifications = []
const ynotifications = []
const xynotifications = []
x.subscribe(v => {
xnotifications.push(v)
})
y.subscribe(v => {
ynotifications.push(v)
})
xy.subscribe(v => {
xynotifications.push(v)
})
xy.set(v => {
v.x.x += 1
})
xy.set(v => {
v.y.y += 1
})
expect(xnotifications.length).toStrictEqual(1)
expect(ynotifications.length).toStrictEqual(1)
expect(xynotifications.length).toStrictEqual(2)
})
test('subscriptions on combined state when undo', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
const xnotifications = []
const ynotifications = []
const xynotifications = []
xy.set(v => {
v.x.x += 1
})
xy.set(v => {
v.y.y += 1
})
x.subscribe(v => {
xnotifications.push(v)
})
y.subscribe(v => {
ynotifications.push(v)
})
xy.subscribe(v => {
xynotifications.push(v)
})
xy.undo()
xy.undo()
expect(xnotifications.length).toStrictEqual(1)
expect(ynotifications.length).toStrictEqual(1)
expect(xynotifications.length).toStrictEqual(2)
})
test('subscriptions on combined state when underlying state changes', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
const xnotifications = []
const ynotifications = []
const xynotifications = []
x.subscribe(v => {
xnotifications.push(v)
})
y.subscribe(v => {
ynotifications.push(v)
})
xy.subscribe(v => {
xynotifications.push(v)
})
x.set(v => {
v.x = 1
})
y.set(v => {
v.y = 1
})
expect(xnotifications.length).toStrictEqual(1)
expect(ynotifications.length).toStrictEqual(1)
expect(xynotifications.length).toStrictEqual(2)
})
test('No history should be added if no change is made', () => {
const s = state({ x: 1 })
s.set(() => {})
s.set(() => {})
s.set(s => {
s.x += 1
})
s.set(() => {})
s.set(() => {})
s.undo()
s.undo()
expect(s.get()).toStrictEqual({ x: 1 })
s.redo()
expect(s.get()).toStrictEqual({ x: 2 })
})
test('push empty state should not clear redo stack', () => {
const s = state({ x: 1 })
s.set(s => {
s.x += 1
})
s.undo()
s.set(() => {})
s.redo()
expect(s.get()).toStrictEqual({ x: 2 })
})
test('state.clearHistory()', () => {
const s = state({ x: 1 })
s.set(s => {
s.x += 1
})
s.clearHistory()
s.undo()
expect(s.get()).toStrictEqual({ x: 2 })
})
test('combinedState.clearHistory()', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
xy.set(s => {
s.x.x += 1
})
xy.clearHistory()
xy.undo()
expect(xy.get().x).toStrictEqual({ x: 2 })
})
test('state.set() return value', () => {
const x = state({ x: 1 })
const result = x.set(s => {
s.x += 1
return 'hello'
})
expect(result).toStrictEqual('hello')
})
test('state.set() return value from store', () => {
const x = state({ x: { y: 1 } })
const result = x.set(s => {
s.x.y += 1
return s.x
})
expect(result).toStrictEqual({ y: 2 })
})
test('combinedState.set() return value', () => {
const x = state({ x: 1 })
const y = state({ y: 2 })
const xy = combinedState({ x, y })
const result = xy.set(s => {
s.x.x += 1
return 'hello'
})
expect(result).toStrictEqual('hello')
})
test('Undo transaction after having undone previous transaction', () => {
const x = state({ x: 1 })
function update(s: { x: number }) {
s.x++
}
x.transaction(() => {
x.set(update)
})
x.transaction(() => {
x.set(update)
})
x.undo()
x.transaction(() => {
x.set(update)
x.set(update)
x.set(update)
})
x.undo()
expect(x.get().x).toStrictEqual(2)
}) | the_stack |
import * as _ from 'underscore';
import { Comments } from '../../lib/collections/comments/collection';
import Conversations from '../../lib/collections/conversations/collection';
import Messages from '../../lib/collections/messages/collection';
import { Posts } from "../../lib/collections/posts/collection";
import { Tags } from "../../lib/collections/tags/collection";
import Users from "../../lib/collections/users/collection";
import { userIsAdmin, userCanDo } from '../../lib/vulcan-users/permissions';
import { userTimeSinceLast } from '../../lib/vulcan-users/helpers';
import { DatabasePublicSetting } from "../../lib/publicSettings";
import { performVoteServer } from '../voteServer';
import { updateMutator, createMutator, deleteMutator, Globals } from '../vulcan-lib';
import { recalculateAFCommentMetadata } from './alignment-forum/alignmentCommentCallbacks';
import { newDocumentMaybeTriggerReview } from './postCallbacks';
import { getCollectionHooks } from '../mutationCallbacks';
import { forumTypeSetting } from '../../lib/instanceSettings';
import { ensureIndex } from '../../lib/collectionUtils';
const MINIMUM_APPROVAL_KARMA = 5
let adminTeamUserData = forumTypeSetting.get() === 'EAForum' ?
{
username: "AdminTeam",
email: "forum@effectivealtruism.org"
} :
{
username: "LessWrong",
email: "lesswrong@lesswrong.com"
}
const getLessWrongAccount = async () => {
let account = await Users.findOne({username: adminTeamUserData.username});
if (!account) {
const newAccount = await createMutator({
collection: Users,
document: adminTeamUserData,
validate: false,
})
return newAccount.data
}
return account;
}
// Return the IDs of all ancestors of the given comment (not including the provided
// comment itself).
const getCommentAncestorIds = async (comment: DbComment): Promise<string[]> => {
const ancestorIds: string[] = [];
let currentComment: DbComment|null = comment;
while (currentComment?.parentCommentId) {
currentComment = await Comments.findOne({_id: currentComment.parentCommentId});
if (currentComment)
ancestorIds.push(currentComment._id);
}
return ancestorIds;
}
// Return all comments in a subtree, given its root.
export const getCommentSubtree = async (rootComment: DbComment, projection: any): Promise<any[]> => {
const comments: DbComment[] = [rootComment];
let visited = new Set<string>();
let unvisited: string[] = [rootComment._id];
while(unvisited.length > 0) {
const childComments = await Comments.find({parentCommentId: {$in: unvisited}}, projection).fetch();
for (let commentId of unvisited)
visited.add(commentId);
unvisited = [];
for (let childComment of childComments) {
if (!visited.has(childComment._id)) {
comments.push(childComment);
unvisited.push(childComment._id);
}
}
}
return comments;
}
Globals.getCommentSubtree = getCommentSubtree;
getCollectionHooks("Comments").newValidate.add(async function createShortformPost (comment: DbComment, currentUser: DbUser) {
if (comment.shortform && !comment.postId) {
if (currentUser.shortformFeedId) {
return ({
...comment,
postId: currentUser.shortformFeedId
});
}
const post = await createMutator({
collection: Posts,
document: {
userId: currentUser._id,
shortform: true,
title: `${ currentUser.displayName }'s Shortform`,
af: currentUser.groups?.includes('alignmentForum'),
},
currentUser,
validate: false,
})
await updateMutator({
collection: Users,
documentId: currentUser._id,
set: {
shortformFeedId: post.data._id
},
unset: {},
validate: false,
})
return ({
...comment,
postId: post.data._id
})
}
return comment
});
getCollectionHooks("Comments").newSync.add(async function CommentsNewOperations (comment: DbComment) {
// update lastCommentedAt field on post or tag
if (comment.postId) {
await Posts.rawUpdateOne(comment.postId, {
$set: {lastCommentedAt: new Date()},
});
} else if (comment.tagId) {
await Tags.rawUpdateOne(comment.tagId, {
$set: {lastCommentedAt: new Date()},
});
}
return comment;
});
//////////////////////////////////////////////////////
// comments.remove.async //
//////////////////////////////////////////////////////
getCollectionHooks("Comments").removeAsync.add(async function CommentsRemovePostCommenters (comment: DbComment, currentUser: DbUser) {
const { postId } = comment;
if (postId) {
const postComments = await Comments.find({postId}, {sort: {postedAt: -1}}).fetch();
const lastCommentedAt = postComments[0] && postComments[0].postedAt;
// update post with a decremented comment count, and corresponding last commented at date
await Posts.rawUpdateOne(postId, {
$set: {lastCommentedAt},
});
}
});
getCollectionHooks("Comments").removeAsync.add(async function CommentsRemoveChildrenComments (comment: DbComment, currentUser: DbUser) {
const childrenComments = await Comments.find({parentCommentId: comment._id}).fetch();
childrenComments.forEach(childComment => {
void deleteMutator({
collection: Comments,
documentId: childComment._id,
currentUser: currentUser,
validate: false
});
});
});
//////////////////////////////////////////////////////
// other //
//////////////////////////////////////////////////////
getCollectionHooks("Comments").createBefore.add(function AddReferrerToComment(comment, properties)
{
if (properties && properties.context && properties.context.headers) {
let referrer = properties.context.headers["referer"];
let userAgent = properties.context.headers["user-agent"];
return {
...comment,
referrer: referrer,
userAgent: userAgent,
};
}
});
const commentIntervalSetting = new DatabasePublicSetting<number>('commentInterval', 15) // How long users should wait in between comments (in seconds)
getCollectionHooks("Comments").newValidate.add(async function CommentsNewRateLimit (comment: DbComment, user: DbUser) {
if (!userIsAdmin(user)) {
const timeSinceLastComment = await userTimeSinceLast(user, Comments);
const commentInterval = Math.abs(parseInt(""+commentIntervalSetting.get()));
// check that user waits more than 15 seconds between comments
if((timeSinceLastComment < commentInterval)) {
throw new Error(`Please wait ${commentInterval-timeSinceLastComment} seconds before commenting again.`);
}
}
return comment;
});
ensureIndex(Comments, { userId: 1, createdAt: 1 });
//////////////////////////////////////////////////////
// LessWrong callbacks //
//////////////////////////////////////////////////////
getCollectionHooks("Comments").editAsync.add(async function CommentsEditSoftDeleteCallback (comment: DbComment, oldComment: DbComment, currentUser: DbUser) {
if (comment.deleted && !oldComment.deleted) {
await moderateCommentsPostUpdate(comment, currentUser);
}
});
export async function moderateCommentsPostUpdate (comment: DbComment, currentUser: DbUser) {
await recalculateAFCommentMetadata(comment.postId)
if (comment.postId) {
const comments = await Comments.find({postId:comment.postId, deleted: false}).fetch()
const lastComment:DbComment = _.max(comments, (c) => c.postedAt)
const lastCommentedAt = (lastComment && lastComment.postedAt) || (await Posts.findOne({_id:comment.postId}))?.postedAt || new Date()
void updateMutator({
collection:Posts,
documentId: comment.postId,
set: {
lastCommentedAt:new Date(lastCommentedAt),
},
unset: {},
validate: false,
})
}
void commentsDeleteSendPMAsync(comment, currentUser);
}
getCollectionHooks("Comments").newValidate.add(function NewCommentsEmptyCheck (comment: DbComment) {
const { data } = (comment.contents && comment.contents.originalContents) || {}
if (!data) {
throw new Error("You cannot submit an empty comment");
}
return comment;
});
export async function commentsDeleteSendPMAsync (comment: DbComment, currentUser: DbUser | undefined) {
if ((!comment.deletedByUserId || comment.deletedByUserId !== comment.userId) && comment.deleted && comment.contents?.html) {
const onWhat = comment.tagId
? (await Tags.findOne(comment.tagId))?.name
: (comment.postId
? (await Posts.findOne(comment.postId))?.title
: null
);
const moderatingUser = comment.deletedByUserId ? await Users.findOne(comment.deletedByUserId) : null;
const lwAccount = await getLessWrongAccount();
const conversationData = {
participantIds: [comment.userId, lwAccount._id],
title: `Comment deleted on ${onWhat}`
}
const conversation = await createMutator({
collection: Conversations,
document: conversationData,
currentUser: lwAccount,
validate: false
});
let firstMessageContents =
`One of your comments on "${onWhat}" has been removed by ${(moderatingUser?.displayName) || "the Akismet spam integration"}. We've sent you another PM with the content. If this deletion seems wrong to you, please send us a message on Intercom (the icon in the bottom-right of the page); we will not see replies to this conversation.`
if (comment.deletedReason && moderatingUser) {
firstMessageContents += ` They gave the following reason: "${comment.deletedReason}".`;
}
const firstMessageData = {
userId: lwAccount._id,
contents: {
originalContents: {
type: "html",
data: firstMessageContents
}
},
conversationId: conversation.data._id
}
const secondMessageData = {
userId: lwAccount._id,
contents: comment.contents,
conversationId: conversation.data._id
}
await createMutator({
collection: Messages,
document: firstMessageData,
currentUser: lwAccount,
validate: false
})
await createMutator({
collection: Messages,
document: secondMessageData,
currentUser: lwAccount,
validate: false
})
// eslint-disable-next-line no-console
console.log("Sent moderation messages for comment", comment)
}
}
// Duplicate of PostsNewUserApprovedStatus
getCollectionHooks("Comments").newSync.add(async function CommentsNewUserApprovedStatus (comment: DbComment) {
const commentAuthor = await Users.findOne(comment.userId);
if (!commentAuthor?.reviewedByUserId && (commentAuthor?.karma || 0) < MINIMUM_APPROVAL_KARMA) {
return {...comment, authorIsUnreviewed: true}
}
return comment;
});
// Make users upvote their own new comments
getCollectionHooks("Comments").newAfter.add(async function LWCommentsNewUpvoteOwnComment(comment: DbComment) {
var commentAuthor = await Users.findOne(comment.userId);
const votedComment = commentAuthor && await performVoteServer({ document: comment, voteType: 'smallUpvote', collection: Comments, user: commentAuthor })
return {...comment, ...votedComment} as DbComment;
});
getCollectionHooks("Comments").newAsync.add(async function NewCommentNeedsReview (comment: DbComment) {
const user = await Users.findOne({_id:comment.userId})
const karma = user?.karma || 0
if (karma < 100) {
await Comments.rawUpdateOne({_id:comment._id}, {$set: {needsReview: true}});
}
});
getCollectionHooks("Comments").editSync.add(async function validateDeleteOperations (modifier, comment: DbComment, currentUser: DbUser) {
if (modifier.$set) {
const { deleted, deletedPublic, deletedReason } = modifier.$set
if (deleted || deletedPublic || deletedReason) {
if (deletedPublic && !deleted) {
throw new Error("You cannot publicly delete a comment without also deleting it")
}
if (
(comment.deleted || comment.deletedPublic) &&
(deletedPublic || deletedReason) &&
!userCanDo(currentUser, 'comments.remove.all') &&
comment.deletedByUserId !== currentUser._id) {
throw new Error("You cannot edit the deleted status of a comment that's been deleted by someone else")
}
if (deletedReason && !deleted && !deletedPublic) {
throw new Error("You cannot set a deleted reason without deleting a comment")
}
const childrenComments = await Comments.find({parentCommentId: comment._id}).fetch()
const filteredChildrenComments = _.filter(childrenComments, (c) => !(c && c.deleted))
if (
filteredChildrenComments &&
(filteredChildrenComments.length > 0) &&
(deletedPublic || deleted) &&
!userCanDo(currentUser, 'comment.remove.all')
) {
throw new Error("You cannot delete a comment that has children")
}
}
}
return modifier
});
getCollectionHooks("Comments").editSync.add(async function moveToAnswers (modifier, comment: DbComment) {
if (modifier.$set) {
if (modifier.$set.answer === true) {
await Comments.rawUpdateMany({topLevelCommentId: comment._id}, {$set:{parentAnswerId:comment._id}}, { multi: true })
} else if (modifier.$set.answer === false) {
await Comments.rawUpdateMany({topLevelCommentId: comment._id}, {$unset:{parentAnswerId:true}}, { multi: true })
}
}
return modifier
});
getCollectionHooks("Comments").createBefore.add(async function HandleReplyToAnswer (comment: DbComment, properties)
{
if (comment.parentCommentId) {
let parentComment = await Comments.findOne(comment.parentCommentId)
if (parentComment) {
let modifiedComment = {...comment};
if (parentComment.answer) {
modifiedComment.parentAnswerId = parentComment._id;
}
if (parentComment.parentAnswerId) {
modifiedComment.parentAnswerId = parentComment.parentAnswerId;
}
if (parentComment.tagId) {
modifiedComment.tagId = parentComment.tagId;
}
if (parentComment.topLevelCommentId) {
modifiedComment.topLevelCommentId = parentComment.topLevelCommentId;
}
return modifiedComment;
}
}
return comment;
});
getCollectionHooks("Comments").createBefore.add(async function SetTopLevelCommentId (comment: DbComment, context)
{
let visited: Partial<Record<string,boolean>> = {};
let rootComment: DbComment|null = comment;
while (rootComment?.parentCommentId) {
// This relies on Meteor fibers (rather than being async/await) because
// Vulcan callbacks aren't async-safe.
rootComment = await Comments.findOne({_id: rootComment.parentCommentId});
if (rootComment && visited[rootComment._id])
throw new Error("Cyclic parent-comment relations detected!");
if (rootComment)
visited[rootComment._id] = true;
}
if (rootComment && rootComment._id !== comment._id) {
return {
...comment,
topLevelCommentId: rootComment._id
};
}
return comment;
});
getCollectionHooks("Comments").createAfter.add(async function UpdateDescendentCommentCounts (comment: DbComment) {
const ancestorIds: string[] = await getCommentAncestorIds(comment);
await Comments.rawUpdateOne({ _id: {$in: ancestorIds} }, {
$set: {lastSubthreadActivity: new Date()},
$inc: {descendentCount:1},
});
return comment;
});
getCollectionHooks("Comments").updateAfter.add(async function UpdateDescendentCommentCounts (comment, context) {
if (context.oldDocument.deleted !== context.newDocument.deleted) {
const ancestorIds: string[] = await getCommentAncestorIds(comment);
const increment = context.oldDocument.deleted ? 1 : -1;
await Comments.rawUpdateOne({_id: {$in: ancestorIds}}, {$inc: {descendentCount: increment}})
}
return comment;
});
getCollectionHooks("Comments").createAfter.add(async (document: DbComment) => {
await newDocumentMaybeTriggerReview(document);
return document;
}) | the_stack |
import * as PIXI from 'pixi.js'
import { DisplayObjectWithCulling, AABB } from './types'
export interface SpatialHashOptions {
size?: number
xSize?: number
ySize?: number
simpleTest?: boolean
dirtyTest?: boolean
}
export interface ContainerCullObject {
static?: boolean
added?: (object: DisplayObjectWithCulling) => void
removed?: (object: DisplayObjectWithCulling) => void
}
export interface SpatialHashStats {
buckets: number
total: number
visible: number
culled: number
}
interface SpatialHashBounds {
xStart: number
yStart: number
xEnd: number
yEnd: number
}
export interface ContainerWithCulling extends PIXI.Container {
cull?: ContainerCullObject
}
const SpatialHashDefaultOptions: SpatialHashOptions = {
xSize: 1000,
ySize: 1000,
simpleTest: true,
dirtyTest: true,
}
export class SpatialHash {
protected xSize: number = 1000
protected ySize: number = 1000
/** simpleTest toggle */
public simpleTest: boolean = true
/** dirtyTest toggle */
public dirtyTest: boolean = true
protected width: number
protected height: number
protected hash: object
/** array of PIXI.Containers added using addContainer() */
protected containers: ContainerWithCulling[]
/** array of DisplayObjects added using add() */
protected elements: DisplayObjectWithCulling[]
protected objects: DisplayObjectWithCulling[]
// protected hash: <string,
protected lastBuckets: number
/**
* creates a spatial-hash cull
* Note, options.dirtyTest defaults to false. To greatly improve performance set to true and set
* displayObject.dirty=true when the displayObject changes)
*
* @param {object} [options]
* @param {number} [options.size=1000] - cell size used to create hash (xSize = ySize)
* @param {number} [options.xSize] - horizontal cell size (leave undefined if size is set)
* @param {number} [options.ySize] - vertical cell size (leave undefined if size is set)
* @param {boolean} [options.simpleTest=true] - after finding visible buckets, iterates through items and tests individual bounds
* @param {string} [options.dirtyTest=false] - only update spatial hash for objects with object.dirty=true; this has a HUGE impact on performance
*/
constructor(options?: SpatialHashOptions) {
options = { ...SpatialHashDefaultOptions, ...options }
if (options && typeof options.size !== 'undefined') {
this.xSize = this.ySize = options.size
} else {
this.xSize = options.xSize
this.ySize = options.ySize
}
this.simpleTest = options.simpleTest
this.dirtyTest = options.dirtyTest
this.width = this.height = 0
this.hash = {}
this.containers = []
this.elements = []
}
/**
* add an object to be culled
* side effect: adds object.spatialHashes to track existing hashes
* @param {DisplayObjectWithCulling} object
* @param {boolean} [staticObject] - set to true if the object's position/size does not change
* @return {DisplayObjectWithCulling} object
*/
add(object: DisplayObjectWithCulling, staticObject?: boolean): DisplayObjectWithCulling {
object.spatial = { hashes: [] }
if (this.dirtyTest) {
object.dirty = true
}
if (staticObject) {
object.staticObject = true
}
this.updateObject(object)
this.elements.push(object)
return object
}
/**
* remove an object added by add()
* @param {DisplayObjectWithCulling} object
* @return {DisplayObjectWithCulling} object
*/
remove(object: DisplayObjectWithCulling): DisplayObjectWithCulling {
this.elements.splice(this.elements.indexOf(object), 1)
this.removeFromHash(object)
return object
}
/**
* add an array of objects to be culled
* @param {PIXI.Container} container
* @param {boolean} [staticObject] - set to true if the objects in the container's position/size do not change
*/
addContainer(container: ContainerWithCulling, staticObject?: boolean) {
const added = (object: DisplayObjectWithCulling) => {
object.spatial = { hashes: [] }
this.updateObject(object)
}
const removed = (object: DisplayObjectWithCulling) => {
this.removeFromHash(object)
}
const length = container.children.length
for (let i = 0; i < length; i++) {
const object = container.children[i] as DisplayObjectWithCulling
object.spatial = { hashes: [] }
this.updateObject(object)
}
container.cull = {}
this.containers.push(container)
container.on('childAdded', added)
container.on('childRemoved', removed)
container.cull.added = added
container.cull.removed = removed
if (staticObject) {
container.cull.static = true
}
}
/**
* remove an array added by addContainer()
* @param {PIXI.Container} container
* @return {PIXI.Container} container
*/
removeContainer(container: ContainerWithCulling): ContainerWithCulling {
this.containers.splice(this.containers.indexOf(container), 1)
container.children.forEach(object => this.removeFromHash(object))
container.off('childAdded', container.cull.added)
container.off('removedFrom', container.cull.removed)
delete container.cull
return container
}
/**
* update the hashes and cull the items in the list
* @param {AABB} AABB
* @param {boolean} [skipUpdate] - skip updating the hashes of all objects
* @param {Function} [callback] - callback for each item that is not culled - note, this function is called before setting `object.visible=true`
* @return {number} number of buckets in results
*/
cull(AABB: AABB, skipUpdate?: boolean, callback?: (object: DisplayObjectWithCulling) => boolean): number {
if (!skipUpdate) {
this.updateObjects()
}
this.invisible()
let objects: DisplayObjectWithCulling[]
if (callback) {
objects = this.queryCallbackAll(AABB, this.simpleTest, callback)
} else {
objects = this.query(AABB, this.simpleTest)
}
objects.forEach(object => object.visible = true)
return this.lastBuckets
}
/**
* set all objects in hash to visible=false
*/
invisible() {
const length = this.elements.length
for (let i = 0; i < length; i++) {
this.elements[i].visible = false
}
for (const container of this.containers) {
const length = container.children.length
for (let i = 0; i < length; i++) {
container.children[i].visible = false
}
}
}
/**
* update the hashes for all objects
* automatically called from update() when skipUpdate=false
*/
updateObjects() {
if (this.dirtyTest) {
const length = this.elements.length
for (let i = 0; i < length; i++) {
const object = this.elements[i]
if (object.dirty) {
this.updateObject(object)
object.dirty = false
}
}
for (const container of this.containers) {
if (!container.cull.static) {
const length = container.children.length
for (let i = 0; i < length; i++) {
const object = container.children[i] as DisplayObjectWithCulling
if (object.dirty) {
this.updateObject(object)
object.dirty = false
}
}
}
}
} else {
const length = this.elements.length
for (let i = 0; i < length; i++) {
const object = this.elements[i]
if (!object.staticObject) {
this.updateObject(object)
}
}
for (let container of this.containers) {
if (!container.cull.static) {
const length = container.children.length
for (let i = 0; i < length; i++) {
this.updateObject(container.children[i])
}
}
}
}
}
/**
* update the has of an object
* automatically called from updateObjects()
* @param {DisplayObjectWithCulling} object
*/
updateObject(object: DisplayObjectWithCulling) {
let AABB: AABB
const box = object.getLocalBounds()
AABB = object.AABB = {
x: object.x + (box.x - object.pivot.x) * object.scale.x,
y: object.y + (box.y - object.pivot.y) * object.scale.y,
width: box.width * object.scale.x,
height: box.height * object.scale.y
}
let spatial = object.spatial
if (!spatial) {
spatial = object.spatial = { hashes: [] }
}
const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB)
// only remove and insert if mapping has changed
if (spatial.xStart !== xStart || spatial.yStart !== yStart || spatial.xEnd !== xEnd || spatial.yEnd !== yEnd) {
if (spatial.hashes.length) {
this.removeFromHash(object)
}
for (let y = yStart; y <= yEnd; y++) {
for (let x = xStart; x <= xEnd; x++) {
const key = x + ',' + y
this.insert(object, key)
spatial.hashes.push(key)
}
}
spatial.xStart = xStart
spatial.yStart = yStart
spatial.xEnd = xEnd
spatial.yEnd = yEnd
}
}
/**
* returns an array of buckets with >= minimum of objects in each bucket
* @param {number} [minimum=1]
* @return {array} array of buckets
*/
getBuckets(minimum: number = 1): string[] {
const hashes = []
for (const key in this.hash) {
const hash = this.hash[key]
if (hash.length >= minimum) {
hashes.push(hash)
}
}
return hashes
}
/**
* gets hash bounds
* @param {AABB} AABB
* @return {SpatialHashBounds}
*/
protected getBounds(AABB: AABB): SpatialHashBounds {
const xStart = Math.floor(AABB.x / this.xSize)
const yStart = Math.floor(AABB.y / this.ySize)
const xEnd = Math.floor((AABB.x + AABB.width) / this.xSize)
const yEnd = Math.floor((AABB.y + AABB.height) / this.ySize)
return { xStart, yStart, xEnd, yEnd }
}
/**
* insert object into the spatial hash
* automatically called from updateObject()
* @param {DisplayObjectWithCulling} object
* @param {string} key
*/
insert(object: DisplayObjectWithCulling, key: string) {
if (!this.hash[key]) {
this.hash[key] = [object]
} else {
this.hash[key].push(object)
}
}
/**
* removes object from the hash table
* should be called when removing an object
* automatically called from updateObject()
* @param {object} object
*/
removeFromHash(object: DisplayObjectWithCulling) {
const spatial = object.spatial
while (spatial.hashes.length) {
const key = spatial.hashes.pop()
const list = this.hash[key]
list.splice(list.indexOf(object), 1)
}
}
/**
* get all neighbors that share the same hash as object
* @param {DisplayObjectWithCulling} object - in the spatial hash
* @return {Array} - of objects that are in the same hash as object
*/
neighbors(object: DisplayObjectWithCulling): DisplayObjectWithCulling[] {
let results = []
object.spatial.hashes.forEach(key => results = results.concat(this.hash[key]))
return results
}
/**
* returns an array of objects contained within bounding box
* @param {AABB} AABB - bounding box to search
* @param {boolean} [simpleTest=true] - perform a simple bounds check of all items in the buckets
* @return {object[]} - search results
*/
query(AABB: AABB, simpleTest: boolean = true): DisplayObjectWithCulling[] {
let buckets = 0
let results = []
const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB)
for (let y = yStart; y <= yEnd; y++) {
for (let x = xStart; x <= xEnd; x++) {
const entry = this.hash[x + ',' + y]
if (entry) {
if (simpleTest) {
const length = entry.length
for (let i = 0; i < length; i++) {
const object = entry[i]
const box = object.AABB
if (box.x + box.width > AABB.x && box.x < AABB.x + AABB.width &&
box.y + box.height > AABB.y && box.y < AABB.y + AABB.height) {
results.push(object)
}
}
} else {
results = results.concat(entry)
}
buckets++
}
}
}
this.lastBuckets = buckets
return results
}
/**
* returns an array of objects contained within bounding box with a callback on each non-culled object
* this function is different from queryCallback, which cancels the query when a callback returns true
*
* @param {AABB} AABB - bounding box to search
* @param {boolean} [simpleTest=true] - perform a simple bounds check of all items in the buckets
* @param {Function} callback - function to run for each non-culled object
* @return {object[]} - search results
*/
queryCallbackAll(AABB: AABB, simpleTest: boolean = true, callback: (object: DisplayObjectWithCulling) => boolean): DisplayObjectWithCulling[] {
let buckets = 0
let results = []
const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB)
for (let y = yStart; y <= yEnd; y++) {
for (let x = xStart; x <= xEnd; x++) {
const entry = this.hash[x + ',' + y]
if (entry) {
if (simpleTest) {
const length = entry.length
for (let i = 0; i < length; i++) {
const object = entry[i]
const box = object.AABB
if (box.x + box.width > AABB.x && box.x < AABB.x + AABB.width &&
box.y + box.height > AABB.y && box.y < AABB.y + AABB.height) {
results.push(object)
callback(object)
}
}
} else {
results = results.concat(entry)
for (const object of entry) {
callback(object)
}
}
buckets++
}
}
}
this.lastBuckets = buckets
return results
}
/**
* iterates through objects contained within bounding box
* stops iterating if the callback returns true
* @param {AABB} AABB - bounding box to search
* @param {function} callback
* @param {boolean} [simpleTest=true] - perform a simple bounds check of all items in the buckets
* @return {boolean} - true if callback returned early
*/
queryCallback(AABB: AABB, callback: (object: DisplayObjectWithCulling) => boolean, simpleTest: boolean = true): boolean {
const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB)
for (let y = yStart; y <= yEnd; y++) {
for (let x = xStart; x <= xEnd; x++) {
const entry = this.hash[x + ',' + y]
if (entry) {
for (let i = 0; i < entry.length; i++) {
const object = entry[i]
if (simpleTest) {
const AABB = object.AABB
if (AABB.x + AABB.width > AABB.x && AABB.x < AABB.x + AABB.width &&
AABB.y + AABB.height > AABB.y && AABB.y < AABB.y + AABB.height) {
if (callback(object)) {
return true
}
}
} else {
if (callback(object)) {
return true
}
}
}
}
}
}
return false
}
/**
* Get stats
* @return {SpatialHashStats}
*/
stats(): SpatialHashStats {
let visible = 0, count = 0
const length = this.elements.length
for (let i = 0; i < length; i++) {
const object = this.elements[i]
visible += object.visible ? 1 : 0
count++
}
for (const list of this.containers) {
const length = list.children.length
for (let i = 0; i < length; i++) {
const object = list.children[i]
visible += object.visible ? 1 : 0
count++
}
}
return {
buckets: this.lastBuckets,
total: count,
visible,
culled: count - visible
}
}
/**
* helper function to evaluate hash table
* @return {number} - the number of buckets in the hash table
* */
getNumberOfBuckets(): number {
return Object.keys(this.hash).length
}
/**
* helper function to evaluate hash table
* @return {number} - the average number of entries in each bucket
*/
getAverageSize(): number {
let total = 0
for (let key in this.hash) {
total += this.hash[key].length
}
return total / this.getBuckets().length
}
/**
* helper function to evaluate the hash table
* @return {number} - the largest sized bucket
*/
getLargest(): number {
let largest = 0
for (let key in this.hash) {
if (this.hash[key].length > largest) {
largest = this.hash[key].length
}
}
return largest
}
/**
* gets quadrant bounds
* @return {SpatialHashBounds}
*/
getWorldBounds(): SpatialHashBounds {
let xStart = Infinity, yStart = Infinity, xEnd = 0, yEnd = 0
for (let key in this.hash) {
const split = key.split(',')
let x = parseInt(split[0])
let y = parseInt(split[1])
xStart = x < xStart ? x : xStart
yStart = y < yStart ? y : yStart
xEnd = x > xEnd ? x : xEnd
yEnd = y > yEnd ? y : yEnd
}
return { xStart, yStart, xEnd, yEnd }
}
/**
* helper function to evaluate the hash table
* @param {AABB} [AABB] - bounding box to search or entire world
* @return {number} - sparseness percentage (i.e., buckets with at least 1 element divided by total possible buckets)
*/
getSparseness(AABB?: AABB): number {
let count = 0, total = 0
const { xStart, yStart, xEnd, yEnd } = AABB ? this.getBounds(AABB) : this.getWorldBounds()
for (let y = yStart; y < yEnd; y++) {
for (let x = xStart; x < xEnd; x++) {
count += (this.hash[x + ',' + y] ? 1 : 0)
total++
}
}
return count / total
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_expand_button/cr_expand_button.m.js';
import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js';
import 'chrome://resources/cr_elements/cr_toggle/cr_toggle.m.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/policy/cr_policy_pref_indicator.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/js/action_link.js';
import 'chrome://resources/cr_elements/action_link_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-collapse/iron-collapse.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import './languages.js';
import './languages_subpage.js';
import '../controls/controlled_radio_button.js';
import '../controls/settings_radio_group.js';
import '../controls/settings_toggle_button.js';
import '../icons.js';
import '../settings_page/settings_animated_pages.js';
import '../settings_page/settings_subpage.js';
import '../settings_shared_css.js';
import '../settings_vars_css.js';
// <if expr="not is_macosx">
import './edit_dictionary_page.js';
// </if>
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BaseMixin} from '../base_mixin.js';
import {loadTimeData} from '../i18n_setup.js';
import {PrefsMixin} from '../prefs/prefs_mixin.js';
import {routes} from '../route.js';
import {Router} from '../router.js';
import {LanguageSettingsMetricsProxy, LanguageSettingsMetricsProxyImpl, LanguageSettingsPageImpressionType} from './languages_settings_metrics_proxy.js';
import {LanguageHelper, LanguagesModel, LanguageState, SpellCheckLanguageState} from './languages_types.js';
interface RepeaterEvent extends Event {
model: {
item: LanguageState,
};
}
type FocusConfig = Map<string, (string|(() => void))>;
const SettingsLanguagesPageElementBase =
I18nMixin(PrefsMixin(BaseMixin(PolymerElement)));
class SettingsLanguagesPageElement extends SettingsLanguagesPageElementBase {
static get is() {
return 'settings-languages-page';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* Read-only reference to the languages model provided by the
* 'settings-languages' instance.
*/
languages: {
type: Object,
notify: true,
},
languageHelper: Object,
// <if expr="not is_macosx">
spellCheckLanguages_: {
type: Array,
value() {
return [];
},
},
// </if>
/**
* The language to display the details for.
*/
detailLanguage_: Object,
enableDesktopRestructuredLanguageSettings_: {
type: Boolean,
value() {
let enabled = false;
// <if expr="not lacros">
enabled = loadTimeData.getBoolean(
'enableDesktopRestructuredLanguageSettings');
// </if>
return enabled;
},
},
hideSpellCheckLanguages_: {
type: Boolean,
value: false,
},
/**
* Whether the language settings list is opened.
*/
languagesOpened_: {
type: Boolean,
observer: 'onLanguagesOpenedChanged_',
},
showAddLanguagesDialog_: Boolean,
focusConfig_: {
type: Object,
value() {
const map = new Map();
// <if expr="not is_macosx">
if (routes.EDIT_DICTIONARY) {
map.set(routes.EDIT_DICTIONARY.path, '#spellCheckSubpageTrigger');
}
// </if>
// <if expr="not lacros">
if (loadTimeData.getBoolean(
'enableDesktopRestructuredLanguageSettings')) {
if (routes.LANGUAGE_SETTINGS) {
map.set(
routes.LANGUAGE_SETTINGS.path, '#languagesSubpageTrigger');
}
}
// </if>
return map;
},
},
};
}
// <if expr="not is_macosx">
static get observers() {
return [
'updateSpellcheckLanguages_(languages.enabled.*, ' +
'languages.spellCheckOnLanguages.*)',
'updateSpellcheckEnabled_(prefs.browser.enable_spellchecking.*)',
];
}
// </if>
languages?: LanguagesModel;
languageHelper: LanguageHelper;
private spellCheckLanguages_: Array<LanguageState|SpellCheckLanguageState>;
private detailLanguage_?: LanguageState;
private enableDesktopRestructuredLanguageSettings_: boolean;
private hideSpellCheckLanguages_: boolean;
private languagesOpened_: boolean;
private showAddLanguagesDialog_: boolean;
private focusConfig_: FocusConfig;
private languageSettingsMetricsProxy_: LanguageSettingsMetricsProxy =
LanguageSettingsMetricsProxyImpl.getInstance();
// <if expr="not is_macosx">
/**
* Checks if there are any errors downloading the spell check dictionary.
* This is used for showing/hiding error messages, spell check toggle and
* retry. button.
*/
private errorsGreaterThan_(
downloadDictionaryFailureCount: number, threshold: number): boolean {
return downloadDictionaryFailureCount > threshold;
}
// </if>
// <if expr="not is_macosx">
/**
* Returns the value to use as the |pref| attribute for the policy indicator
* of spellcheck languages, based on whether or not the language is enabled.
* @param isEnabled Whether the language is enabled or not.
*/
getIndicatorPrefForManagedSpellcheckLanguage_(isEnabled: boolean):
chrome.settingsPrivate.PrefObject {
return isEnabled ? this.get('spellcheck.forced_dictionaries', this.prefs) :
this.get('spellcheck.blocked_dictionaries', this.prefs);
}
/**
* Returns an array of enabled languages, plus spellcheck languages that are
* force-enabled by policy.
*/
private getSpellCheckLanguages_():
Array<LanguageState|SpellCheckLanguageState> {
const supportedSpellcheckLanguages:
Array<LanguageState|SpellCheckLanguageState> =
this.languages!.enabled.filter(
(item) => item.language.supportsSpellcheck);
const supportedSpellcheckLanguagesSet =
new Set(supportedSpellcheckLanguages.map(x => x.language.code));
this.languages!.spellCheckOnLanguages.forEach(spellCheckLang => {
if (!supportedSpellcheckLanguagesSet.has(spellCheckLang.language.code)) {
supportedSpellcheckLanguages.push(spellCheckLang);
}
});
return supportedSpellcheckLanguages;
}
private updateSpellcheckLanguages_() {
if (this.languages === undefined) {
return;
}
this.set('spellCheckLanguages_', this.getSpellCheckLanguages_());
// Notify Polymer of subproperties that might have changed on the items in
// the spellCheckLanguages_ array, to make sure the UI updates. Polymer
// would otherwise not notice the changes in the subproperties, as some of
// them are references to those from |this.languages.enabled|. It would be
// possible to |this.linkPaths()| objects from |this.languages.enabled| to
// |this.spellCheckLanguages_|, but that would require complex
// housekeeping to |this.unlinkPaths()| as |this.languages.enabled|
// changes.
for (let i = 0; i < this.spellCheckLanguages_.length; i++) {
this.notifyPath(`spellCheckLanguages_.${i}.isManaged`);
this.notifyPath(`spellCheckLanguages_.${i}.spellCheckEnabled`);
this.notifyPath(
`spellCheckLanguages_.${i}.downloadDictionaryFailureCount`);
}
if (this.spellCheckLanguages_.length === 0) {
// If there are no supported spell check languages, automatically turn
// off spell check to indicate no spell check will happen.
this.setPrefValue('browser.enable_spellchecking', false);
}
if (this.spellCheckLanguages_.length === 1) {
const singleLanguage = this.spellCheckLanguages_[0];
// Hide list of spell check languages if there is only 1 language
// and we don't need to display any errors for that language
// TODO(crbug/1124888): Make hideSpellCheckLanugages_ a computed property
this.hideSpellCheckLanguages_ = !singleLanguage.isManaged &&
singleLanguage.downloadDictionaryFailureCount === 0;
} else {
this.hideSpellCheckLanguages_ = false;
}
}
private updateSpellcheckEnabled_() {
if (this.prefs === undefined) {
return;
}
// If there is only 1 language, we hide the list of languages so users
// are unable to toggle on/off spell check specifically for the 1
// language. Therefore, we need to treat the toggle for
// `browser.enable_spellchecking` as the toggle for the 1 language as
// well.
if (this.spellCheckLanguages_.length === 1) {
this.languageHelper.toggleSpellCheck(
this.spellCheckLanguages_[0].language.code,
!!this.getPref('browser.enable_spellchecking').value);
}
}
/**
* Opens the Custom Dictionary page.
*/
private onEditDictionaryTap_() {
Router.getInstance().navigateTo(routes.EDIT_DICTIONARY);
}
/**
* Handler for enabling or disabling spell check for a specific language.
*/
private onSpellCheckLanguageChange_(e: RepeaterEvent) {
const item = e.model.item;
if (!item.language.supportsSpellcheck) {
return;
}
this.languageHelper.toggleSpellCheck(
item.language.code, !item.spellCheckEnabled);
}
/**
* @return The display name for a given language code.
*/
private getProspectiveUILanguageName_(languageCode: string): string {
return this.languageHelper.getLanguage(languageCode)!.displayName;
}
/**
* Handler to initiate another attempt at downloading the spell check
* dictionary for a specified language.
*/
private onRetryDictionaryDownloadClick_(e: RepeaterEvent) {
assert(this.errorsGreaterThan_(
e.model.item.downloadDictionaryFailureCount, 0));
this.languageHelper.retryDownloadDictionary(e.model.item.language.code);
}
/**
* Handler for clicking on the name of the language. The action taken must
* match the control that is available.
*/
private onSpellCheckNameClick_(e: RepeaterEvent) {
assert(!this.isSpellCheckNameClickDisabled_(e.model.item));
this.onSpellCheckLanguageChange_(e);
}
/**
* Name only supports clicking when language is not managed, supports
* spellcheck, and the dictionary has been downloaded with no errors.
*/
private isSpellCheckNameClickDisabled_(item: LanguageState|
SpellCheckLanguageState): boolean {
return item.isManaged || !item.language.supportsSpellcheck ||
item.downloadDictionaryFailureCount > 0;
}
// </if> expr="not is_macosx"
private getSpellCheckSubLabel_(): string|undefined {
// <if expr="not is_macosx">
if (this.spellCheckLanguages_.length === 0) {
return this.i18n('spellCheckDisabledReason');
}
// </if>
return undefined;
}
/**
* @param newVal The new value of languagesOpened_.
* @param oldVal The old value of languagesOpened_.
*/
private onLanguagesOpenedChanged_(newVal: boolean, oldVal: boolean) {
if (!oldVal && newVal) {
this.languageSettingsMetricsProxy_.recordPageImpressionMetric(
LanguageSettingsPageImpressionType.MAIN);
}
}
// <if expr="not lacros">
/**
* Opens the Language Settings page.
*/
private onLanguagesSubpageClick_() {
if (this.enableDesktopRestructuredLanguageSettings_) {
Router.getInstance().navigateTo(routes.LANGUAGE_SETTINGS);
}
}
// </if>
/**
* Toggles the expand button within the element being listened to.
*/
private toggleExpandButton_(e: Event) {
// The expand button handles toggling itself.
if ((e.target as HTMLElement).tagName === 'CR-EXPAND-BUTTON') {
return;
}
if (!(e.currentTarget as HTMLElement).hasAttribute('actionable')) {
return;
}
const expandButton =
(e.currentTarget as HTMLElement).querySelector('cr-expand-button')!;
assert(expandButton);
expandButton.expanded = !expandButton.expanded;
focusWithoutInk(expandButton);
}
}
customElements.define(
SettingsLanguagesPageElement.is, SettingsLanguagesPageElement); | the_stack |
import * as React from "react";
import { Button, ButtonType } from "office-ui-fabric-react";
import { ExcelUtils } from "./ExceLint-core/src/excelutils";
import { ExceLintVector, ProposedFix } from "./ExceLint-core/src/ExceLintTypes";
import { Config } from "./ExceLint-core/src/config";
const barWidth = 100; // pixel length of the suspiciousness bar
export interface ContentProps {
message1: string;
buttonLabel1: string;
click1: any;
message2: string;
buttonLabel2: string;
click2: any;
sheetName: string;
currentFix: number;
totalFixes: number;
themFixes: ProposedFix[];
suspiciousCells: ExceLintVector[];
currentSuspiciousCell: number;
numFixes: number;
selector: any;
cellSelector: any;
}
const divStyle: any = {
height: "100px",
overflowY: "auto",
overflowX: "hidden",
};
const lineStyle: any = {
color: "blue",
textAlign: "left",
verticalAlign: "middle",
};
const notSuspiciousStyle: any = {
color: "red",
};
function makeTable(
sheetName: string,
arr: ProposedFix[],
selector,
current: number,
numFixes: number
): any {
if (numFixes === 0) {
numFixes = 1;
}
let counter = 0;
if (arr.length > 0) {
let children = [];
for (let i = 0; i < arr.length; i++) {
let r = ExcelUtils.get_rectangle(arr, i);
if (r) {
let [col0, row0, col1, row1] = r;
let scoreBar = arr[i].score;
scoreBar *= barWidth;
if (scoreBar > barWidth) {
scoreBar = barWidth;
}
counter += 1;
let rangeDisplay = <b></b>;
if (current === i) {
rangeDisplay = (
<td style={{ width: 100 }}>
<b>
{col0}
{row0}:{col1}
{row1}
</b>
</td>
);
} else {
rangeDisplay = (
<td style={{ width: 100 }}>
{col0}
{row0}:{col1}
{row1}
</td>
);
}
const scoreStr = arr[i].score.toString(); // + "\n" + "(" + Math.round(score).toString() + "% anomalous)";
let barColor = "red";
if (Math.round(scoreBar) < 50) {
barColor = "yellow";
}
children.push(
<tr
style={lineStyle}
onClick={(ev) => {
ev.preventDefault();
selector(i);
}}
>
{rangeDisplay}
<td
title={scoreStr}
style={{
width: Math.round(scoreBar),
backgroundColor: barColor,
display: "inline-block",
}}
>
</td>
<td
title={scoreStr}
style={{
width: barWidth - Math.round(scoreBar),
backgroundColor: "lightgray",
display: "inline-block",
}}
>
</td>
</tr>
);
}
}
if (counter > 0) {
let table = [];
let header = (
<tr>
<th align="left">Range</th>
<th align="left">Anomalousness</th>
</tr>
);
table.push(
<div style={notSuspiciousStyle}>
Click to jump to anomalous formulas in {sheetName}:<br />
<em>Hover over a range for more details.</em>
<br />
<br />
<div style={divStyle}>
<table style={{ width: "300px" }}>
<tbody>
{header}
{children}
</tbody>
</table>
</div>
</div>
);
return table;
}
}
return (
<div style={notSuspiciousStyle}>
No anomalous formulas found in {sheetName}.<br />
</div>
);
}
class PropsThing {
sheetName: string;
currentFix: number;
totalFixes: number;
themFixes: ProposedFix[];
selector: any;
numFixes: number;
suspiciousCells: ExceLintVector[];
cellSelector: any;
currentSuspiciousCell: number;
}
function DisplayFixes(props: PropsThing) {
if (props.sheetName === "") {
return <div></div>;
}
let result1 = <div></div>;
let str = "";
// Filter out fixes whose score is below the threshold.
let filteredFixes = props.themFixes.filter((pf) =>
pf.score >= Config.getReportingThreshold() / 100
);
let table1 = <div></div>;
// OK, if we got here, we did some analysis.
if (filteredFixes.length === 0 && props.suspiciousCells.length === 0) {
// We got nothing.
table1 = (
<div style={notSuspiciousStyle}>
<br />
Nothing anomalous found in {props.sheetName}.<br />
<br />
</div>
);
}
table1 = makeTable(
props.sheetName,
filteredFixes,
props.selector,
props.currentFix,
filteredFixes.length
);
result1 = (
<div>
<br />
<br />
{table1}
</div>
);
return (
<div>
{result1}
</div>
);
}
class ReactState implements ContentProps {
// obligatory react stuff
message1: string;
buttonLabel1: string;
click1: any;
message2: string;
buttonLabel2: string;
click2: any;
selector: any;
cellSelector: any;
// my stuff
sheetName: string;
currentFix: number;
totalFixes: number;
themFixes: ProposedFix[];
numFixes: number;
suspiciousCells: ExceLintVector[];
currentSuspiciousCell: number;
}
export class Content extends React.Component<ReactState, any> {
constructor(props: ReactState, context: any) {
super(props, context);
this.state = {
sheetName: props.sheetName,
currentFix: props.currentFix,
totalFixes: props.totalFixes,
themFixes: props.themFixes,
numFixes: props.numFixes,
suspiciousCells: props.suspiciousCells,
currentSuspiciousCell: props.currentSuspiciousCell,
};
}
render() {
let instructions = <div></div>;
let slider1 = <div></div>;
let slider2 = <div></div>;
if (this.state.themFixes.length === 0 && this.state.suspiciousCells.length === 0) {
instructions = (
<div>
<br />
Click on{" "}
<a onClick={this.props.click1}>
<b>Reveal Structure</b>
</a>{" "}
to reveal the underlying structure of the spreadsheet. Different formulas are assigned
different colors, making it easy to spot inconsistencies or to audit a spreadsheet for
correctness.
<br />
<br />
<br />
</div>
);
}
return (
<div id="content-main">
<div className="padding">
<Button className="ms-button" buttonType={ButtonType.primary} onClick={this.props.click1}>
{this.props.buttonLabel1}
</Button>
<Button className="ms-button" buttonType={ButtonType.primary} onClick={this.props.click2}>
{this.props.buttonLabel2}
</Button>
<DisplayFixes
sheetName={this.state.sheetName as string}
currentFix={this.state.currentFix as number}
totalFixes={this.state.totalFixes as number}
themFixes={this.state.themFixes as ProposedFix[]}
selector={this.props.selector}
numFixes={this.state.numFixes as number}
suspiciousCells={this.state.suspiciousCells as ExceLintVector[]}
cellSelector={this.props.cellSelector}
currentSuspiciousCell={this.state.currentSuspiciousCell as number}
/>
{instructions}
{slider1}
{slider2}
<br />
<svg width="300" height="20">
<rect x="0" y="0" width="3.5714285714285716" height="20" fill="#ecaaae" />
<rect
x="3.5714285714285716"
y="0"
width="3.5714285714285716"
height="20"
fill="#74aff3"
/>
<rect
x="7.142857142857143"
y="0"
width="3.5714285714285716"
height="20"
fill="#d8e9b2"
/>
<rect
x="10.714285714285715"
y="0"
width="3.5714285714285716"
height="20"
fill="#deb1e0"
/>
<rect
x="14.285714285714286"
y="0"
width="3.5714285714285716"
height="20"
fill="#9ec991"
/>
<rect
x="17.857142857142858"
y="0"
width="3.5714285714285716"
height="20"
fill="#adbce9"
/>
<rect
x="21.42857142857143"
y="0"
width="3.5714285714285716"
height="20"
fill="#e9c59a"
/>
<rect
x="25.000000000000004"
y="0"
width="3.5714285714285716"
height="20"
fill="#71cdeb"
/>
<rect
x="28.571428571428577"
y="0"
width="3.5714285714285716"
height="20"
fill="#bfbb8a"
/>
<rect
x="32.142857142857146"
y="0"
width="3.5714285714285716"
height="20"
fill="#94d9df"
/>
<rect
x="35.714285714285715"
y="0"
width="3.5714285714285716"
height="20"
fill="#91c7a8"
/>
<rect
x="39.285714285714285"
y="0"
width="3.5714285714285716"
height="20"
fill="#b4efd3"
/>
<rect
x="42.857142857142854"
y="0"
width="3.5714285714285716"
height="20"
fill="#80b6aa"
/>
<rect
x="46.42857142857142"
y="0"
width="3.5714285714285716"
height="20"
fill="#9bd1c6"
/>
<text x="55" y="13">
formulas (pastel colors)
</text>
</svg>
<svg width="300" height="20">
<rect x="0" y="0" width="50" height="20" fill="#d3d3d3" />
<text x="55" y="13">
data used by some formula (gray)
</text>
</svg>
<br />
<svg width="300" height="20">
<rect x="0" y="0" width="50" height="20" fill="#eed202" />
<text x="55" y="13">
data not used by ANY formula (yellow)
</text>
</svg>
<br />
<br />
<div className="ExceLint-scrollbar"></div>
<br />
<small>
<a
target="_blank"
href="https://github.com/plasma-umass/ExceLint-addin/issues/new?assignees=dbarowy%2C+emeryberger%2C+bzorn&labels=enhancement&template=feature_request.md&title="
>
Send feedback
</a>{" "}
|{" "}
<a
target="_blank"
href="https://github.com/plasma-umass/ExceLint-addin/issues/new?assignees=dbarowy%2C+emeryberger%2C+bzorn&labels=bug&template=bug_report.md&title="
>
Report bugs
</a>
<br />
For more information, see <a href="https://excelint.org">excelint.org</a>.
</small>
<br />
</div>
</div>
);
}
} | the_stack |
import { record, getRecordedTrials, getWarmupTrials } from "../record";
import seedrandom from "seedrandom";
import { assert } from "chai";
import { byteLength, Data, getMemoryUsed } from "../util";
const SEED = "42";
const CONCURRENT_NUM_DEVICES = 100;
const ROTATE_NUM_DEVICES = 1000;
export interface Replica {
/**
* Execute doOps, which performs ops on this replica, in a single
* transaction, i.e., sending a single message
* via onsend (provided to Implementation).
*/
transact(doOps: () => void): void;
receive(msg: Data): void;
save(): Data;
load(saveData: Data): void;
skipLoad(): void;
}
/**
* A Replica constructor with the given constructor args,
* i.e., a Replica factory.
*/
export type Implementation<I> = new (
onsend: (msg: Data) => void,
replicaIdRng: seedrandom.prng
) => Replica & I;
export interface Trace<I> {
/**
* Do one op on replica. In practice, replica will be a Replica,
* but we don't express that constraint by default because we don't
* expect you to need any Replica methods. In particular, don't call
* transact (we'll call it for you as needed, possibly transacting
* more than one op at a time).
*
* TODO: opNum guarantees (unique; mostly in-order on
* same replica)
*/
doOp(replica: I, rng: seedrandom.prng, opNum: number): void;
/**
* Used for checking that all replicas end up in the
* same state when they should.
*
* The return value must be comparable using
* assert.deepStrictEqual.
*/
getState(replica: I): unknown;
/**
* The intended number of ops.
*/
readonly numOps: number;
/**
* The correct output of getState after performing
* numOps operations sequentially, or undefined if N/A.
*/
readonly correctState: unknown;
}
export type Mode = "single" | "rotate" | "concurrent";
export class ReplicaBenchmark<I> {
// TODO: mention measurement.csv used as file name
// (e.g. sendTime.csv). Method name convention (lowerCamelCase).
// Label used for method params (e.g. ops), space-separated.
// Describe full file/folder name.
constructor(
private readonly trace: Trace<I>,
/**
* The name of the trace
* (e.g. text-trace, counter). Used as the results
* folder name. Folder name convention
* (lower-hyphen-case).
*/
private readonly traceName: string,
private readonly implementation: Implementation<I>,
/**
* The name of the implementation
* (e.g. Yjs, CollabsDeleting). Used in the results
* "Implementation" column. Class name convention
* (UpperCamelCase).
*/
private readonly implementationName: string
) {}
/**
* Do one trace op in a transaction.
*/
private transactOp(
replica: Replica & I,
rng: seedrandom.prng,
op: number
): void {
replica.transact(() => this.trace.doOp(replica, rng, op));
}
/**
* Returns the sent messages for the given mode, which are to be received
* during "receive" benchmarks.
*
* Also returns the intended finalState, for checking against the receiver's
* final state. Before returning, it is checked that all
* senders are also in this finalState (if applicable).
*/
async getSentMessages(
mode: Mode
): Promise<[msgs: Data[], finalState: unknown]> {
const senderRng = seedrandom(SEED + "sender");
const rng = seedrandom(SEED);
const msgs: Data[] = [];
if (mode === "single") {
// Single device: The ops are performed by one device, sequentially.
const sender = new this.implementation((msg) => {
msgs.push(msg);
}, senderRng);
sender.skipLoad();
const rng = seedrandom(SEED);
for (let op = 0; op < this.trace.numOps; op++) {
this.transactOp(sender, rng, op);
}
return [msgs, this.trace.getState(sender)];
} else if (mode === "rotate") {
// Device rotation: The ops are performed by ROTATE_NUM_DEVICES
// devices, sequentially. The ops are divided equally between devices.
const opsPerSender = Math.floor(this.trace.numOps / ROTATE_NUM_DEVICES);
let sender = new this.implementation((msg) => {
msgs.push(msg);
}, senderRng);
sender.skipLoad();
for (let op = 0; op < this.trace.numOps; op++) {
// Each device performs opsPerSender ops, except the last, who performs
// the remainder if the ops do not divide evenly.
if (
op % opsPerSender === 0 &&
op !== 0 &&
op / opsPerSender < ROTATE_NUM_DEVICES
) {
if ((op / opsPerSender) % 100 === 0) {
console.log(
"Setup: Rotating device " +
op / opsPerSender +
"/" +
ROTATE_NUM_DEVICES
);
// Force GC, to prevent OOM errors (Node doesn't seem to GC
// very well during sync code).
await getMemoryUsed();
}
const saveData = sender.save();
sender = new this.implementation((msg) => {
msgs.push(msg);
}, senderRng);
sender.load(saveData);
}
this.transactOp(sender, rng, op);
}
return [msgs, this.trace.getState(sender)];
} else if (mode === "concurrent") {
// Concurrency: Ops are performed by CONCURRENT_NUM_DEVICES devices
// acting concurrently.
const concurrers: (Replica & I)[] = [];
const lastMsgs = new Array<Data>(CONCURRENT_NUM_DEVICES);
for (let i = 0; i < CONCURRENT_NUM_DEVICES; i++) {
const concurrerI = new this.implementation((msg) => {
msgs.push(msg);
lastMsgs[i] = msg;
}, senderRng);
concurrerI.skipLoad();
concurrers.push(concurrerI);
}
// Each device performs a contiguous range of ops. If the ops do not
// divide evenly, then the last concurrer performs fewer ops.
const numRounds = Math.ceil(this.trace.numOps / CONCURRENT_NUM_DEVICES);
const lastConcurrerOps =
this.trace.numOps - numRounds * (CONCURRENT_NUM_DEVICES - 1);
const roundsPerPrint = Math.floor(numRounds / 10);
for (let round = 0; round < numRounds; round++) {
if (round % roundsPerPrint === 0) {
console.log("Setup: Concurrency round " + round + "/" + numRounds);
// Force GC, to prevent OOM errors (Node doesn't seem to GC
// very well during sync code).
await getMemoryUsed();
}
// For the last round, might not have enough messages for all senders.
const numSenders =
round >= lastConcurrerOps
? CONCURRENT_NUM_DEVICES - 1
: CONCURRENT_NUM_DEVICES;
for (let i = 0; i < numSenders; i++) {
this.transactOp(concurrers[i], rng, i * numRounds + round);
}
// Everyone receives each others' messages.
for (let sender = 0; sender < numSenders; sender++) {
for (
let receiver = 0;
receiver < CONCURRENT_NUM_DEVICES;
receiver++
) {
if (sender !== receiver) {
concurrers[receiver].receive(lastMsgs[sender]);
}
}
}
}
// Check all states are equal.
const finalState = this.trace.getState(concurrers[0]);
for (let i = 1; i < concurrers.length; i++) {
assert.deepStrictEqual(
this.trace.getState(concurrers[i]),
finalState,
"unequal concurrer states"
);
}
return [msgs, finalState];
} else {
throw new Error("Unrecognized mode: " + mode);
}
}
/**
* Benchmark time to send all the ops.
*/
async sendTimeSingle() {
const values = new Array<number>(getRecordedTrials());
values.fill(0);
for (let trial = -getWarmupTrials(); trial < getRecordedTrials(); trial++) {
// Between trials, force GC.
await getMemoryUsed();
console.log("Starting sendTimeSingle trial " + trial);
const sender = new this.implementation(() => {},
seedrandom(SEED + "sender"));
sender.skipLoad();
const rng = seedrandom(SEED);
// Prep measurement.
const startTime = process.hrtime.bigint();
// Send all edits.
// We don't use getSentMessages here because it adds overhead that we
// don't want to measure (e.g., recording the messages).
for (let op = 0; op < this.trace.numOps; op++) {
this.transactOp(sender, rng, op);
}
// Take measurement.
if (trial >= 0) {
values[trial] = new Number(
process.hrtime.bigint() - startTime!
).valueOf();
}
// // For profiling memory usage:
// console.log("Ready to profile");
// await new Promise((resolve) => setTimeout(resolve, 1000 * 1000));
// Check final state.
if (this.trace.correctState !== undefined) {
assert.deepStrictEqual(
this.trace.getState(sender),
this.trace.correctState,
"sender state does not equal trace.correctState"
);
}
}
// Record measurements.
record(
"sendTime/" + this.traceName,
this.implementationName,
"single",
this.trace.numOps,
values
);
}
/**
* Benchmark memory of a sender after sending all the ops.
*/
async sendMemorySingle() {
const values = new Array<number>(getRecordedTrials());
values.fill(0);
let bases = new Array<number>(getRecordedTrials());
bases.fill(0);
for (let trial = -getWarmupTrials(); trial < getRecordedTrials(); trial++) {
// Between trials, force GC.
// We do this even for warmup trials because empirically, after the first
// few GCs (usually 3), the memory usage suddenly gets smaller.
// Presumably this is due to some Node internal optimization.
// If that happens during a recorded trial, it gives a spuriously
// low (often negative) memory measurement. By forcing GC's during warmup,
// with sufficiently many warmup trials, we avoid that happening.
await getMemoryUsed();
console.log("Starting sendMemorySingle trial " + trial);
const sender = new this.implementation(() => {},
seedrandom(SEED + "sender"));
sender.skipLoad();
const rng = seedrandom(SEED);
// Prep measurement.
bases[trial] = await getMemoryUsed();
// Send all edits.
// We don't use getSentMessages here because it adds overhead that we
// don't want to measure (e.g., recording the messages).
for (let op = 0; op < this.trace.numOps; op++) {
this.transactOp(sender, rng, op);
}
// Take measurement.
if (trial >= 0) {
values[trial] = await getMemoryUsed();
}
// Check final state.
if (this.trace.correctState !== undefined) {
assert.deepStrictEqual(
this.trace.getState(sender),
this.trace.correctState,
"sender state does not equal trace.correctState"
);
}
}
// Record measurements.
record(
"sendMemory/" + this.traceName,
this.implementationName,
"single",
this.trace.numOps,
values,
bases
);
}
/**
* Benchmark network bytes of receiving all the ops.
*/
async receiveNetwork(mode: Mode, msgs: Data[], _finalState: unknown) {
let bytesSent = 0;
for (const msg of msgs) bytesSent += byteLength(msg);
// Record measurements.
record(
"receiveNetwork/" + this.traceName,
this.implementationName,
mode,
this.trace.numOps,
[bytesSent]
);
}
/**
* Benchmark time of a user's receiving all
* the ops, which were generated (off the clock)
* by other user(s) according to the mode.
*/
async receiveTime(mode: Mode, msgs: Data[], finalState: unknown) {
const values = new Array<number>(getRecordedTrials());
values.fill(0);
for (let trial = -getWarmupTrials(); trial < getRecordedTrials(); trial++) {
// Between trials, force GC.
// See comment in sendMemorySingle().
await getMemoryUsed();
console.log("Starting receiveTime trial " + trial);
const receiver = new this.implementation(() => {},
seedrandom(SEED + "receiver"));
receiver.skipLoad();
// Prep measurement.
const startTime = process.hrtime.bigint();
// Receive all edits.
for (let i = 0; i < msgs.length; i++) {
receiver.receive(msgs[i]);
}
// Take measurement.
if (trial >= 0) {
values[trial] = new Number(
process.hrtime.bigint() - startTime!
).valueOf();
}
// Check final state.
assert.deepStrictEqual(
this.trace.getState(receiver),
finalState,
"receiver state does not equal sender state"
);
}
// Record measurements.
record(
"receiveTime/" + this.traceName,
this.implementationName,
mode,
this.trace.numOps,
values
);
}
/**
* Benchmark memory of a user after receiving all
* the ops, which were generated (off the clock)
* by other user(s) according to the mode.
*/
async receiveMemory(mode: Mode, msgs: Data[], finalState: unknown) {
const values = new Array<number>(getRecordedTrials());
values.fill(0);
let bases = new Array<number>(getRecordedTrials());
bases.fill(0);
for (let trial = -getWarmupTrials(); trial < getRecordedTrials(); trial++) {
// Between trials, force GC.
// See comment in sendMemorySingle().
await getMemoryUsed();
console.log("Starting receiveMemory trial " + trial);
const receiver = new this.implementation(() => {},
seedrandom(SEED + "receiver"));
receiver.skipLoad();
// Prep measurement.
bases[trial] = await getMemoryUsed();
// Receive all edits.
for (let i = 0; i < msgs.length; i++) {
receiver.receive(msgs[i]);
}
// Take measurement.
if (trial >= 0) {
values[trial] = await getMemoryUsed();
}
// Check final state.
assert.deepStrictEqual(
this.trace.getState(receiver),
finalState,
"receiver state does not equal sender state"
);
}
// Record measurements.
record(
"receiveMemory/" + this.traceName,
this.implementationName,
mode,
this.trace.numOps,
values,
bases
);
}
async receiveSave(mode: Mode, msgs: Data[], finalState: unknown) {
// Receive all messages.
const receiver = new this.implementation(() => {},
seedrandom(SEED + "receiver"));
receiver.skipLoad();
for (let i = 0; i < msgs.length; i++) {
receiver.receive(msgs[i]);
}
// Measure save time, save size, and load time for receiver.
await this.saveTime(receiver, "receiveSaveTime", mode);
const saveData = receiver.save();
record(
"receiveSaveSize/" + this.traceName,
this.implementationName,
mode,
this.trace.numOps,
[byteLength(saveData)]
);
await this.loadTime(saveData, finalState, "receiveLoadTime", mode);
}
private async saveTime(saver: Replica, metric: string, label: string) {
const values = new Array<number>(getRecordedTrials());
values.fill(0);
for (let trial = -getWarmupTrials(); trial < getRecordedTrials(); trial++) {
// Between trials, force GC.
await getMemoryUsed();
console.log("Starting saveTime trial " + trial);
// Prep measurement.
const startTime = process.hrtime.bigint();
// Save.
saver.save();
// Take measurements.
if (trial >= 0) {
values[trial] = new Number(
process.hrtime.bigint() - startTime!
).valueOf();
}
}
// Record measurements.
record(
metric + "/" + this.traceName,
this.implementationName,
label,
this.trace.numOps,
values
);
}
private async loadTime(
saveData: Data,
saverState: unknown,
metric: string,
label: string
) {
const values = new Array<number>(getRecordedTrials());
values.fill(0);
for (let trial = -getWarmupTrials(); trial < getRecordedTrials(); trial++) {
// Between trials, force GC.
await getMemoryUsed();
console.log("Starting loadTime trial " + trial);
// Prepare loader.
const loader = new this.implementation(() => {},
seedrandom(SEED + "loader"));
// Prep measurement.
const startTime = process.hrtime.bigint();
// Load.
loader.load(saveData);
// Take measurements.
if (trial >= 0) {
values[trial] = new Number(
process.hrtime.bigint() - startTime!
).valueOf();
}
// Check loaded state.
assert.deepStrictEqual(
this.trace.getState(loader),
saverState,
"loader state does not equal saver state"
);
}
// Record measurements.
record(
metric + "/" + this.traceName,
this.implementationName,
label,
this.trace.numOps,
values
);
}
} | the_stack |
import { expect as chaiExpect } from "chai";
import { parseCategories, parsePage, getProxyList } from "../src/parser";
import Torrent, { convertOrderByObject } from "../src";
import { baseUrl } from "../src/constants";
const testingUsername = "YIFY";
function torrentFactory() {
return Torrent.getTorrent("10676856");
}
function torrentSearchFactory() {
return Torrent.search("Game of Thrones", {
category: "205"
});
}
function torrentCommentsFactory() {
return Torrent.getComments("10676856");
}
function torrentCategoryFactory() {
return Torrent.getCategories();
}
function greaterThanOrEqualTo(first, second) {
return first > second || first === second;
}
function lessThanOrEqualToZero(first, second) {
return first < second || first === 0;
}
function assertHasArrayOfTorrents(arrayOfTorrents) {
chaiExpect(arrayOfTorrents).to.be.an("array");
chaiExpect(arrayOfTorrents[0]).to.be.an("object");
}
/**
* todo: test the 'torrentLink' property, which is undefined in many queries
*/
function assertHasNecessaryProperties(torrent, additionalProperties = []) {
const defaultPropertiesToValidate = [
"id",
"name",
"size",
"link",
"category",
"seeders",
"leechers",
"uploadDate",
"magnetLink",
"subcategory",
"uploader",
"verified",
"uploaderLink",
...additionalProperties
];
for (const property of defaultPropertiesToValidate) {
chaiExpect(torrent).to.have.property(property);
chaiExpect(torrent[property]).to.exist;
if (typeof torrent[property] === "string") {
chaiExpect(torrent[property]).to.not.contain("undefined");
}
}
}
describe("Torrent", () => {
describe("order object to number converter", () => {
it("should convert orderBy and sortBy with name", () => {
const searchNumber = convertOrderByObject({
orderBy: "name",
sortBy: "asc"
});
chaiExpect(searchNumber).to.equal(2);
});
it("should convert orderBy and sortBy with leechers", () => {
const searchNumber = convertOrderByObject({
orderBy: "leeches",
sortBy: "desc"
});
chaiExpect(searchNumber).to.equal(9);
});
});
describe("categories", function() {
beforeAll(async () => {
this.categories = await torrentCategoryFactory();
});
it("retrieves categories", async () => {
chaiExpect(this.categories).to.be.an("array");
});
it("retrieves categories with expected properties", async () => {
const properties = ["name", "id", "subcategories"];
for (const property of properties) {
chaiExpect(this.categories[0]).to.have.property(property);
chaiExpect(this.categories[0][property]).to.exist;
chaiExpect(this.categories[0][property]).to.not.contain("undefined");
}
});
});
describe("comments", function() {
beforeAll(async () => {
this.comments = await torrentCommentsFactory();
});
it("retrieves comments", async () => {
chaiExpect(this.comments).to.be.an("array");
});
it("retrieves comments with expected properties", async () => {
const properties = ["user", "comment"];
for (const property of properties) {
chaiExpect(this.comments[0])
.to.have.property(property)
.that.is.a("string");
}
});
});
/**
* @todo
*
* it('searches by page number', async () => {});
* it('searches by category', async () => {});
*/
describe("search", function() {
beforeAll(async () => {
this.search = await torrentSearchFactory();
});
it("searches for items", async () => {
assertHasArrayOfTorrents(this.search);
});
it("should have verified property", () => {
chaiExpect(this.search[0]).to.have.property("verified");
chaiExpect(this.search[0].verified).to.be.a("boolean");
});
it("should search un-verified", async () => {
const searchResults = await Torrent.search("Game of Thrones", {
category: "205",
filter: {
verified: false
}
});
for (const result of searchResults) {
chaiExpect(result)
.to.have.property("verified")
.that.is.a("boolean");
}
});
/**
* Assert by searching wrong
*/
it.skip("should search using primary category names", async function getCategoryNames() {
this.timeout(50000);
const searchResults = await Promise.all([
Torrent.search("Game of Thrones", {
category: "applications"
}),
Torrent.search("Game of Thrones", {
category: "audio"
}),
Torrent.search("Game of Thrones", {
category: "video"
}),
Torrent.search("Game of Thrones", {
category: "games"
}),
Torrent.search("Game of Thrones", {
category: "xxx"
}),
Torrent.search("Game of Thrones", {
category: "other"
})
]);
chaiExpect(searchResults[0][0].category.name).to.equal("Applications");
chaiExpect(searchResults[1][0].category.name).to.equal("Audio");
chaiExpect(searchResults[2][0].category.name).to.equal("Video");
chaiExpect(searchResults[3][0].category.name).to.equal("Games");
chaiExpect(searchResults[4][0].category.name).to.equal("Porn");
chaiExpect(searchResults[5][0].category.name).to.equal("Other");
});
it("should handle numerical values", async () => {
const searchResults = await Torrent.search("Game of Thrones", {
page: 1,
orderBy: "seeds",
sortBy: "asc"
});
assertHasNecessaryProperties(searchResults[0]);
});
it("should handle non-numerical values", async () => {
const searchResults = await Torrent.search("Game of Thrones", {
category: "all",
page: "1",
orderBy: "seeds",
sortBy: "asc"
});
assertHasNecessaryProperties(searchResults[0]);
});
it("should search with backwards compatible method", async () => {
const searchResults = await Torrent.search("Game of Thrones", {
orderBy: "8" // Search orderBy seeds, asc
});
assertHasNecessaryProperties(searchResults[0]);
lessThanOrEqualToZero(searchResults[0].seeders, searchResults[1].seeders);
lessThanOrEqualToZero(searchResults[1].seeders, searchResults[2].seeders);
lessThanOrEqualToZero(searchResults[3].seeders, searchResults[3].seeders);
});
it("retrieves expected properties", async () => {
assertHasNecessaryProperties(this.search[0]);
});
it("searches by sortBy: desc", async () => {
const searchResults = await Torrent.search("Game of Thrones", {
category: "205",
orderBy: "seeds",
sortBy: "desc"
});
greaterThanOrEqualTo(searchResults[0].seeders, searchResults[1].seeders);
greaterThanOrEqualTo(searchResults[1].seeders, searchResults[2].seeders);
greaterThanOrEqualTo(searchResults[3].seeders, searchResults[3].seeders);
});
it("searches by sortBy: asc", async () => {
const searchResults = await Torrent.search("Game of Thrones", {
category: "205",
orderBy: "seeds",
sortBy: "asc"
});
lessThanOrEqualToZero(searchResults[0].seeders, searchResults[1].seeders);
lessThanOrEqualToZero(searchResults[1].seeders, searchResults[2].seeders);
lessThanOrEqualToZero(searchResults[3].seeders, searchResults[3].seeders);
});
it("should get torrents, strict", async () => {
const searchResults = await Promise.all([
Torrent.search("Game of Thrones S01E08"),
Torrent.search("Game of Thrones S02E03"),
Torrent.search("Game of Thrones S03E03")
]);
for (const result of searchResults) {
chaiExpect(result).to.have.length.above(10);
chaiExpect(result[0])
.to.have.deep.property("seeders")
.that.is.greaterThan(20);
}
});
});
/**
* Get torrent types
*/
describe("torrent types", () => {
it("should get top torrents", async () => {
const torrents = await Torrent.topTorrents();
assertHasArrayOfTorrents(torrents);
assertHasNecessaryProperties(torrents[0]);
chaiExpect(torrents.length === 100).to.be.true;
});
it("should get recent torrents", async () => {
const torrents = await Torrent.recentTorrents();
assertHasArrayOfTorrents(torrents);
assertHasNecessaryProperties(torrents[0]);
chaiExpect(torrents).to.have.length.above(20);
});
it("should get users torrents", async () => {
const torrents = await Torrent.userTorrents(testingUsername);
assertHasArrayOfTorrents(torrents);
assertHasNecessaryProperties(torrents[0]);
});
});
//
// Original tests
//
/**
* Get torrents
*/
describe("Torrent.getTorrent(id)", function() {
beforeAll(async () => {
this.torrent = await torrentFactory();
});
it("should have no undefined properties", () => {
for (const property in this.torrent) { // eslint-disable-line
if (this.torrent.hasOwnProperty(property)) {
if (typeof this.torrent[property] === "string") {
chaiExpect(this.torrent[property]).to.not.include("undefined");
}
}
}
});
it("should return a promise", () => {
chaiExpect(torrentFactory()).to.be.a("promise");
});
it("should have a name", () => {
chaiExpect(this.torrent).to.have.property(
"name",
"The Amazing Spider-Man 2 (2014) 1080p BrRip x264 - YIFY"
);
});
it("should have uploader", () => {
chaiExpect(this.torrent).to.have.property("uploader", "YIFY");
});
it("should have uploader link", () => {
chaiExpect(this.torrent).to.have.property(
"uploaderLink",
`${baseUrl}/user/YIFY/`
);
});
it("should have an id", () => {
chaiExpect(this.torrent).to.have.property("id", "10676856");
});
it("should have upload date", () => {
chaiExpect(this.torrent).to.have.property(
"uploadDate",
"2014-08-02 08:15:25 GMT"
);
});
it("should have size", () => {
chaiExpect(this.torrent).to.have.property("size");
chaiExpect(this.torrent.size).to.match(/\d+\.\d+\s(G|M|K)iB/);
});
it("should have seeders and leechers count", () => {
chaiExpect(this.torrent).to.have.property("seeders");
chaiExpect(this.torrent).to.have.property("leechers");
chaiExpect(~~this.torrent.leechers).to.be.above(-1);
chaiExpect(~~this.torrent.seeders).to.be.above(-1);
});
it("should have a link", () => {
chaiExpect(this.torrent).to.have.property(
"link",
`${baseUrl}/torrent/10676856`
);
});
it("should have a magnet link", () => {
chaiExpect(this.torrent).to.have.property("magnetLink");
});
it("should have a description", () => {
chaiExpect(this.torrent).to.have.property("description");
chaiExpect(this.torrent.description).to.be.a("string");
});
});
/**
* Search
*/
describe("Torrent.search(title, opts)", function() {
beforeAll(async () => {
this.searchResults = await Torrent.search("Game of Thrones");
this.fistSearchResult = this.searchResults[0];
});
it("should return a promise", () => {
chaiExpect(Torrent.search("Game of Thrones")).to.be.a("promise");
});
it("should return an array of search results", () => {
chaiExpect(this.searchResults).to.be.an("array");
});
describe("search result", () => {
it("should have an id", () => {
chaiExpect(this.fistSearchResult).to.have.property("id");
chaiExpect(this.fistSearchResult.id).to.match(/^\d+$/);
});
it("should have a name", () => {
chaiExpect(this.fistSearchResult).to.have.property("name");
chaiExpect(this.fistSearchResult.name).to.match(/game.of.thrones/i);
});
it("should have upload date", () => {
chaiExpect(this.fistSearchResult).to.have.property("uploadDate");
/**
* Valid dates:
* 31 mins ago
* Today 02:18
* Y-day 22:14
* 02-10 03:36
* 06-21 2011
*/
chaiExpect(this.fistSearchResult.uploadDate).to.match(
/(\d*\smins\sago)|(Today|Y-day)\s\d\d:\d\d|\d\d-\d\d\s(\d\d:\d\d|\d{4})/
);
});
it("should have size", () => {
chaiExpect(this.fistSearchResult).to.have.property("size");
/**
* Valid sizes:
* 529.84 MiB
* 2.04 GiB
* 598.98 KiB
*/
chaiExpect(this.fistSearchResult.size).to.exist;
});
it("should have seeders and leechers count", () => {
chaiExpect(this.fistSearchResult).to.have.property("seeders");
chaiExpect(this.fistSearchResult).to.have.property("leechers");
chaiExpect(~~this.fistSearchResult.leechers).to.be.above(-1);
chaiExpect(~~this.fistSearchResult.seeders).to.be.above(-1);
});
it("should have a link", () => {
chaiExpect(this.fistSearchResult).to.have.property("link");
chaiExpect(this.fistSearchResult.link).to.match(
new RegExp(`${baseUrl}/torrent/\\d+/+`)
);
});
it("should have a magnet link", () => {
chaiExpect(this.fistSearchResult).to.have.property("magnetLink");
chaiExpect(this.fistSearchResult.magnetLink).to.match(/magnet:\?xt=.+/);
});
it("should have a category", () => {
chaiExpect(this.fistSearchResult).to.have.property("category");
chaiExpect(this.fistSearchResult.category.id).to.match(/[1-6]00/);
chaiExpect(this.fistSearchResult.category.name).to.match(/\w+/);
});
it("should have a subcategory", () => {
chaiExpect(this.fistSearchResult).to.have.property("subcategory");
chaiExpect(this.fistSearchResult.subcategory.id).to.match(
/[1-6][09][1-9]/
);
chaiExpect(this.fistSearchResult.subcategory.name).to.match(
/[a-zA-Z0-9 ()/-]/
);
});
it("should have an uploader and uploader link", () => {
chaiExpect(this.fistSearchResult).to.have.property("uploader");
chaiExpect(this.fistSearchResult).to.have.property("uploaderLink");
});
});
});
describe("Torrent.topTorrents(category, opts)", function() {
beforeAll(async () => {
this.topTorrents = await Torrent.topTorrents("205");
});
it("should return a promise", () => {
chaiExpect(Torrent.topTorrents("205")).to.be.a("promise");
});
it("should handle numeric input", async () => {
const topTorrents = await Torrent.topTorrents(205);
chaiExpect(topTorrents).to.be.an("array");
chaiExpect(topTorrents[0].category.name).to.be.equal("Video");
chaiExpect(topTorrents[0].subcategory.name).to.be.equal("TV shows");
});
it("should return an array of top torrents of the selected category", () => {
chaiExpect(this.topTorrents).to.be.an("array");
});
describe("search result", () => {
it("category and subcategory shoud match specified category", () => {
chaiExpect(this.topTorrents[0].category.name).to.be.equal("Video");
chaiExpect(this.topTorrents[0].subcategory.name).to.be.equal(
"TV shows"
);
});
});
});
describe("Torrent.recentTorrents()", function testRecentTorrents() {
beforeAll(async () => {
this.recentTorrents = await Torrent.recentTorrents();
});
it("should return a promise", () => {
chaiExpect(Torrent.recentTorrents()).to.be.a("promise");
});
it("should return an array of the most recent torrents", () => {
chaiExpect(this.recentTorrents).to.be.an("array");
});
describe("recent torrent", () => {
it("should be uploaded recently", () => {
const [recentTorrent] = this.recentTorrents;
chaiExpect(recentTorrent.uploadDate).to.exist;
});
});
});
describe("Torrent.getCategories()", function testGetCategories() {
beforeAll(async () => {
this.categories = await torrentCategoryFactory();
this.subcategory = this.categories[0].subcategories[0];
});
it("should return promise", () => {
chaiExpect(parsePage(`${baseUrl}/recent`, parseCategories)).to.be.a(
"promise"
);
});
it("should return an array of categories", () => {
chaiExpect(this.categories).to.be.an("array");
});
describe("category", () => {
it("should have an id", () => {
chaiExpect(this.categories[0]).to.have.property("id");
chaiExpect(this.categories[0].id).to.match(/\d00/);
});
it("should have a name", () => {
chaiExpect(this.categories[0]).to.have.property("name");
chaiExpect(this.categories[0].name).to.be.a("string");
});
it("name should match id", () => {
const video = this.categories.find(elem => elem.name === "Video");
chaiExpect(video.id).to.equal("200");
});
it("shold have subcategories array", () => {
chaiExpect(this.categories[0]).to.have.property("subcategories");
chaiExpect(this.categories[0].subcategories).to.be.an("array");
});
describe("subcategory", () => {
it("should have an id", () => {
chaiExpect(this.subcategory).to.have.property("id");
chaiExpect(this.subcategory.id).to.match(/\d{3}/);
});
it("should have a name", () => {
chaiExpect(this.subcategory).to.have.property("name");
chaiExpect(this.subcategory.name).to.be.a("string");
});
});
});
});
describe("Torrent.getComments()", function testGetComments() {
beforeAll(async () => {
this.comments = await torrentCommentsFactory();
});
it("should return promise", () => {
chaiExpect(Torrent.getComments("10676856")).to.be.a("promise");
});
it("should return an array of comment", () => {
chaiExpect(this.comments).to.be.an("array");
});
describe("comment", () => {
it("should have a user", () => {
chaiExpect(this.comments[0]).to.have.property("user");
chaiExpect(this.comments[0].user).to.be.a("string");
});
it("should have a comment", () => {
chaiExpect(this.comments[0]).to.have.property("comment");
chaiExpect(this.comments[0].comment).to.be.a("string");
});
});
});
/**
* User torrents
*/
describe("Torrent.userTorrents(userName, opts)", function testUserTorrents() {
beforeAll(async () => {
this.userTorrents = await Torrent.userTorrents("YIFY");
});
it("should return a promise", () => {
chaiExpect(Torrent.userTorrents("YIFY")).to.be.a("promise");
});
it("should return an array of the user torrents", () => {
chaiExpect(this.userTorrents).to.be.an("array");
});
describe("user torrent", () => {
it("should have a name", () => {
chaiExpect(this.userTorrents[0]).to.have.property("name");
});
it("should have upload date", () => {
chaiExpect(this.userTorrents[0]).to.have.property("uploadDate");
/*
* Valid dates:
* 31 mins ago
* Today 02:18
* Y-day 22:14
* 02-10 03:36
* 06-21 2011
*/
chaiExpect(this.userTorrents[0].uploadDate).to.match(
/(\d*\smins\sago)|(Today|Y-day)\s\d\d:\d\d|\d\d-\d\d\s(\d\d:\d\d|\d{4})/
);
});
it("should have size", () => {
chaiExpect(this.userTorrents[0]).to.have.property("size");
/*
* Valid sizes:
* 529.84 MiB
* 2.04 GiB
* 598.98 KiB
*/
chaiExpect(this.userTorrents[0].size).to.match(/\d+\.\d+\s(G|M|K)iB/);
});
it("should have seeders and leechers count", () => {
chaiExpect(this.userTorrents[0]).to.have.property("seeders");
chaiExpect(this.userTorrents[0]).to.have.property("leechers");
chaiExpect(~~this.userTorrents[0].leechers).to.be.above(-1);
chaiExpect(~~this.userTorrents[0].seeders).to.be.above(-1);
});
it("should have a link", () => {
chaiExpect(this.userTorrents[0]).to.have.property("link");
chaiExpect(this.userTorrents[0].link).to.match(
new RegExp(`${baseUrl}/torrent/\\d+/+`)
);
});
it("should have a magnet link", () => {
chaiExpect(this.userTorrents[0]).to.have.property("magnetLink");
chaiExpect(this.userTorrents[0].magnetLink).to.match(/magnet:\?xt=.+/);
});
it("should have a category", () => {
chaiExpect(this.userTorrents[0]).to.have.property("category");
chaiExpect(this.userTorrents[0].category.id).to.match(/[1-6]00/);
chaiExpect(this.userTorrents[0].category.name).to.match(/\w+/);
});
it("should have a subcategory", () => {
chaiExpect(this.userTorrents[0]).to.have.property("subcategory");
chaiExpect(this.userTorrents[0].subcategory.id).to.match(
/[1-6][09][1-9]/
);
chaiExpect(this.userTorrents[0].subcategory.name).to.match(
/[a-zA-Z0-9 ()/-]/
);
});
});
});
/**
* Get TV show
*/
describe("Torrent.getTvShow(id)", function testGetTvShow() {
beforeAll(async () => {
this.tvShow = await Torrent.getTvShow("2");
});
it("should return a promise", () => {
chaiExpect(Torrent.getTvShow("2")).to.be.a("promise");
});
describe("Helper Methods", () => {
it("getProxyList should return an array of links", async () => {
const list = await getProxyList();
chaiExpect(list).to.be.an("array");
for (const link of list) {
chaiExpect(link).to.be.a("string");
chaiExpect(link).to.contain("https://");
}
});
});
});
}); | the_stack |
import * as fs from "fs";
import * as path from "path";
import slash = require("slash");
import * as recursiveFs from "recursive-fs";
import * as yazl from "yazl";
import Adapter from "../utils/adapter/adapter"
import RequestManager from "../utils/request-manager"
import { CodePushUnauthorizedError } from "./code-push-error"
import FileUploadClient, { IProgress } from "appcenter-file-upload-client";
import { AccessKey, AccessKeyRequest, Account, App, AppCreationRequest, CollaboratorMap, Deployment, DeploymentMetrics, Headers, Package, PackageInfo, ReleaseUploadAssets, UploadReleaseProperties, CodePushError } from "./types";
interface JsonResponse {
headers: Headers;
body?: any;
}
interface PackageFile {
isTemporary: boolean;
path: string;
}
// A template string tag function that URL encodes the substituted values
function urlEncode(strings: TemplateStringsArray, ...values: string[]): string {
var result = "";
for (var i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += encodeURIComponent(values[i]);
}
}
return result;
}
class AccountManager {
public static AppPermission = {
OWNER: "Owner",
COLLABORATOR: "Collaborator"
};
private _accessKey: string;
private _requestManager: RequestManager;
private _adapter: Adapter;
private _fileUploadClient: FileUploadClient;
constructor(accessKey: string, customHeaders?: Headers, serverUrl?: string, proxy?: string) {
if (!accessKey) throw new CodePushUnauthorizedError("A token must be specified.");
this._accessKey = accessKey;
this._requestManager = new RequestManager(accessKey, customHeaders, serverUrl, proxy);
this._adapter = new Adapter(this._requestManager);
this._fileUploadClient = new FileUploadClient();
}
public get accessKey(): string {
return this._accessKey;
}
public async isAuthenticated(throwIfUnauthorized?: boolean): Promise<boolean> {
let res: JsonResponse;
let codePushError: CodePushError;
try {
res = await this._requestManager.get(urlEncode`/user`, false);
} catch (error) {
codePushError = error as CodePushError;
if (codePushError && (codePushError.statusCode !== RequestManager.ERROR_UNAUTHORIZED || throwIfUnauthorized)) {
throw codePushError;
}
}
const authenticated: boolean = !!res && !!res.body;
return authenticated;
}
// Access keys
public async addAccessKey(friendlyName: string, ttl?: number): Promise<AccessKey> {
if (!friendlyName) {
throw new CodePushUnauthorizedError("A name must be specified when adding an access key.");
}
const accessKeyRequest: AccessKeyRequest = {
description: friendlyName
};
const res: JsonResponse = await this._requestManager.post(urlEncode`/api_tokens`, JSON.stringify(accessKeyRequest), /*expectResponseBody=*/ true);
const accessKey = this._adapter.toLegacyAccessKey(res.body);
return accessKey;
}
public async getAccessKeys(): Promise<AccessKey[]> {
const res: JsonResponse = await this._requestManager.get(urlEncode`/api_tokens`);
const accessKeys = this._adapter.toLegacyAccessKeyList(res.body);
return accessKeys;
}
public async removeAccessKey(name: string): Promise<void> {
const accessKey = await this._adapter.resolveAccessKey(name);
await this._requestManager.del(urlEncode`/api_tokens/${accessKey.id}`);
return null;
}
// Account
public async getAccountInfo(): Promise<Account> {
const res: JsonResponse = await this._requestManager.get(urlEncode`/user`);
const accountInfo = this._adapter.toLegacyAccount(res.body);
return accountInfo;
}
// Apps
public async getApps(): Promise<App[]> {
const res: JsonResponse = await this._requestManager.get(urlEncode`/apps`);
const apps = await this._adapter.toLegacyApps(res.body);
return apps;
}
public async getApp(appName: string): Promise<App> {
const appParams = await this._adapter.parseApiAppName(appName);
const res: JsonResponse = await this._requestManager.get(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}`);
const app = await this._adapter.toLegacyApp(res.body);
return app;
}
public async addApp(appName: string, appOs: string, appPlatform: string, manuallyProvisionDeployments: boolean = false): Promise<App> {
var app: AppCreationRequest = {
name: appName,
os: appOs,
platform: appPlatform,
manuallyProvisionDeployments: manuallyProvisionDeployments
};
const apigatewayAppCreationRequest = this._adapter.toApigatewayAppCreationRequest(app);
const path = apigatewayAppCreationRequest.org ? `/orgs/${apigatewayAppCreationRequest.org}/apps` : `/apps`;
await this._requestManager.post(path, JSON.stringify(apigatewayAppCreationRequest.appcenterClientApp), /*expectResponseBody=*/ false);
if (!manuallyProvisionDeployments) {
await this._adapter.addStandardDeployments(appName);
}
return app;
}
public async removeApp(appName: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
await this._requestManager.del(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}`);
return null;
}
public async renameApp(oldAppName: string, newAppName: string): Promise<void> {
const { appOwner, appName } = await this._adapter.parseApiAppName(oldAppName);
const updatedApp = await this._adapter.getRenamedApp(newAppName, appOwner, appName);
await this._requestManager.patch(urlEncode`/apps/${appOwner}/${appName}`, JSON.stringify(updatedApp));
return null;
}
public async transferApp(appName: string, orgName: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
await this._requestManager.post(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/transfer/${orgName}`, /*requestBody=*/ null, /*expectResponseBody=*/ false);
return null;
}
// Collaborators
public async getCollaborators(appName: string): Promise<CollaboratorMap> {
const appParams = await this._adapter.parseApiAppName(appName);
const res: JsonResponse = await this._requestManager.get(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/users`);
const collaborators = await this._adapter.toLegacyCollaborators(res.body, appParams.appOwner);
return collaborators;
}
public async addCollaborator(appName: string, email: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
const userEmailRequest = {
user_email: email
};
await this._requestManager.post(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/invitations`, JSON.stringify(userEmailRequest), /*expectResponseBody=*/ false);
return null;
}
public async removeCollaborator(appName: string, email: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
await this._requestManager.del(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/invitations/${email}`);
return null;
}
// Deployments
public async addDeployment(appName: string, deploymentName: string): Promise<Deployment> {
const deployment = <Deployment>{ name: deploymentName };
const appParams = await this._adapter.parseApiAppName(appName);
const res = await this._requestManager.post(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/`, JSON.stringify(deployment), /*expectResponseBody=*/ true);
return this._adapter.toLegacyDeployment(res.body);
}
public async clearDeploymentHistory(appName: string, deploymentName: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
await this._requestManager.del(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}/releases`);
return null;
}
public async getDeployments(appName: string): Promise<Deployment[]> {
const appParams = await this._adapter.parseApiAppName(appName);
const res: JsonResponse = await this._requestManager.get(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/`);
return this._adapter.toLegacyDeployments(res.body);
}
public async getDeployment(appName: string, deploymentName: string): Promise<Deployment> {
const appParams = await this._adapter.parseApiAppName(appName);
const res: JsonResponse = await this._requestManager.get(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}`);
return this._adapter.toLegacyDeployment(res.body);
}
public async renameDeployment(appName: string, oldDeploymentName: string, newDeploymentName: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
await this._requestManager.patch(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${oldDeploymentName}`, JSON.stringify({ name: newDeploymentName }));
return null;
}
public async removeDeployment(appName: string, deploymentName: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
await this._requestManager.del(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}`);
return null;
}
public async getDeploymentMetrics(appName: string, deploymentName: string): Promise<DeploymentMetrics> {
const appParams = await this._adapter.parseApiAppName(appName);
const res = await this._requestManager.get(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}/metrics`);
const deploymentMetrics = this._adapter.toLegacyDeploymentMetrics(res.body);
return deploymentMetrics;
}
public async getDeploymentHistory(appName: string, deploymentName: string): Promise<Package[]> {
const appParams = await this._adapter.parseApiAppName(appName);
const res = await this._requestManager.get(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}/releases`);
return this._adapter.toLegacyDeploymentHistory(res.body);
}
// Releases
public async release(appName: string, deploymentName: string, filePath: string, targetBinaryVersion: string, updateMetadata: PackageInfo, uploadProgressCallback?: (progress: number) => void): Promise<Package> {
updateMetadata.appVersion = targetBinaryVersion;
const packageFile: PackageFile = await this.packageFileFromPath(filePath);
const appParams = await this._adapter.parseApiAppName(appName);
const assetJsonResponse: JsonResponse = await this._requestManager.post(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}/uploads`, null, true)
const assets = assetJsonResponse.body as ReleaseUploadAssets;
await this._fileUploadClient.upload({
assetId: assets.id,
assetDomain: assets.upload_domain,
assetToken: assets.token,
file: packageFile.path,
onProgressChanged: (progressData: IProgress) => {
if (uploadProgressCallback) {
uploadProgressCallback(progressData.percentCompleted);
}
},
});
const releaseUploadProperties: UploadReleaseProperties = this._adapter.toReleaseUploadProperties(updateMetadata, assets, deploymentName);
const releaseJsonResponse: JsonResponse = await this._requestManager.post(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}/releases`, JSON.stringify(releaseUploadProperties), true);
const releasePackage: Package = this._adapter.releaseToPackage(releaseJsonResponse.body);
return releasePackage;
}
public async patchRelease(appName: string, deploymentName: string, label: string, updateMetadata: PackageInfo): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
const requestBody = this._adapter.toRestReleaseModification(updateMetadata);
await this._requestManager.patch(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}/releases/${label}`, JSON.stringify(requestBody), /*expectResponseBody=*/ false)
return null;
}
public async promote(appName: string, sourceDeploymentName: string, destinationDeploymentName: string, updateMetadata: PackageInfo): Promise<Package> {
const appParams = await this._adapter.parseApiAppName(appName);
const requestBody = this._adapter.toRestReleaseModification(updateMetadata);
const res = await this._requestManager.post(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${sourceDeploymentName}/promote_release/${destinationDeploymentName}`, JSON.stringify(requestBody), /*expectResponseBody=*/ true);
const releasePackage: Package = this._adapter.releaseToPackage(res.body);
return releasePackage;
}
public async rollback(appName: string, deploymentName: string, targetRelease?: string): Promise<void> {
const appParams = await this._adapter.parseApiAppName(appName);
const requestBody = targetRelease ? {
label: targetRelease
} : {};
await this._requestManager.post(urlEncode`/apps/${appParams.appOwner}/${appParams.appName}/deployments/${deploymentName}/rollback_release`, JSON.stringify(requestBody), /*expectResponseBody=*/ false);
return null;
}
// Deprecated
public getAccessKey(accessKeyName: string): CodePushError {
throw {
message: 'Method is deprecated',
statusCode: 404
}
}
// Deprecated
public getSessions(): CodePushError {
throw this.getDeprecatedMethodError();
}
// Deprecated
public patchAccessKey(oldName: string, newName?: string, ttl?: number): CodePushError {
throw this.getDeprecatedMethodError();
}
// Deprecated
public removeSession(machineName: string): CodePushError {
throw this.getDeprecatedMethodError();
}
private packageFileFromPath(filePath: string): Promise<PackageFile> {
var getPackageFilePromise: Promise<PackageFile>;
if (fs.lstatSync(filePath).isDirectory()) {
getPackageFilePromise = new Promise<PackageFile>((resolve: (file: PackageFile) => void, reject: (reason: Error) => void): void => {
var directoryPath: string = filePath;
recursiveFs.readdirr(directoryPath, (error?: any, directories?: string[], files?: string[]): void => {
if (error) {
reject(error);
return;
}
var baseDirectoryPath = path.dirname(directoryPath);
var fileName: string = this.generateRandomFilename(15) + ".zip";
var zipFile = new yazl.ZipFile();
var writeStream: fs.WriteStream = fs.createWriteStream(fileName);
zipFile.outputStream.pipe(writeStream)
.on("error", (error: Error): void => {
reject(error);
})
.on("close", (): void => {
filePath = path.join(process.cwd(), fileName);
resolve({ isTemporary: true, path: filePath });
});
for (var i = 0; i < files.length; ++i) {
var file: string = files[i];
var relativePath: string = path.relative(baseDirectoryPath, file);
// yazl does not like backslash (\) in the metadata path.
relativePath = slash(relativePath);
zipFile.addFile(file, relativePath);
}
zipFile.end();
});
});
} else {
getPackageFilePromise = new Promise<PackageFile>((resolve: (file: PackageFile) => void, reject: (reason: Error) => void): void => {
resolve({ isTemporary: false, path: filePath });
});
}
return getPackageFilePromise;
}
private generateRandomFilename(length: number): string {
var filename: string = "";
var validChar: string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
filename += validChar.charAt(Math.floor(Math.random() * validChar.length));
}
return filename;
}
private getDeprecatedMethodError() {
return {
message: 'Method is deprecated',
statusCode: 404
};
}
}
export = AccountManager; | the_stack |
import * as React from "react";
import * as ReactDOM from "react-dom";
import Cells from "./containers/cells";
import ExNodes from "./containers/exnodes";
import Stickies from "./containers/stickies";
import Inputer from "./containers/inputer";
import {KeyPressble, IKeyPress} from "./mixins/key-pressble";
import Sheet from "./model/sheet";
import Operation from "./model/operation";
import Extension from "./model/extension";
import Sticky from "./model/sheet/sticky";
import Border from "./model/sheet/border";
import {OBJECT_TYPE} from "./model/sheet/object-type";
import {GridViewBar} from "./containers/scrollbar";
import {VERTICAL_ALIGN, TEXT_ALIGN, BORDER_POSITION, CellPoint} from "./model/common";
import {drag} from "./util/drag";
import {Point} from "./model/common";
import {operationResult} from "./model/lib/change";
import {pointToGridViewItem} from "./model/lib/select";
import {modelToRangeItem} from "./model/common/cell-range";
import {fitForTarget} from "./model/lib/fit-for-target";
import {applyMixins} from "./util/apply-mixins";
// スタイルシート読み込み
import "./css.js";
/**
* ドラッグ時にスクロールする処理
* @param {Sheet} sheet 表示情報
* @param {Operation} opeModel 操作情報
* @return {CellPoint} スクロール場所
*/
function dragScroll(sheet, opeModel) {
const opeItem = opeModel.opeItem;
const hoverItem = opeModel.hoverItem;
// 操作中オブジェクトがセルで無い場合、範囲選択しない
if ((!opeItem) || (opeItem.objectType !== OBJECT_TYPE.CELL)) {
return opeModel.scroll;
}
// ホバーアイテムがセルで無い場合、前回の範囲選択情報のままとする。
if ((!hoverItem) || (hoverItem.objectType !== OBJECT_TYPE.CELL)) {
return opeModel.scroll;
}
return fitForTarget(sheet, opeModel, hoverItem.cellPoint);
}
export interface IGridViewProps {
className?: string;
key?: any;
ref?: any;
sheet?: Sheet;
operation?: Operation;
extension?: Extension;
onChangeSheet?: (prevSheet: Sheet, nextSheet: Sheet) => Sheet;
onChangeOperation?: (prevOpe: Operation, nextOpe: Operation) => Operation;
}
export interface IGridViewState {
sheet: Sheet;
operation: Operation;
}
export class GridView extends React.Component<IGridViewProps, IGridViewState> implements KeyPressble {
public static displayName = "gridview";
public static defaultProps = {
sheet: new Sheet(),
operation: new Operation(),
extension: new Extension(),
onChangeSheet: (prevView, nextView) => { return nextView; },
onChangeOperation: (prevVOperation, nextOperation) => { return nextOperation; }
}
constructor(props: IGridViewProps, context) {
super(props, context);
this.state = {
sheet: this.props.sheet,
operation: this.props.operation
};
this._isTouched = false;
this._tColumnNo = 0;
this._tRowNo = 0;
this._unmounted = false;
}
_keyPress: IKeyPress;
_addKeyPressEvent: () => void;
_removeKeyPressEvent: () => void;
_isTouched:boolean;
_tColumnNo: number;
_tRowNo: number;
_unmounted: boolean;
componentWillReceiveProps(nextProps: IGridViewProps) {
this.setState((prevState, props) => {
if (this.props.sheet !== nextProps.sheet) {
prevState.sheet = nextProps.sheet;
}
if (this.props.operation !== nextProps.operation) {
prevState.operation = nextProps.operation;
}
return prevState;
});
}
/**
* マウスホイール処理
* @param {Object} e イベント引数
*/
_onMouseWheel = (e) => {
const opeModel = this.state.operation;
let value = opeModel.scroll.rowNo + Math.round(e.deltaY / 100) * 3;
if (value < 1) {
value = 1;
}
if (opeModel.scroll.rowNo !== value) {
this._isTouched = true;
this._tColumnNo = opeModel.scroll.columnNo;
this._tRowNo = value;
}
e.preventDefault();
}
_onContextMenu = (e) => {
e.preventDefault();
}
/**
* マウスアップ処理
*/
_onMouseUp = () => {
const opeModel = this.state.operation;
const sheet = this.state.sheet;
const nextSheet = operationResult(sheet, opeModel);
if (sheet !== nextSheet) {
this._onViewModelChange(nextSheet);
}
const ope = opeModel.setOpeItem(null);
this._onOperationChange(ope);
}
/**
* マウスダウン処理
* マウスの下にあるオブジェクトを検出し、選択処理等を行う
* @param {Object} e イベント引数
*/
_onMouseDown = (e) => {
// 右クリック時、何もしない
if (e.button === 2) {
return;
}
const sheet = this.state.sheet;
const opeModel = this.state.operation;
// テーブル上の座標を取得
const point = new Point(e.offsetX / sheet.scale, e.offsetY / sheet.scale);
const item = pointToGridViewItem(sheet, opeModel, point, false);
let ope = opeModel
.setSelectItem(item)
.setOpeItem(item);
if (this._keyPress.ctrl) {
ope = ope.pushClipRanges(ope.rangeItem);
}
else {
ope = ope.clearClipRanges();
}
ope = ope.setRangeItem(null);
const rangeItem = modelToRangeItem(sheet, ope);
const input = ope.input.setIsInputing(false);
this._onOperationChange(ope.setRangeItem(rangeItem).setInput(input));
}
_onMouseMove = (e) => {
const node = ReactDOM.findDOMNode(this.refs["gwcells"]);
const sheet = this.state.sheet;
const opeModel = this.state.operation;
const rect = node.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// テーブル上の座標を取得
const point = new Point(x / sheet.scale, y / sheet.scale);
const item = pointToGridViewItem(sheet, opeModel, point, true);
const ope = opeModel.setHoverItem(item);
const scroll = dragScroll(sheet, ope);
const rangeItem = modelToRangeItem(sheet, ope);
this._onOperationChange(ope.setRangeItem(rangeItem).setScroll(scroll));
}
_startOperation: Operation;
_startToucheClientX: number;
_startToucheClientY: number;
_startToucheIdentifier: number;
_touchDecided = () => {
if (this._unmounted){
return;
}
if (!this._isTouched){
requestAnimationFrame(this._touchDecided);
return;
}
const operation = this.state.operation;
const columnNo = this._tColumnNo;
const rowNo = this._tRowNo;
if ((operation.scroll.columnNo === columnNo) &&
(operation.scroll.rowNo === rowNo)){
this._isTouched = false;
requestAnimationFrame(this._touchDecided);
return;
}
const scroll = operation.scroll
.setColumnNo(columnNo)
.setRowNo(rowNo);
this._onOperationChange(operation.setScroll(scroll));
this._isTouched = false;
requestAnimationFrame(this._touchDecided);
}
_onTouchStart = (e:React.TouchEvent) => {
this._startToucheClientX = e.touches[0].clientX;
this._startToucheClientY = e.touches[0].clientY;
this._startToucheIdentifier = e.touches[0].identifier;
this._startOperation = this.state.operation;
}
_onTouchMove = (e:React.TouchEvent) => {
e.preventDefault();
if (e.touches.length < 1) {
return;
}
const touch = e.touches[0];
if (this._startToucheIdentifier !== touch.identifier) {
return;
}
const sheet = this.state.sheet;
const operation = this.state.operation;
const diffX = this._startToucheClientX - touch.clientX + sheet.rowHeader.width;
const diffY = this._startToucheClientY - touch.clientY + sheet.columnHeader.height;
const top = sheet.rowHeader.items.get(this._startOperation.scroll.rowNo).top;
const left = sheet.columnHeader.items.get(this._startOperation.scroll.columnNo).left;
let columnNo = sheet.pointToColumnNo(left + diffX / sheet.scale);
let rowNo = sheet.pointToRowNo(top + diffY / sheet.scale);
if (rowNo < 1) {
rowNo = 1;
}
if (columnNo < 1) {
columnNo = 1;
}
this._isTouched = true;
this._tColumnNo = columnNo;
this._tRowNo = rowNo;
}
componentDidMount() {
const node = ReactDOM.findDOMNode(this.refs["gwcells"]);
drag(node, this._onMouseDown, this._onMouseMove, this._onMouseUp);
this._addKeyPressEvent();
this._touchDecided();
}
componentWillUnmount() {
this._removeKeyPressEvent();
this._unmounted = true;
}
_onValueChange = (cellPoint, value) => {
const sheet = this.state.sheet
.setValue(cellPoint, value);
this._onViewModelChange(sheet);
}
_onViewModelChange = (sheet) => {
const prevSheet = this.state.sheet;
const nextSheet = this.props.onChangeSheet(prevSheet, sheet);
if (prevSheet === nextSheet) {
return;
}
this.setState((prevState, props) => {
prevState.sheet = nextSheet;
return prevState;
});
}
_onOperationChange = (ope) => {
const nextOpe = this.props.onChangeOperation(this.state.operation, ope);
if (this.state.operation === nextOpe) {
return;
}
this.setState((prevState, props) => {
prevState.operation = nextOpe;
return prevState;
});
}
_onStateChange = (sheet, operation) => {
this._onViewModelChange(sheet);
this._onOperationChange(operation);
}
render() {
const sheet = this.state.sheet;
const operation = this.state.operation;
const cellStyle = {
width: "100%",
height: "100%",
position: "relative",
zIndex: 2,
background: "#FFF",
cursor: operation.hoverCursor
};
let className = "react-sheet";
if (this.props.className) {
className = className + " " + this.props.className;
}
return (
<div className={className} ref="gridview"
onWheel={this._onMouseWheel} onContextMenu={this._onContextMenu}>
<div style={cellStyle} ref="gwcells" onMouseMove={this._onMouseMove} onTouchStart={this._onTouchStart} onTouchMove={this._onTouchMove}>
<Cells onOperationChange={this._onOperationChange}
sheet={sheet} opeModel={operation}/>
<ExNodes sheet={sheet} operation={operation} extension={this.props.extension} />
<Stickies sheet={sheet} operation={operation} extension={this.props.extension} />
</div>
<Inputer ref="inputer" opeModel={operation} sheet={sheet}
onValueChange={this._onValueChange} onStateChange={this._onStateChange}/>
<GridViewBar sheet={sheet} opeModel={operation} onOperationChange={this._onOperationChange}/>
</div>
);
}
}
applyMixins(GridView, [KeyPressble]); | the_stack |
import {
useRef,
useState,
useCallback,
SyntheticEvent,
ClipboardEvent,
FormEvent,
useEffect,
useLayoutEffect,
} from 'react';
import _uniq from 'lodash/uniq';
import _difference from 'lodash/difference';
import _includes from 'lodash/includes';
import { find as linkifyFind } from 'linkifyjs';
import { useDebouncedCallback } from 'use-debounce';
import { BaseEmoji, EmojiData } from 'emoji-mart';
import { UploadState } from 'react-file-utils';
import { NewActivity, OGAPIResponse, StreamClient, UR } from 'getstream';
import { DefaultAT, DefaultUT, useStreamContext } from '../../context';
import { StatusUpdateFormProps } from './StatusUpdateForm';
import {
generateRandomId,
dataTransferItemsToFiles,
dataTransferItemsHaveFiles,
inputValueFromEvent,
} from '../../utils';
import { NetworkRequestTypes } from 'utils/errors';
type Og = {
dismissed: boolean;
scrapingActive: boolean;
data?: OGAPIResponse;
};
export type FileUploadState = {
file: File | Blob;
id: string;
state: UploadState;
url?: string;
};
export type ImageUploadState = FileUploadState & { previewUri?: string };
type OgState = { activeUrl: string; data: Record<string, Og>; order: string[] };
type ImagesState = { data: Record<string, ImageUploadState>; order: string[] };
type FilesState = { data: Record<string, FileUploadState>; order: string[] };
type UseOgProps = { client: StreamClient; logErr: (e: Error | unknown, type: NetworkRequestTypes) => void };
type UseUploadProps = UseOgProps;
const defaultOgState = { activeUrl: '', data: {}, order: [] };
const defaultImageState = { data: {}, order: [] };
const defaultFileState = { data: {}, order: [] };
const useTextArea = () => {
const [text, setText] = useState('');
const [curser, setCurser] = useState<number | null>(null);
const textInputRef = useRef<HTMLTextAreaElement>();
const insertText = useCallback((insertedText: string) => {
setText((prevText) => {
const textareaElement = textInputRef.current;
if (!textareaElement) {
setCurser(null);
return prevText + insertedText;
}
// Insert emoji at previous cursor position
const { selectionStart, selectionEnd } = textareaElement;
setCurser(selectionStart + insertedText.length);
return prevText.slice(0, selectionStart) + insertedText + prevText.slice(selectionEnd);
});
}, []);
const onSelectEmoji = useCallback((emoji: EmojiData) => insertText((emoji as BaseEmoji).native), []);
useLayoutEffect(() => {
// Update cursorPosition after insertText is fired
const textareaElement = textInputRef.current;
if (textareaElement && curser !== null) {
textareaElement.selectionStart = curser;
textareaElement.selectionEnd = curser;
}
}, [curser]);
return { text, setText, insertText, onSelectEmoji, textInputRef };
};
const useOg = ({ client, logErr }: UseOgProps) => {
const [og, setOg] = useState<OgState>(defaultOgState);
const reqInProgress = useRef<Record<string, boolean>>({});
const activeOg = og.data[og.activeUrl]?.data;
const orderedOgStates = og.order.map((url) => og.data[url]).filter(Boolean);
const isOgScraping = orderedOgStates.some((state) => state.scrapingActive);
const availableOg = orderedOgStates.map((state) => state.data).filter(Boolean) as OGAPIResponse[];
const resetOg = useCallback(() => setOg(defaultOgState), []);
const setActiveOg = useCallback((url: string) => {
if (url) {
setOg((prevState) => {
prevState.data[url].dismissed = false;
return { ...prevState, activeUrl: url };
});
}
}, []);
const dismissOg = useCallback((e?: SyntheticEvent) => {
e?.preventDefault();
setOg((prevState) => {
for (const url in prevState.data) {
prevState.data[url].dismissed = true;
}
return { ...prevState, activeUrl: '' };
});
}, []);
const handleOG = useCallback((text: string) => {
const urls = _uniq(linkifyFind(text, 'url').map((info) => info.href));
// removed delete ogs from state and add the new urls
setOg((prevState) => {
const newUrls = _difference(urls, prevState.order);
const removedUrls = _difference(prevState.order, urls);
if (!_includes(urls, prevState.activeUrl)) {
prevState.activeUrl = '';
for (const url of urls) {
const og = prevState.data[url];
if (og?.data && !og.dismissed) {
prevState.activeUrl = url;
break;
}
}
}
for (const url of removedUrls) {
delete prevState.data[url];
}
for (const url of newUrls) {
prevState.data[url] = { scrapingActive: true, dismissed: false };
}
return { ...prevState, order: urls };
});
}, []);
const handleOgDebounced = useDebouncedCallback(handleOG, 750, { leading: true, trailing: true });
useEffect(() => {
og.order
.filter((url) => !reqInProgress.current[url] && og.data[url].scrapingActive)
.forEach(async (url) => {
reqInProgress.current[url] = true;
try {
const resp = await client.og(url);
resp.url = url;
setOg((prevState) => {
prevState.data[url] = { ...prevState.data[url], data: resp, scrapingActive: false, dismissed: false };
prevState.activeUrl = prevState.activeUrl || url;
return { ...prevState };
});
} catch (e) {
console.warn(e);
logErr(e, 'get-og');
setOg((prevState) => {
prevState.data[url] = { ...prevState.data[url], scrapingActive: false, dismissed: false };
return { ...prevState };
});
}
delete reqInProgress.current[url];
});
}, [og.order]);
return {
og,
activeOg,
setActiveOg,
resetOg,
availableOg,
orderedOgStates,
isOgScraping,
handleOgDebounced,
dismissOg,
ogActiveUrl: og.activeUrl,
};
};
const useUpload = ({ client, logErr }: UseUploadProps) => {
const [images, setImages] = useState<ImagesState>(defaultImageState);
const [files, setFiles] = useState<FilesState>(defaultFileState);
const reqInProgress = useRef<Record<string, boolean>>({});
const orderedImages = images.order.map((id) => images.data[id]);
const uploadedImages = orderedImages.filter((upload) => upload.url);
const orderedFiles = files.order.map((id) => files.data[id]);
const uploadedFiles = orderedFiles.filter((upload) => upload.url);
const resetUpload = useCallback(() => {
setImages(defaultImageState);
setFiles(defaultFileState);
}, []);
const uploadNewImage = useCallback((file: File | Blob) => {
const id = generateRandomId();
setImages(({ order, data }) => {
data[id] = { id, file, state: 'uploading' };
return { data: { ...data }, order: [...order, id] };
});
if (FileReader) {
// TODO: Possibly use URL.createObjectURL instead. However, then we need
// to release the previews when not used anymore though.
const reader = new FileReader();
reader.onload = (event) => {
const previewUri = event.target?.result as string;
if (!previewUri) return;
setImages((prevState) => {
if (!prevState.data[id]) return prevState;
prevState.data[id].previewUri = previewUri;
return { ...prevState, data: { ...prevState.data } };
});
};
reader.readAsDataURL(file);
}
}, []);
const uploadNewFile = useCallback((file: File) => {
const id = generateRandomId();
setFiles(({ order, data }) => {
data[id] = { id, file, state: 'uploading' };
return { data: { ...data }, order: [...order, id] };
});
}, []);
const uploadImage = useCallback(async (id: string, img: ImageUploadState) => {
setImages((prevState) => {
if (!prevState.data[id]) return prevState;
prevState.data[id].state = 'uploading';
return { ...prevState };
});
try {
const { file: url } = await client.images.upload(img.file as File);
setImages((prevState) => {
if (!prevState.data[id]) return prevState;
prevState.data[id].url = url;
prevState.data[id].state = 'finished';
return { ...prevState };
});
} catch (e) {
console.warn(e);
setImages((prevState) => {
if (!prevState.data[id]) return prevState;
logErr(e, 'upload-image');
prevState.data[id].state = 'failed';
return { ...prevState };
});
}
}, []);
const uploadFile = useCallback(async (id: string, file: FileUploadState) => {
setFiles((prevState) => {
if (!prevState.data[id]) return prevState;
prevState.data[id].state = 'uploading';
return { ...prevState, data: { ...prevState.data } };
});
try {
const { file: url } = await client.files.upload(file.file as File);
setFiles((prevState) => {
if (!prevState.data[id]) return prevState;
prevState.data[id].url = url;
prevState.data[id].state = 'finished';
return { ...prevState, data: { ...prevState.data } };
});
} catch (e) {
console.warn(e);
setFiles((prevState) => {
if (!prevState.data[id]) return prevState;
logErr(e, 'upload-file');
prevState.data[id].state = 'failed';
return { ...prevState, data: { ...prevState.data } };
});
}
}, []);
const uploadNewFiles = useCallback((files: Blob[] | File[] | FileList) => {
for (let i = 0; i < files.length; i += 1) {
const file = files[i];
if (file.type.startsWith('image/')) {
uploadNewImage(file);
} else if (file instanceof File) {
uploadNewFile(file);
}
}
}, []);
const removeImage = useCallback((id: string) => {
setImages((prevState) => {
prevState.order = prevState.order.filter((oid) => id !== oid);
delete prevState.data[id];
return { ...prevState };
});
}, []);
const removeFile = useCallback((id: string) => {
// eslint-disable-next-line sonarjs/no-identical-functions
setFiles((prevState) => {
prevState.order = prevState.order.filter((oid) => id !== oid);
delete prevState.data[id];
return { ...prevState };
});
}, []);
useEffect(() => {
images.order
.filter((id) => !reqInProgress.current[id] && images.data[id].state === 'uploading')
.forEach(async (id) => {
reqInProgress.current[id] = true;
await uploadImage(id, images.data[id]);
delete reqInProgress.current[id];
});
}, [images.order]);
useEffect(() => {
files.order
.filter((id) => !reqInProgress.current[id] && files.data[id].state === 'uploading')
.forEach(async (id) => {
reqInProgress.current[id] = true;
await uploadFile(id, files.data[id]);
delete reqInProgress.current[id];
});
}, [files.order]);
return {
images,
files,
orderedImages,
orderedFiles,
uploadedImages,
uploadedFiles,
resetUpload,
uploadNewFiles,
uploadFile,
uploadImage,
removeFile,
removeImage,
};
};
export function useStatusUpdateForm<
UT extends DefaultUT = DefaultUT,
AT extends DefaultAT = DefaultAT,
CT extends UR = UR,
RT extends UR = UR,
CRT extends UR = UR,
PT extends UR = UR
>({
activityVerb,
feedGroup,
modifyActivityData,
doRequest,
userId,
onSuccess,
}: { activityVerb: string; feedGroup: string } & Pick<
StatusUpdateFormProps<AT>,
'doRequest' | 'modifyActivityData' | 'onSuccess' | 'userId'
>) {
const [submitting, setSubmitting] = useState(false);
const appCtx = useStreamContext<UT, AT, CT, RT, CRT, PT>();
const client = appCtx.client as StreamClient<UT, AT, CT, RT, CRT, PT>;
const userData = (appCtx.user?.data || {}) as UT;
const logErr: UseOgProps['logErr'] = useCallback(
(e, type) => appCtx.errorHandler(e, type, { userId, feedGroup }),
[],
);
const { text, setText, insertText, onSelectEmoji, textInputRef } = useTextArea();
const {
resetOg,
setActiveOg,
ogActiveUrl,
activeOg,
dismissOg,
availableOg,
isOgScraping,
handleOgDebounced,
} = useOg({ client: client as StreamClient, logErr });
const {
images,
files,
orderedImages,
orderedFiles,
uploadedImages,
uploadedFiles,
resetUpload,
uploadNewFiles,
uploadFile,
uploadImage,
removeFile,
removeImage,
} = useUpload({ client: client as StreamClient, logErr });
const resetState = useCallback(() => {
setText('');
setSubmitting(false);
resetOg();
resetUpload();
}, []);
const object = () => {
for (const image of orderedImages) {
if (image.url) return image.url;
}
return text.trim();
};
const canSubmit = () =>
!submitting &&
Boolean(object()) &&
orderedImages.every((upload) => upload.state !== 'uploading') &&
orderedFiles.every((upload) => upload.state !== 'uploading') &&
!isOgScraping;
const addActivity = async () => {
// FIXME:
// @ts-expect-error
const activity: NewActivity<AT> = {
actor: client.currentUser?.ref() as string,
object: object(),
verb: activityVerb,
text: text.trim(),
attachments: {
og: activeOg,
images: uploadedImages.map((image) => image.url).filter(Boolean) as string[],
files: uploadedFiles.map((upload) => ({
// url will never actually be empty string because uploadedFiles
// filters those out.
url: upload.url as string,
name: (upload.file as File).name,
mimeType: upload.file.type,
})),
},
};
const modifiedActivity = modifyActivityData ? modifyActivityData(activity) : activity;
if (doRequest) {
return await doRequest(modifiedActivity);
} else {
return await client.feed(feedGroup, userId).addActivity(modifiedActivity);
}
};
const onSubmitForm = async (e: FormEvent) => {
e.preventDefault();
try {
setSubmitting(true);
const response = await addActivity();
resetState();
if (onSuccess) onSuccess(response);
} catch (e) {
setSubmitting(false);
logErr(e, 'add-activity');
}
};
const onChange = useCallback((event: SyntheticEvent<HTMLTextAreaElement>) => {
const text = inputValueFromEvent(event, true);
if (text === null || text === undefined) return;
setText(text);
handleOgDebounced(text);
}, []);
const onPaste = useCallback(async (event: ClipboardEvent<HTMLTextAreaElement>) => {
const { items } = event.clipboardData;
if (!dataTransferItemsHaveFiles(items)) return;
event.preventDefault();
// Get a promise for the plain text in case no files are
// found. This needs to be done here because chrome cleans
// up the DataTransferItems after resolving of a promise.
let plainTextPromise: Promise<string> | undefined;
for (let i = 0; i < items.length; i += 1) {
const item = items[i];
if (item.kind === 'string' && item.type === 'text/plain') {
plainTextPromise = new Promise((resolve) => item.getAsString(resolve));
break;
}
}
const fileLikes = await dataTransferItemsToFiles(items);
if (fileLikes.length) {
uploadNewFiles(fileLikes);
return;
}
// fallback to regular text paste
if (plainTextPromise) {
const s = await plainTextPromise;
insertText(s);
}
}, []);
return {
userData,
textInputRef,
text,
submitting,
files,
images,
activeOg,
availableOg,
isOgScraping,
ogActiveUrl,
onSubmitForm,
onSelectEmoji,
insertText,
onChange,
dismissOg,
setActiveOg,
canSubmit,
uploadNewFiles,
uploadFile,
uploadImage,
removeFile,
removeImage,
onPaste,
};
} | the_stack |
module WinJSTests {
"use strict";
var testHost;
var lv;
function generateListView(host, rowsPerPage, columnsPerPage, pages, options?) {
rowsPerPage = Math.max(rowsPerPage | 0, 1);
columnsPerPage = Math.max(columnsPerPage | 0, 1);
pages = Math.max(pages | 0, 1);
options = options || {};
var controlHeight = 600;
var controlWidth = 600;
//This calculation is accurate for the first page. Starting margins
// can cause more columns per page on page 2+
var itemHeight = controlHeight / rowsPerPage - 10; //10px total margin per item
var itemWidth = (controlWidth - 70) / columnsPerPage; //70px starting margin
function template(itemPromise) {
var el = document.createElement("div");
el.style.height = itemHeight + "px";
el.style.width = itemWidth + "px";
itemPromise.then(function (item) {
el.textContent = item.index;
});
return el;
}
options.itemTemplate = template;
var itemCount = rowsPerPage * columnsPerPage * pages;
var myList: any = [];
for (var i = 0; i < itemCount; i++) {
myList.push({ index: i });
}
myList = new WinJS.Binding.List(myList);
options.itemDataSource = myList.dataSource;
options.layout = new WinJS.UI.ListLayout({ orientation: 'horizontal' });
var lv = new WinJS.UI.ListView(null, options);
lv.element.style.height = controlHeight + "px";
lv.element.style.width = controlWidth + "px";
host.appendChild(lv.element);
lv['testOptions'] = {
rowsPerPage: rowsPerPage,
columnsPerPage: columnsPerPage,
pages: pages
};
return lv;
}
function checkFirstLastVisible(lv) {
LiveUnit.Assert.areEqual(Helper.ListView.Utils.getFirstVisibleElement(lv).querySelector(".win-item").innerHTML, lv.elementFromIndex(lv.indexOfFirstVisible).innerHTML);
LiveUnit.Assert.areEqual(Helper.ListView.Utils.getLastVisibleElement(lv).querySelector(".win-item").innerHTML, lv.elementFromIndex(lv.indexOfLastVisible).innerHTML);
}
function setScrollAndWait(scrollLeft) {
var viewport = lv._viewport;
return new WinJS.Promise(function (c) {
viewport.addEventListener("scroll", function handleScroll() {
viewport.removeEventListener("scroll", handleScroll);
lv.addEventListener("loadingstatechanged", function handleLoadingState() {
if (lv.loadingState === "viewPortLoaded") {
lv.removeEventListener("loadingstatechanged", handleLoadingState);
c();
}
});
});
WinJS.Utilities.setScrollPosition(viewport, { scrollLeft: scrollLeft, scrollTop: 0 });
});
}
export class HorizontalListTest {
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
var newNode = document.createElement("div");
newNode.id = "HorizontalListTest";
newNode.style.width = "600px";
newNode.style.height = "600px";
document.body.appendChild(newNode);
testHost = newNode;
lv = null;
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
var element = document.getElementById("HorizontalListTest");
if (element && document.body.contains(element)) {
WinJS.Utilities.disposeSubTree(element);
document.body.removeChild(element);
}
lv = null;
}
}
// Test generator
function generateTest(name, testFunction) {
var configurations = [
{
rowsPerPage: 1,
columnsPerPage: 1,
pages: 5
},
{
rowsPerPage: 1,
columnsPerPage: 2,
pages: 3
},
{
rowsPerPage: 1,
columnsPerPage: 3,
pages: 5
},
{
rowsPerPage: 1,
columnsPerPage: 5,
pages: 3
},
{
rowsPerPage: 1,
columnsPerPage: 1,
pages: 5
}
];
configurations.forEach(function (options) {
var testName = name + "_HList_" + options.rowsPerPage + 'X' + options.columnsPerPage + 'X' + options.pages;
HorizontalListTest.prototype[testName] = function (complete) {
lv = generateListView(testHost, options.rowsPerPage, options.columnsPerPage, options.pages);
testFunction.call(null, complete);
};
});
};
// Test cases
generateTest("testGetScrollPosition", function (complete) {
var viewport = lv.element.querySelector(".win-viewport");
var scrollPositions;
var scrollIndex;
Helper.ListView.Utils.waitForReady(lv)().done(function () {
Helper.asyncWhile(function () {
if (!scrollPositions) {
var scrollMax = viewport.scrollWidth - viewport.clientWidth;
scrollPositions = [50, Math.floor(scrollMax / 2), scrollMax];
scrollIndex = 0;
} else {
scrollIndex++;
}
return WinJS.Promise.wrap(scrollIndex < scrollPositions.length);
}, function () {
return new WinJS.Promise(function (c) {
var targetScrollPosition = scrollPositions[scrollIndex];
setScrollAndWait(targetScrollPosition).done(function () {
LiveUnit.Assert.areEqual(targetScrollPosition, lv.scrollPosition);
c();
});
});
}).done(complete);
});
});
generateTest("testSetScrollPosition", function (complete) {
var viewport = lv.element.querySelector(".win-viewport");
var scrollMax = 0;
var increment = 50;
Helper.ListView.Utils.waitForReady(lv)().done(function () {
Helper.asyncWhile(function () {
scrollMax = viewport.scrollWidth - viewport.clientWidth;
return WinJS.Promise.wrap(WinJS.Utilities.getScrollPosition(viewport).scrollLeft < scrollMax);
}, function () {
return new WinJS.Promise(function (c) {
var targetScrollPosition = Math.min(WinJS.Utilities.getScrollPosition(viewport).scrollLeft + increment, scrollMax);
lv.scrollPosition = targetScrollPosition;
Helper.ListView.Utils.waitForReady(lv)().done(function () {
LiveUnit.Assert.areEqual(targetScrollPosition, WinJS.Utilities.getScrollPosition(viewport).scrollLeft);
c();
});
});
}).done(complete);
});
});
generateTest("testGetIndexOfFirstLastVisible", function (complete) {
var viewport = lv.element.querySelector(".win-viewport");
var scrollPositions;
var scrollIndex;
Helper.ListView.Utils.waitForReady(lv)().done(function () {
Helper.asyncWhile(function () {
if (!scrollPositions) {
var scrollMax = viewport.scrollWidth - viewport.clientWidth;
scrollPositions = [50, Math.floor(scrollMax / 2), scrollMax];
scrollIndex = 0;
} else {
scrollIndex++;
}
return WinJS.Promise.wrap(scrollIndex < scrollPositions.length);
}, function () {
return new WinJS.Promise(function (c) {
var targetScrollPosition = scrollPositions[scrollIndex];
setScrollAndWait(targetScrollPosition).done(function () {
checkFirstLastVisible(lv);
c();
});
});
}).done(complete);
});
});
generateTest("testSetIndexOfFirstVisible", function (complete) {
var columnsPerPage = lv.testOptions.columnsPerPage;
var rowsPerPage = lv.testOptions.rowsPerPage;
var pages = lv.testOptions.pages;
var itemCount = columnsPerPage * rowsPerPage * pages;
var maxFirstVisibleIndex = itemCount - ((1 + columnsPerPage) * rowsPerPage); // Skip the last page and 1 column
Helper.ListView.Utils.waitForReady(lv)().done(function () {
Helper.asyncWhile(function () {
return WinJS.Promise.wrap(lv.indexOfFirstVisible < maxFirstVisibleIndex);
}, function () {
return new WinJS.Promise(function (c) {
var expectedIndexOfFirstVisible = Math.min(maxFirstVisibleIndex, Math.max(0, lv.indexOfFirstVisible) + rowsPerPage);
lv.indexOfFirstVisible = expectedIndexOfFirstVisible;
Helper.ListView.Utils.waitForReady(lv)().done(function () {
LiveUnit.Assert.areEqual(expectedIndexOfFirstVisible, lv.indexOfFirstVisible, "Read value is different after setting");
checkFirstLastVisible(lv);
c();
});
});
}).done(complete);
});
});
generateTest("testEnsureVisible", function (complete) {
var columnsPerPage = lv.testOptions.columnsPerPage;
var rowsPerPage = lv.testOptions.rowsPerPage;
var pages = lv.testOptions.pages;
var itemCount = columnsPerPage * rowsPerPage * pages;
var ensureVisibleTargets = [
0, // start
((itemCount / 2) | 0) - 1, // middle
itemCount - 1 // end
];
Helper.asyncWhile(function () {
return WinJS.Promise.wrap(ensureVisibleTargets.length > 0);
}, function () {
return new WinJS.Promise(function (c) {
var ensureVisibleIndex = ensureVisibleTargets.pop();
lv.ensureVisible(ensureVisibleIndex);
Helper.ListView.Utils.waitForReady(lv)().done(function () {
LiveUnit.Assert.isTrue(ensureVisibleIndex >= lv.indexOfFirstVisible, "Index of first visible should be less than or eq to ensured visible item index");
LiveUnit.Assert.isTrue(ensureVisibleIndex <= lv.indexOfLastVisible, "Index of first visible should be greater than or eq to ensured visible item index");
c();
});
});
}).done(complete);
});
}
// register the object as a test class by passing in the name
LiveUnit.registerTestClass("WinJSTests.HorizontalListTest"); | the_stack |
import { Injectable } from '@angular/core';
import { Observable, Subject, from, of, BehaviorSubject, forkJoin, empty } from 'rxjs';
import { concatMap, map, tap, switchMap } from 'rxjs/operators';
import { TreeNode } from './interfaces/tree-node';
import { TreeService } from './interfaces/tree-service';
import { NodeMenuItemAction, TreeMenuActionEvent } from './interfaces/tree-menu';
@Injectable()
export class TreeStore {
nodeMenuActionEvent$: Subject<TreeMenuActionEvent> = new Subject<TreeMenuActionEvent>();
nodeSelectedInner$: Subject<Partial<TreeNode>> = new Subject<Partial<TreeNode>>();
nodeInlineCreated$: Subject<TreeNode> = new Subject<TreeNode>();
nodeCut$: Subject<TreeNode> = new Subject<TreeNode>();
nodeCopied$: Subject<TreeNode> = new Subject<TreeNode>();
nodePasted$: Subject<TreeNode> = new Subject<TreeNode>();
scrollToSelectedNode$: BehaviorSubject<TreeNode> = new BehaviorSubject<TreeNode>(new TreeNode());
/**
* The dictionary of the node children subject with key of parent node's id.
*
* Each tree-children component will get the corresponding subject by node id to subscribe and show the node children
*
*/
private subjectOfNodeChildrenDictionary: { [nodeId: string]: Subject<TreeNode[]> } = {};
/**
* This dictionary of node's children with key of parent node Id
*
* The whole tree nodes data will be store in this dictionary
*
* ex nodes[parentId] = array of node's children
*/
private nodeChildrenDictionary: { [nodeId: string]: TreeNode[] } = {};
private selectedNode: Partial<TreeNode>;
/**
* Default Id: `0` in case node id is undefined or null
*/
private readonly DEFAULT_NODE_ID: string = '0';
constructor(private treeService: TreeService) { }
getSelectedNode(): Partial<TreeNode> {
return this.selectedNode;
}
setSelectedNode(node: Partial<TreeNode>) {
node.isSelected = true;
this.selectedNode = node;
}
/**
* This method will get the corresponding subject node children of parent node's id
*
* The `treeNodesRxSubject$` Subject of node's children with key of node's id.
*
* @returns Return the `Subject` of node's children by which each tree-children component will get the corresponding subject by node id to subscribe and show the node children
*/
getSubjectOfNodeChildren(nodeId: string): Subject<TreeNode[]> {
if (!this.subjectOfNodeChildrenDictionary.hasOwnProperty(nodeId)) {
this.subjectOfNodeChildrenDictionary[nodeId] = new Subject<TreeNode[]>();
}
return this.subjectOfNodeChildrenDictionary[nodeId];
}
/**
* Gets node children based on parent node id. Check if the node children was loaded
* @param parentId
* @returns tree children data
*/
getNodeChildren(parentId: string): Observable<TreeNode[]> {
if (this.nodeChildrenDictionary[parentId]) { return of(this.nodeChildrenDictionary[parentId]); }
return this.fetchNodeChildren(parentId);
}
/**
* Reload whole the tree including tree node children and parent node
* @param subTreeRootId
*/
reloadTreeChildrenData(subTreeRootId: string) {
if (!subTreeRootId) { subTreeRootId = this.DEFAULT_NODE_ID; }
// Reload the root node of sub tree
forkJoin(this.fetchNodeData(subTreeRootId), this.fetchNodeChildren(subTreeRootId))
.subscribe(([subTreeRootNode, nodeChildren]: [TreeNode, TreeNode[]]) => {
this.getSubjectOfNodeChildren(subTreeRootId).next(nodeChildren);
subTreeRootNode.isExpanded = subTreeRootNode.hasChildren;
});
}
/**
* Fetch the node children based on parent node id
* @param parentId Parent node's Id
*/
private fetchNodeChildren(parentId: string): Observable<TreeNode[]> {
// Set default parent id
if (!parentId) { parentId = this.DEFAULT_NODE_ID; }
return this.treeService.loadChildren(parentId).pipe(
tap((childNodes: TreeNode[]) => {
this.nodeChildrenDictionary[parentId] = childNodes;
return this.nodeChildrenDictionary[parentId];
})
);
}
private fetchNodeData(nodeId: string): Observable<TreeNode> {
if (nodeId == this.DEFAULT_NODE_ID) { return of(new TreeNode({ id: nodeId })); }
return this.treeService.getNode(nodeId).pipe(
switchMap((nodeData: TreeNode) => this.updateNodeDataInDictionary(nodeData))
);
}
/**
* Update node data in dictionary
*/
private updateNodeDataInDictionary = (currentNode: TreeNode): Observable<TreeNode> => {
if (!currentNode) { return of(new TreeNode({ id: this.DEFAULT_NODE_ID })); }
const { id, parentId, parentPath, hasChildren } = currentNode;
const parentKey = parentId ? parentId : this.DEFAULT_NODE_ID;
if (!this.nodeChildrenDictionary[parentKey]) { return of(currentNode); }
const matchIndex = this.nodeChildrenDictionary[parentKey]
.findIndex((x: TreeNode) => x.id == currentNode.id || (x.isNew && x.name == currentNode.name));
if (matchIndex == -1) { return of(currentNode); }
const currentNodeItem = this.nodeChildrenDictionary[parentKey][matchIndex];
currentNodeItem.id = id;
currentNodeItem.parentPath = parentPath;
currentNodeItem.isNew = false;
currentNodeItem.isEditing = false;
currentNodeItem.hasChildren = hasChildren;
return of(currentNodeItem);
}
/**
* Expand the tree to target node
* @param newSelectedNode
*/
expandTreeToSelectedNode(newSelectedNode: TreeNode): Observable<string> {
if (this.selectedNode && this.selectedNode.id == newSelectedNode.id) { return empty(); }
this.setSelectedNode(newSelectedNode);
this.fireNodeSelectedInner(newSelectedNode);
const parentPath = newSelectedNode.parentPath ?
`${this.DEFAULT_NODE_ID}${newSelectedNode.parentPath}${newSelectedNode.id},` :
`${this.DEFAULT_NODE_ID},${newSelectedNode.id},`;
const parentIds = parentPath.split(',').filter(id => id);
if (parentIds.length > 0) {
return from(parentIds).pipe(
concatMap((nodeId: string, index: number) =>
(this.nodeChildrenDictionary[nodeId] ? of(this.nodeChildrenDictionary[nodeId]) : this.treeService.loadChildren(nodeId))
.pipe(map((nodes: TreeNode[]) => [nodeId, index, nodes])) // TODO: need to refactor this
),
map(([nodeId, index, nodes]: [string, number, TreeNode[]]) => {
if (!this.nodeChildrenDictionary[nodeId]) { this.nodeChildrenDictionary[nodeId] = nodes; }
if (index > 0) {
const currentNodeIndex = this.nodeChildrenDictionary[parentIds[index - 1]].findIndex(x => x.id == nodeId);
if (currentNodeIndex != -1) {
this.nodeChildrenDictionary[parentIds[index - 1]][currentNodeIndex].isExpanded = true;
}
}
return nodeId;
})
);
}
}
/**
* Fires node selected event in inner tree scope. Only inner components in the tree will subscribe this event
* @param node
*/
fireNodeSelectedInner(node: Partial<TreeNode>) {
this.nodeSelectedInner$.next(node);
}
fireScrollToSelectedNode(node: TreeNode) {
this.scrollToSelectedNode$.next(node);
}
handleNodeMenuItemSelected(nodeAction: TreeMenuActionEvent) {
const { action, node } = nodeAction;
switch (action) {
case NodeMenuItemAction.NewNodeInline:
// add temp new node with status is new
this.showNewNodeInline(node);
break;
case NodeMenuItemAction.EditNowInline:
// update current node with status is rename
this.showNodeInlineEdit(node);
break;
case NodeMenuItemAction.Cut:
this.fireNodeCut(node);
break;
case NodeMenuItemAction.Copy:
this.fireNodeCopied(node);
break;
case NodeMenuItemAction.Paste:
this.fireNodePasted(node);
break;
default:
this.fireMenuActionSelected(nodeAction);
break;
}
}
showNewNodeInline(parentNode: TreeNode) {
const newInlineNode = new TreeNode({
isNew: true,
parentId: parentNode.id == this.DEFAULT_NODE_ID ? null : parentNode.id
});
// Check if the child nodes of parentNode has been loaded
if (this.nodeChildrenDictionary[parentNode.id]) {
// insert new node to begin of node's children
this.nodeChildrenDictionary[parentNode.id].unshift(newInlineNode);
parentNode.isExpanded = true;
parentNode.hasChildren = true;
} else {
this.fetchNodeChildren(parentNode.id).subscribe((nodeChildren: TreeNode[]) => {
// insert new node to begin of node's children
this.nodeChildrenDictionary[parentNode.id].unshift(newInlineNode);
parentNode.isExpanded = true;
parentNode.hasChildren = true;
// reload sub tree
this.getSubjectOfNodeChildren(parentNode.id).next(this.nodeChildrenDictionary[parentNode.id]);
});
}
}
cancelNewNodeInline(parent: TreeNode, node: TreeNode) {
const childNodes = this.nodeChildrenDictionary[node.parentId ? node.parentId : this.DEFAULT_NODE_ID];
if (childNodes) {
const newNodeIndex = childNodes.findIndex((x: TreeNode) => !x.id);
if (newNodeIndex > -1) { childNodes.splice(newNodeIndex, 1); }
if (childNodes.length == 0) {
parent.hasChildren = false;
parent.isExpanded = false;
}
}
}
showNodeInlineEdit(node: TreeNode) {
node.isEditing = true;
}
cancelNodeInlineEdit(node: TreeNode) {
node.isEditing = false;
}
private fireNodeCut(node: TreeNode) {
this.nodeCut$.next(node);
}
private fireNodeCopied(node: TreeNode) {
this.nodeCopied$.next(node);
}
private fireNodePasted(node: TreeNode) {
this.nodePasted$.next(node);
}
// fire and forward menu action click event
private fireMenuActionSelected(actionEvent: TreeMenuActionEvent) {
this.nodeMenuActionEvent$.next(actionEvent);
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Data Flow inside an Azure Data Factory.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const exampleFactory = new azure.datafactory.Factory("exampleFactory", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* });
* const exampleLinkedCustomService = new azure.datafactory.LinkedCustomService("exampleLinkedCustomService", {
* dataFactoryId: exampleFactory.id,
* type: "AzureBlobStorage",
* typePropertiesJson: pulumi.interpolate`{
* "connectionString": "${exampleAccount.primaryConnectionString}"
* }
* `,
* });
* const example1 = new azure.datafactory.DatasetJson("example1", {
* resourceGroupName: exampleResourceGroup.name,
* dataFactoryName: exampleFactory.name,
* linkedServiceName: exampleLinkedCustomService.name,
* azureBlobStorageLocation: {
* container: "container",
* path: "foo/bar/",
* filename: "foo.txt",
* },
* encoding: "UTF-8",
* });
* const example2 = new azure.datafactory.DatasetJson("example2", {
* resourceGroupName: exampleResourceGroup.name,
* dataFactoryName: exampleFactory.name,
* linkedServiceName: exampleLinkedCustomService.name,
* azureBlobStorageLocation: {
* container: "container",
* path: "foo/bar/",
* filename: "bar.txt",
* },
* encoding: "UTF-8",
* });
* const exampleDataFlow = new azure.datafactory.DataFlow("exampleDataFlow", {
* dataFactoryId: exampleFactory.id,
* sources: [{
* name: "source1",
* dataset: {
* name: example1.name,
* },
* }],
* sinks: [{
* name: "sink1",
* dataset: {
* name: example2.name,
* },
* }],
* script: `source(
* allowSchemaDrift: true,
* validateSchema: false,
* limit: 100,
* ignoreNoFilesFound: false,
* documentForm: 'documentPerLine') ~> source1
* source1 sink(
* allowSchemaDrift: true,
* validateSchema: false,
* skipDuplicateMapInputs: true,
* skipDuplicateMapOutputs: true) ~> sink1
* `,
* });
* ```
*
* ## Import
*
* Data Factory Data Flow can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:datafactory/dataFlow:DataFlow example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.DataFactory/factories/example/dataflows/example
* ```
*/
export class DataFlow extends pulumi.CustomResource {
/**
* Get an existing DataFlow 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?: DataFlowState, opts?: pulumi.CustomResourceOptions): DataFlow {
return new DataFlow(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:datafactory/dataFlow:DataFlow';
/**
* Returns true if the given object is an instance of DataFlow. 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 DataFlow {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === DataFlow.__pulumiType;
}
/**
* List of tags that can be used for describing the Data Factory Data Flow.
*/
public readonly annotations!: pulumi.Output<string[] | undefined>;
/**
* The ID of Data Factory in which to associate the Data Flow with. Changing this forces a new resource.
*/
public readonly dataFactoryId!: pulumi.Output<string>;
/**
* The description for the Data Factory Data Flow.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* The folder that this Data Flow is in. If not specified, the Data Flow will appear at the root level.
*/
public readonly folder!: pulumi.Output<string | undefined>;
/**
* Specifies the name of the Data Factory Data Flow. Changing this forces a new resource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* The script for the Data Factory Data Flow.
*/
public readonly script!: pulumi.Output<string>;
/**
* One or more `sink` blocks as defined below.
*/
public readonly sinks!: pulumi.Output<outputs.datafactory.DataFlowSink[]>;
/**
* One or more `source` blocks as defined below.
*/
public readonly sources!: pulumi.Output<outputs.datafactory.DataFlowSource[]>;
/**
* One or more `transformation` blocks as defined below.
*/
public readonly transformations!: pulumi.Output<outputs.datafactory.DataFlowTransformation[] | undefined>;
/**
* Create a DataFlow 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: DataFlowArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: DataFlowArgs | DataFlowState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as DataFlowState | undefined;
inputs["annotations"] = state ? state.annotations : undefined;
inputs["dataFactoryId"] = state ? state.dataFactoryId : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["folder"] = state ? state.folder : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["script"] = state ? state.script : undefined;
inputs["sinks"] = state ? state.sinks : undefined;
inputs["sources"] = state ? state.sources : undefined;
inputs["transformations"] = state ? state.transformations : undefined;
} else {
const args = argsOrState as DataFlowArgs | undefined;
if ((!args || args.dataFactoryId === undefined) && !opts.urn) {
throw new Error("Missing required property 'dataFactoryId'");
}
if ((!args || args.script === undefined) && !opts.urn) {
throw new Error("Missing required property 'script'");
}
if ((!args || args.sinks === undefined) && !opts.urn) {
throw new Error("Missing required property 'sinks'");
}
if ((!args || args.sources === undefined) && !opts.urn) {
throw new Error("Missing required property 'sources'");
}
inputs["annotations"] = args ? args.annotations : undefined;
inputs["dataFactoryId"] = args ? args.dataFactoryId : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["folder"] = args ? args.folder : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["script"] = args ? args.script : undefined;
inputs["sinks"] = args ? args.sinks : undefined;
inputs["sources"] = args ? args.sources : undefined;
inputs["transformations"] = args ? args.transformations : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(DataFlow.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering DataFlow resources.
*/
export interface DataFlowState {
/**
* List of tags that can be used for describing the Data Factory Data Flow.
*/
annotations?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The ID of Data Factory in which to associate the Data Flow with. Changing this forces a new resource.
*/
dataFactoryId?: pulumi.Input<string>;
/**
* The description for the Data Factory Data Flow.
*/
description?: pulumi.Input<string>;
/**
* The folder that this Data Flow is in. If not specified, the Data Flow will appear at the root level.
*/
folder?: pulumi.Input<string>;
/**
* Specifies the name of the Data Factory Data Flow. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* The script for the Data Factory Data Flow.
*/
script?: pulumi.Input<string>;
/**
* One or more `sink` blocks as defined below.
*/
sinks?: pulumi.Input<pulumi.Input<inputs.datafactory.DataFlowSink>[]>;
/**
* One or more `source` blocks as defined below.
*/
sources?: pulumi.Input<pulumi.Input<inputs.datafactory.DataFlowSource>[]>;
/**
* One or more `transformation` blocks as defined below.
*/
transformations?: pulumi.Input<pulumi.Input<inputs.datafactory.DataFlowTransformation>[]>;
}
/**
* The set of arguments for constructing a DataFlow resource.
*/
export interface DataFlowArgs {
/**
* List of tags that can be used for describing the Data Factory Data Flow.
*/
annotations?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The ID of Data Factory in which to associate the Data Flow with. Changing this forces a new resource.
*/
dataFactoryId: pulumi.Input<string>;
/**
* The description for the Data Factory Data Flow.
*/
description?: pulumi.Input<string>;
/**
* The folder that this Data Flow is in. If not specified, the Data Flow will appear at the root level.
*/
folder?: pulumi.Input<string>;
/**
* Specifies the name of the Data Factory Data Flow. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* The script for the Data Factory Data Flow.
*/
script: pulumi.Input<string>;
/**
* One or more `sink` blocks as defined below.
*/
sinks: pulumi.Input<pulumi.Input<inputs.datafactory.DataFlowSink>[]>;
/**
* One or more `source` blocks as defined below.
*/
sources: pulumi.Input<pulumi.Input<inputs.datafactory.DataFlowSource>[]>;
/**
* One or more `transformation` blocks as defined below.
*/
transformations?: pulumi.Input<pulumi.Input<inputs.datafactory.DataFlowTransformation>[]>;
} | the_stack |
import { ethers, optics } from 'hardhat';
import { expect } from 'chai';
import * as types from 'ethers';
import { formatCall, sendFromSigner } from './utils';
import { increaseTimestampBy } from '../utils';
import { getTestDeploy } from '../testChain';
import { Updater } from '../../lib/core';
import { Signer } from '../../lib/types';
import { CoreDeploy as Deploy } from '@optics-xyz/deploy/dist/src/core/CoreDeploy';
import { deployNChains } from '@optics-xyz/deploy/dist/src/core';
import * as contracts from '@optics-xyz/ts-interface/dist/optics-core';
async function expectNotInRecovery(
updaterManager: contracts.UpdaterManager,
recoveryManager: types.Signer,
randomSigner: Signer,
governor: Signer,
governanceRouter: contracts.TestGovernanceRouter,
home: contracts.TestHome,
) {
expect(await governanceRouter.inRecovery()).to.be.false;
// Format optics call message
const call = await formatCall(updaterManager, 'setUpdater', [
randomSigner.address,
]);
// Expect that Governor *CAN* Call Local & Call Remote
// dispatch call on local governorRouter
await expect(
sendFromSigner(governor, governanceRouter, 'callLocal', [[call]]),
)
.to.emit(home, 'NewUpdater')
.withArgs(randomSigner.address);
// dispatch call on local governorRouter
await expect(
sendFromSigner(governor, governanceRouter, 'callRemote', [2000, [call]]),
).to.emit(home, 'Dispatch');
// set xApp Connection Manager
const xAppConnectionManager = await governanceRouter.xAppConnectionManager();
await expect(
sendFromSigner(governor, governanceRouter, 'setXAppConnectionManager', [
randomSigner.address,
]),
).to.not.be.reverted;
// reset xApp Connection Manager to actual contract
await sendFromSigner(governor, governanceRouter, 'setXAppConnectionManager', [
xAppConnectionManager,
]);
// set Router Locally
const otherDomain = 2000;
const previousRouter = await governanceRouter.routers(otherDomain);
await expect(
sendFromSigner(governor, governanceRouter, 'setRouterLocal', [
2000,
optics.ethersAddressToBytes32(randomSigner.address),
]),
)
.to.emit(governanceRouter, 'SetRouter')
.withArgs(
otherDomain,
previousRouter,
optics.ethersAddressToBytes32(randomSigner.address),
);
// Expect that Recovery Manager CANNOT Call Local OR Call Remote
// cannot dispatch call on local governorRouter
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'callLocal', [[call]]),
).to.be.revertedWith('! called by governor');
// cannot dispatch call to remote governorRouter
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'callRemote', [
2000,
[call],
]),
).to.be.revertedWith('! called by governor');
// cannot set xAppConnectionManager
await expect(
sendFromSigner(
recoveryManager,
governanceRouter,
'setXAppConnectionManager',
[randomSigner.address],
),
).to.be.revertedWith('! called by governor');
// cannot set Router
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'setRouterLocal', [
2000,
optics.ethersAddressToBytes32(randomSigner.address),
]),
).to.be.revertedWith('! called by governor');
}
async function expectOnlyRecoveryManagerCanTransferRole(
governor: Signer,
governanceRouter: contracts.TestGovernanceRouter,
randomSigner: Signer,
recoveryManager: Signer,
) {
await expect(
sendFromSigner(governor, governanceRouter, 'transferRecoveryManager', [
randomSigner.address,
]),
).to.be.revertedWith('! called by recovery manager');
await expect(
sendFromSigner(randomSigner, governanceRouter, 'transferRecoveryManager', [
randomSigner.address,
]),
).to.be.revertedWith('! called by recovery manager');
await expect(
sendFromSigner(
recoveryManager,
governanceRouter,
'transferRecoveryManager',
[randomSigner.address],
),
)
.to.emit(governanceRouter, 'TransferRecoveryManager')
.withArgs(recoveryManager.address, randomSigner.address);
await expect(
sendFromSigner(randomSigner, governanceRouter, 'transferRecoveryManager', [
recoveryManager.address,
]),
)
.to.emit(governanceRouter, 'TransferRecoveryManager')
.withArgs(randomSigner.address, recoveryManager.address);
}
async function expectOnlyRecoveryManagerCanExitRecovery(
governor: Signer,
governanceRouter: contracts.TestGovernanceRouter,
randomSigner: Signer,
recoveryManager: Signer,
) {
await expect(
sendFromSigner(governor, governanceRouter, 'exitRecovery', []),
).to.be.revertedWith('! called by recovery manager');
await expect(
sendFromSigner(randomSigner, governanceRouter, 'exitRecovery', []),
).to.be.revertedWith('! called by recovery manager');
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'exitRecovery', []),
)
.to.emit(governanceRouter, 'ExitRecovery')
.withArgs(recoveryManager.address);
}
async function expectOnlyRecoveryManagerCanInitiateRecovery(
governor: Signer,
governanceRouter: contracts.TestGovernanceRouter,
randomSigner: Signer,
recoveryManager: Signer,
) {
await expect(
sendFromSigner(governor, governanceRouter, 'initiateRecoveryTimelock', []),
).to.be.revertedWith('! called by recovery manager');
await expect(
sendFromSigner(
randomSigner,
governanceRouter,
'initiateRecoveryTimelock',
[],
),
).to.be.revertedWith('! called by recovery manager');
expect(await governanceRouter.recoveryActiveAt()).to.equal(0);
await expect(
sendFromSigner(
recoveryManager,
governanceRouter,
'initiateRecoveryTimelock',
[],
),
).to.emit(governanceRouter, 'InitiateRecovery');
expect(await governanceRouter.recoveryActiveAt()).to.not.equal(0);
}
const localDomain = 1000;
const remoteDomain = 2000;
/*
* Deploy the full Optics suite on two chains
*/
describe('RecoveryManager', async () => {
let governor: Signer,
recoveryManager: Signer,
randomSigner: Signer,
governanceRouter: contracts.TestGovernanceRouter,
home: contracts.TestHome,
updaterManager: contracts.UpdaterManager;
let deploys: Deploy[] = [];
before(async () => {
[governor, recoveryManager, randomSigner] = await ethers.getSigners();
const updater = await Updater.fromSigner(randomSigner, localDomain);
deploys.push(
await getTestDeploy(
localDomain,
updater.address,
[],
recoveryManager.address,
),
);
deploys.push(
await getTestDeploy(
remoteDomain,
updater.address,
[],
recoveryManager.address,
),
);
await deployNChains(deploys);
governanceRouter = deploys[0].contracts.governance
?.proxy! as contracts.TestGovernanceRouter;
home = deploys[0].contracts.home?.proxy! as contracts.TestHome;
updaterManager = deploys[0].contracts.updaterManager!;
// set governor
await governanceRouter.transferGovernor(localDomain, governor.address);
});
it('Before Recovery Initiated: Timelock has not been set', async () => {
expect(await governanceRouter.recoveryActiveAt()).to.equal(0);
});
it('Before Recovery Initiated: Cannot Exit Recovery yet', async () => {
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'exitRecovery', []),
).to.be.revertedWith('recovery not initiated');
});
it('Before Recovery Initiated: Not in Recovery (Governor CAN Call Local & Remote; Recovery Manager CANNOT Call either)', async () => {
await expectNotInRecovery(
updaterManager,
recoveryManager,
randomSigner,
governor,
governanceRouter,
home,
);
});
it('Before Recovery Initiated: ONLY RecoveryManager can transfer RecoveryManager role', async () => {
await expectOnlyRecoveryManagerCanTransferRole(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
it('Before Recovery Initiated: ONLY RecoveryManager can Initiate Recovery', async () => {
await expectOnlyRecoveryManagerCanInitiateRecovery(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
it('Before Recovery Active: CANNOT Initiate Recovery Twice', async () => {
await expect(
sendFromSigner(
recoveryManager,
governanceRouter,
'initiateRecoveryTimelock',
[],
),
).to.be.revertedWith('recovery already initiated');
});
it('Before Recovery Active: Not in Recovery (Governor CAN Call Local & Remote; Recovery Manager CANNOT Call either)', async () => {
await expectNotInRecovery(
updaterManager,
recoveryManager,
randomSigner,
governor,
governanceRouter,
home,
);
});
it('Before Recovery Active: ONLY RecoveryManager can transfer RecoveryManager role', async () => {
await expectOnlyRecoveryManagerCanTransferRole(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
it('Before Recovery Active: ONLY RecoveryManager can Exit Recovery', async () => {
await expectOnlyRecoveryManagerCanExitRecovery(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
it('Before Recovery Active: ONLY RecoveryManager can Initiate Recovery (CAN initiate a second time)', async () => {
await expectOnlyRecoveryManagerCanInitiateRecovery(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
it('Recovery Active: inRecovery becomes true when timelock expires', async () => {
// increase timestamp on-chain
const timelock = await governanceRouter.recoveryTimelock();
await increaseTimestampBy(ethers.provider, timelock.toNumber());
expect(await governanceRouter.inRecovery()).to.be.true;
});
it('Recovery Active: RecoveryManager CAN call local', async () => {
// Format optics call message
const call = await formatCall(updaterManager, 'setUpdater', [
randomSigner.address,
]);
// dispatch call on local governorRouter
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'callLocal', [[call]]),
)
.to.emit(home, 'NewUpdater')
.withArgs(randomSigner.address);
});
it('Recovery Active: RecoveryManager CANNOT call remote', async () => {
// Format optics call message
const call = await formatCall(updaterManager, 'setUpdater', [
randomSigner.address,
]);
// dispatch call on local governorRouter
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'callRemote', [
2000,
[call],
]),
).to.be.revertedWith('! called by governor');
});
it('Recovery Active: RecoveryManager CAN set xAppConnectionManager', async () => {
// set xApp Connection Manager
const xAppConnectionManager =
await governanceRouter.xAppConnectionManager();
await expect(
sendFromSigner(
recoveryManager,
governanceRouter,
'setXAppConnectionManager',
[randomSigner.address],
),
).to.not.be.reverted;
// reset xApp Connection Manager to actual contract
await sendFromSigner(
recoveryManager,
governanceRouter,
'setXAppConnectionManager',
[xAppConnectionManager],
);
});
it('Recovery Active: RecoveryManager CAN set Router locally', async () => {
const otherDomain = 2000;
const previousRouter = await governanceRouter.routers(otherDomain);
await expect(
sendFromSigner(recoveryManager, governanceRouter, 'setRouterLocal', [
2000,
optics.ethersAddressToBytes32(randomSigner.address),
]),
)
.to.emit(governanceRouter, 'SetRouter')
.withArgs(
otherDomain,
previousRouter,
optics.ethersAddressToBytes32(randomSigner.address),
);
});
it('Recovery Active: Governor CANNOT call local OR remote', async () => {
// Format optics call message
const call = await formatCall(updaterManager, 'setUpdater', [
randomSigner.address,
]);
// dispatch call on local governorRouter
await expect(
sendFromSigner(governor, governanceRouter, 'callLocal', [[call]]),
).to.be.revertedWith('! called by recovery manager');
// dispatch call on local governorRouter
await expect(
sendFromSigner(governor, governanceRouter, 'callRemote', [2000, [call]]),
).to.be.revertedWith('in recovery');
});
it('Recovery Active: Governor CANNOT set xAppConnectionManager', async () => {
// cannot set xAppConnectionManager
await expect(
sendFromSigner(governor, governanceRouter, 'setXAppConnectionManager', [
randomSigner.address,
]),
).to.be.revertedWith('! called by recovery manager');
});
it('Recovery Active: Governor CANNOT set Router locally', async () => {
// cannot set Router
await expect(
sendFromSigner(governor, governanceRouter, 'setRouterLocal', [
2000,
optics.ethersAddressToBytes32(randomSigner.address),
]),
).to.be.revertedWith('! called by recovery manager');
});
it('Recovery Active: ONLY RecoveryManager can transfer RecoveryManager role', async () => {
await expectOnlyRecoveryManagerCanTransferRole(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
it('Recovery Active: ONLY RecoveryManager can Exit Recovery', async () => {
await expectOnlyRecoveryManagerCanExitRecovery(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
it('Exited Recovery: Timelock is deleted', async () => {
expect(await governanceRouter.recoveryActiveAt()).to.equal(0);
});
it('Exited Recovery: Not in Recovery (Governor CAN Call Local & Remote; Recovery Manager CANNOT Call either)', async () => {
await expectNotInRecovery(
updaterManager,
recoveryManager,
randomSigner,
governor,
governanceRouter,
home,
);
});
it('Exited Recovery: ONLY RecoveryManager can transfer RecoveryManager role', async () => {
await expectOnlyRecoveryManagerCanTransferRole(
governor,
governanceRouter,
randomSigner,
recoveryManager,
);
});
}); | the_stack |
'use strict';
// Use untyped import syntax for Node built-ins
import https = require('https');
import * as _ from 'lodash';
import * as chai from 'chai';
import * as nock from 'nock';
import * as sinon from 'sinon';
import * as mocks from '../../resources/mocks';
import {
ALGORITHM_RS256, DecodedToken, decodeJwt, EmulatorSignatureVerifier, JwksFetcher,
JwtErrorCode, PublicKeySignatureVerifier, UrlKeyFetcher, verifyJwtSignature
} from '../../../src/utils/jwt';
const expect = chai.expect;
const ONE_HOUR_IN_SECONDS = 60 * 60;
const SIX_HOURS_IN_SECONDS = ONE_HOUR_IN_SECONDS * 6;
const publicCertPath = '/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com';
const jwksPath = '/v1alpha/jwks';
/**
* Returns a mocked out success response from the URL containing the public keys for the Google certs.
*
* @param {string=} path URL path to which the mock request should be made. If not specified, defaults
* to the URL path of ID token public key certificates.
* @return {Object} A nock response object.
*/
function mockFetchPublicKeys(path: string = publicCertPath): nock.Scope {
const mockedResponse: { [key: string]: string } = {};
mockedResponse[mocks.certificateObject.private_key_id] = mocks.keyPairs[0].public;
return nock('https://www.googleapis.com')
.get(path)
.reply(200, mockedResponse, {
'cache-control': 'public, max-age=1, must-revalidate, no-transform',
});
}
/**
* Returns a mocked out error response from the URL containing the public keys for the Google certs.
* The status code is 200 but the response itself will contain an 'error' key.
*
* @return {Object} A nock response object.
*/
function mockFetchPublicKeysWithErrorResponse(): nock.Scope {
return nock('https://www.googleapis.com')
.get('/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com')
.reply(200, {
error: 'message',
error_description: 'description', // eslint-disable-line @typescript-eslint/camelcase
});
}
/**
* Returns a mocked out failed response from the URL containing the public keys for the Google certs.
* The status code is non-200 and the response itself will fail.
*
* @return {Object} A nock response object.
*/
function mockFailedFetchPublicKeys(): nock.Scope {
return nock('https://www.googleapis.com')
.get('/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com')
.replyWithError('message');
}
/**
* Returns a mocked out success JWKS response.
*
* @returns A nock response object.
*/
function mockFetchJsonWebKeys(path: string = jwksPath): nock.Scope {
return nock('https://firebaseappcheck.googleapis.com')
.get(path)
.reply(200, mocks.jwksResponse);
}
/**
* Returns a mocked out error response for JWKS.
* The status code is 200 but the response itself will contain an 'error' key.
*
* @returns A nock response object.
*/
function mockFetchJsonWebKeysWithErrorResponse(): nock.Scope {
return nock('https://firebaseappcheck.googleapis.com')
.get(jwksPath)
.reply(200, {
error: 'message',
error_description: 'description', // eslint-disable-line @typescript-eslint/camelcase
});
}
/**
* Returns a mocked out failed JSON Web Keys response.
* The status code is non-200 and the response itself will fail.
*
* @returns A nock response object.
*/
function mockFailedFetchJsonWebKeys(): nock.Scope {
return nock('https://firebaseappcheck.googleapis.com')
.get(jwksPath)
.replyWithError('message');
}
const TOKEN_PAYLOAD = {
one: 'uno',
two: 'dos',
iat: 1,
exp: ONE_HOUR_IN_SECONDS + 1,
aud: mocks.projectId,
iss: 'https://securetoken.google.com/' + mocks.projectId,
sub: mocks.uid,
};
const DECODED_SIGNED_TOKEN: DecodedToken = {
header: {
alg: 'RS256',
kid: 'aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd',
typ: 'JWT',
},
payload: TOKEN_PAYLOAD
};
const DECODED_UNSIGNED_TOKEN: DecodedToken = {
header: {
alg: 'none',
typ: 'JWT',
},
payload: TOKEN_PAYLOAD
};
const VALID_PUBLIC_KEYS_RESPONSE: { [key: string]: string } = {};
VALID_PUBLIC_KEYS_RESPONSE[mocks.certificateObject.private_key_id] = mocks.keyPairs[0].public;
describe('decodeJwt', () => {
let clock: sinon.SinonFakeTimers | undefined;
afterEach(() => {
if (clock) {
clock.restore();
clock = undefined;
}
});
it('should reject given no token', () => {
return (decodeJwt as any)()
.should.eventually.be.rejectedWith('The provided token must be a string.');
});
const invalidIdTokens = [null, NaN, 0, 1, true, false, [], {}, { a: 1 }, _.noop];
invalidIdTokens.forEach((invalidIdToken) => {
it('should reject given a non-string token: ' + JSON.stringify(invalidIdToken), () => {
return decodeJwt(invalidIdToken as any)
.should.eventually.be.rejectedWith('The provided token must be a string.');
});
});
it('should reject given an empty string token', () => {
return decodeJwt('')
.should.eventually.be.rejectedWith('Decoding token failed.');
});
it('should reject given an invalid token', () => {
return decodeJwt('invalid-token')
.should.eventually.be.rejectedWith('Decoding token failed.');
});
it('should be fulfilled with decoded claims given a valid signed token', () => {
clock = sinon.useFakeTimers(1000);
const mockIdToken = mocks.generateIdToken();
return decodeJwt(mockIdToken)
.should.eventually.be.fulfilled.and.deep.equal(DECODED_SIGNED_TOKEN);
});
it('should be fulfilled with decoded claims given a valid unsigned token', () => {
clock = sinon.useFakeTimers(1000);
const mockIdToken = mocks.generateIdToken({
algorithm: 'none',
header: {}
});
return decodeJwt(mockIdToken)
.should.eventually.be.fulfilled.and.deep.equal(DECODED_UNSIGNED_TOKEN);
});
});
describe('verifyJwtSignature', () => {
let clock: sinon.SinonFakeTimers | undefined;
afterEach(() => {
if (clock) {
clock.restore();
clock = undefined;
}
});
it('should throw given no token', () => {
return (verifyJwtSignature as any)()
.should.eventually.be.rejectedWith('The provided token must be a string.');
});
const invalidIdTokens = [null, NaN, 0, 1, true, false, [], {}, { a: 1 }, _.noop];
invalidIdTokens.forEach((invalidIdToken) => {
it('should reject given a non-string token: ' + JSON.stringify(invalidIdToken), () => {
return verifyJwtSignature(invalidIdToken as any, mocks.keyPairs[0].public)
.should.eventually.be.rejectedWith('The provided token must be a string.');
});
});
it('should reject given an empty string token', () => {
return verifyJwtSignature('', mocks.keyPairs[0].public)
.should.eventually.be.rejectedWith('jwt must be provided');
});
it('should be fulfilled given a valid signed token and public key', () => {
const mockIdToken = mocks.generateIdToken();
return verifyJwtSignature(mockIdToken, mocks.keyPairs[0].public,
{ algorithms: [ALGORITHM_RS256] })
.should.eventually.be.fulfilled;
});
it('should be fulfilled given a valid unsigned (emulator) token and no public key', () => {
const mockIdToken = mocks.generateIdToken({
algorithm: 'none',
header: {}
});
return verifyJwtSignature(mockIdToken, '')
.should.eventually.be.fulfilled;
});
it('should be fulfilled given a valid signed token and a function to provide public keys', () => {
const mockIdToken = mocks.generateIdToken();
const getKeyCallback = (_: any, callback: any): void => callback(null, mocks.keyPairs[0].public);
return verifyJwtSignature(mockIdToken, getKeyCallback,
{ algorithms: [ALGORITHM_RS256] })
.should.eventually.be.fulfilled;
});
it('should be rejected when the given algorithm does not match the token', () => {
const mockIdToken = mocks.generateIdToken();
return verifyJwtSignature(mockIdToken, mocks.keyPairs[0].public,
{ algorithms: ['RS384'] })
.should.eventually.be.rejectedWith('invalid algorithm')
.with.property('code', JwtErrorCode.INVALID_SIGNATURE);
});
it('should be rejected given an expired token', () => {
clock = sinon.useFakeTimers(1000);
const mockIdToken = mocks.generateIdToken();
clock.tick((ONE_HOUR_IN_SECONDS * 1000) - 1);
// token should still be valid
return verifyJwtSignature(mockIdToken, mocks.keyPairs[0].public,
{ algorithms: [ALGORITHM_RS256] })
.then(() => {
clock!.tick(1);
// token should now be invalid
return verifyJwtSignature(mockIdToken, mocks.keyPairs[0].public,
{ algorithms: [ALGORITHM_RS256] })
.should.eventually.be.rejectedWith(
'The provided token has expired. Get a fresh token from your client app and try again.'
)
.with.property('code', JwtErrorCode.TOKEN_EXPIRED);
});
});
it('should be rejected with correct public key fetch error.', () => {
const mockIdToken = mocks.generateIdToken();
const getKeyCallback = (_: any, callback: any): void =>
callback(new Error('key fetch failed.'));
return verifyJwtSignature(mockIdToken, getKeyCallback,
{ algorithms: [ALGORITHM_RS256] })
.should.eventually.be.rejectedWith('key fetch failed.')
.with.property('code', JwtErrorCode.KEY_FETCH_ERROR);
});
it('should be rejected with correct no matching key id found error.', () => {
const mockIdToken = mocks.generateIdToken();
const getKeyCallback = (_: any, callback: any): void =>
callback(new Error('no-matching-kid-error'));
return verifyJwtSignature(mockIdToken, getKeyCallback,
{ algorithms: [ALGORITHM_RS256] })
.should.eventually.be.rejectedWith('no-matching-kid-error')
.with.property('code', JwtErrorCode.NO_MATCHING_KID);
});
it('should be rejected given a public key that does not match the token.', () => {
const mockIdToken = mocks.generateIdToken();
return verifyJwtSignature(mockIdToken, mocks.keyPairs[1].public,
{ algorithms: [ALGORITHM_RS256] })
.should.eventually.be.rejectedWith('invalid signature')
.with.property('code', JwtErrorCode.INVALID_SIGNATURE);
});
it('should be rejected given an invalid JWT.', () => {
return verifyJwtSignature('invalid-token', mocks.keyPairs[0].public)
.should.eventually.be.rejectedWith('jwt malformed')
.with.property('code', JwtErrorCode.INVALID_SIGNATURE);
});
});
describe('PublicKeySignatureVerifier', () => {
let stubs: sinon.SinonStub[] = [];
let clock: sinon.SinonFakeTimers | undefined;
const verifier = new PublicKeySignatureVerifier(
new UrlKeyFetcher('https://www.example.com/publicKeys'));
afterEach(() => {
_.forEach(stubs, (stub) => stub.restore());
stubs = [];
if (clock) {
clock.restore();
clock = undefined;
}
});
describe('Constructor', () => {
it('should not throw when valid key fetcher is provided', () => {
expect(() => {
new PublicKeySignatureVerifier(
new UrlKeyFetcher('https://www.example.com/publicKeys'));
}).not.to.throw();
});
const invalidKeyFetchers = [null, NaN, 0, 1, true, false, [], ['a'], _.noop, '', 'a'];
invalidKeyFetchers.forEach((invalidKeyFetcher) => {
it('should throw given an invalid key fetcher: ' + JSON.stringify(invalidKeyFetcher), () => {
expect(() => {
new PublicKeySignatureVerifier(invalidKeyFetchers as any);
}).to.throw('The provided key fetcher is not an object or null.');
});
});
});
describe('withCertificateUrl', () => {
it('should return a PublicKeySignatureVerifier instance with a UrlKeyFetcher when a ' +
'valid cert url is provided', () => {
const verifier = PublicKeySignatureVerifier.withCertificateUrl('https://www.example.com/publicKeys');
expect(verifier).to.be.an.instanceOf(PublicKeySignatureVerifier);
expect((verifier as any).keyFetcher).to.be.an.instanceOf(UrlKeyFetcher);
});
});
describe('withJwksUrl', () => {
it('should return a PublicKeySignatureVerifier instance with a JwksFetcher when a ' +
'valid jwks url is provided', () => {
const verifier = PublicKeySignatureVerifier.withJwksUrl('https://www.example.com/publicKeys');
expect(verifier).to.be.an.instanceOf(PublicKeySignatureVerifier);
expect((verifier as any).keyFetcher).to.be.an.instanceOf(JwksFetcher);
});
});
describe('verify', () => {
it('should throw given no token', () => {
return (verifier.verify as any)()
.should.eventually.be.rejectedWith('The provided token must be a string.');
});
const invalidIdTokens = [null, NaN, 0, 1, true, false, [], {}, { a: 1 }, _.noop];
invalidIdTokens.forEach((invalidIdToken) => {
it('should reject given a non-string token: ' + JSON.stringify(invalidIdToken), () => {
return verifier.verify(invalidIdToken as any)
.should.eventually.be.rejectedWith('The provided token must be a string.');
});
});
it('should reject given an empty string token', () => {
return verifier.verify('')
.should.eventually.be.rejectedWith('jwt must be provided');
});
it('should be fulfilled given a valid token', () => {
const keyFetcherStub = sinon.stub(UrlKeyFetcher.prototype, 'fetchPublicKeys')
.resolves(VALID_PUBLIC_KEYS_RESPONSE);
stubs.push(keyFetcherStub);
const mockIdToken = mocks.generateIdToken();
return verifier.verify(mockIdToken).should.eventually.be.fulfilled;
});
it('should be fulfilled given a valid token without a kid (should check against all the keys)', () => {
const keyFetcherStub = sinon.stub(UrlKeyFetcher.prototype, 'fetchPublicKeys')
.resolves({ 'kid-other': 'key-other', ...VALID_PUBLIC_KEYS_RESPONSE });
stubs.push(keyFetcherStub);
const mockIdToken = mocks.generateIdToken({
header: {}
});
return verifier.verify(mockIdToken).should.eventually.be.fulfilled;
});
it('should be rejected given an expired token without a kid (should check against all the keys)', () => {
const keyFetcherStub = sinon.stub(UrlKeyFetcher.prototype, 'fetchPublicKeys')
.resolves({ 'kid-other': 'key-other', ...VALID_PUBLIC_KEYS_RESPONSE });
stubs.push(keyFetcherStub);
clock = sinon.useFakeTimers(1000);
const mockIdToken = mocks.generateIdToken({
header: {}
});
clock.tick((ONE_HOUR_IN_SECONDS * 1000) - 1);
// token should still be valid
return verifier.verify(mockIdToken)
.then(() => {
clock!.tick(1);
// token should now be invalid
return verifier.verify(mockIdToken).should.eventually.be.rejectedWith(
'The provided token has expired. Get a fresh token from your client app and try again.')
.with.property('code', JwtErrorCode.TOKEN_EXPIRED);
});
});
it('should be rejected given a token with an incorrect algorithm', () => {
const keyFetcherStub = sinon.stub(UrlKeyFetcher.prototype, 'fetchPublicKeys')
.resolves(VALID_PUBLIC_KEYS_RESPONSE);
stubs.push(keyFetcherStub);
const mockIdToken = mocks.generateIdToken({
algorithm: 'HS256',
});
return verifier.verify(mockIdToken).should.eventually.be
.rejectedWith('invalid algorithm')
.with.property('code', JwtErrorCode.INVALID_SIGNATURE);
});
// tests to cover the private getKeyCallback function.
it('should reject when no matching kid found', () => {
const keyFetcherStub = sinon.stub(UrlKeyFetcher.prototype, 'fetchPublicKeys')
.resolves({ 'not-a-matching-key': 'public-key' });
stubs.push(keyFetcherStub);
const mockIdToken = mocks.generateIdToken();
return verifier.verify(mockIdToken).should.eventually.be
.rejectedWith('no-matching-kid-error')
.with.property('code', JwtErrorCode.NO_MATCHING_KID);
});
it('should reject when an error occurs while fetching the keys', () => {
const keyFetcherStub = sinon.stub(UrlKeyFetcher.prototype, 'fetchPublicKeys')
.rejects(new Error('Error fetching public keys.'));
stubs.push(keyFetcherStub);
const mockIdToken = mocks.generateIdToken();
return verifier.verify(mockIdToken).should.eventually.be
.rejectedWith('Error fetching public keys.')
.with.property('code', JwtErrorCode.KEY_FETCH_ERROR);
});
});
});
describe('EmulatorSignatureVerifier', () => {
const emulatorVerifier = new EmulatorSignatureVerifier();
describe('verify', () => {
it('should be fullfilled given a valid unsigned (emulator) token', () => {
const mockIdToken = mocks.generateIdToken({
algorithm: 'none',
header: {}
});
return emulatorVerifier.verify(mockIdToken).should.eventually.be.fulfilled;
});
it('should be rejected given a valid signed (non-emulator) token', () => {
const mockIdToken = mocks.generateIdToken();
return emulatorVerifier.verify(mockIdToken).should.eventually.be.rejected;
});
});
});
describe('UrlKeyFetcher', () => {
const agent = new https.Agent();
let keyFetcher: UrlKeyFetcher;
let clock: sinon.SinonFakeTimers | undefined;
let httpsSpy: sinon.SinonSpy;
beforeEach(() => {
keyFetcher = new UrlKeyFetcher(
'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com',
agent);
httpsSpy = sinon.spy(https, 'request');
});
afterEach(() => {
if (clock) {
clock.restore();
clock = undefined;
}
httpsSpy.restore();
});
after(() => {
nock.cleanAll();
});
describe('Constructor', () => {
it('should not throw when valid key parameters are provided', () => {
expect(() => {
new UrlKeyFetcher('https://www.example.com/publicKeys', agent);
}).not.to.throw();
});
const invalidCertURLs = [null, NaN, 0, 1, true, false, [], {}, { a: 1 }, _.noop, 'file://invalid'];
invalidCertURLs.forEach((invalidCertUrl) => {
it('should throw given a non-URL public cert: ' + JSON.stringify(invalidCertUrl), () => {
expect(() => {
new UrlKeyFetcher(invalidCertUrl as any, agent);
}).to.throw('The provided public client certificate URL is not a valid URL.');
});
});
});
describe('fetchPublicKeys', () => {
let mockedRequests: nock.Scope[] = [];
afterEach(() => {
_.forEach(mockedRequests, (mockedRequest) => mockedRequest.done());
mockedRequests = [];
});
it('should use the given HTTP Agent', () => {
const agent = new https.Agent();
const urlKeyFetcher = new UrlKeyFetcher('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com', agent);
mockedRequests.push(mockFetchPublicKeys());
return urlKeyFetcher.fetchPublicKeys()
.then(() => {
expect(https.request).to.have.been.calledOnce;
expect(httpsSpy.args[0][0].agent).to.equal(agent);
});
});
it('should not fetch the public keys until the first time fetchPublicKeys() is called', () => {
mockedRequests.push(mockFetchPublicKeys());
const urlKeyFetcher = new UrlKeyFetcher('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com', agent);
expect(https.request).not.to.have.been.called;
return urlKeyFetcher.fetchPublicKeys()
.then(() => expect(https.request).to.have.been.calledOnce);
});
it('should not re-fetch the public keys every time fetchPublicKeys() is called', () => {
mockedRequests.push(mockFetchPublicKeys());
return keyFetcher.fetchPublicKeys().then(() => {
expect(https.request).to.have.been.calledOnce;
return keyFetcher.fetchPublicKeys();
}).then(() => expect(https.request).to.have.been.calledOnce);
});
it('should refresh the public keys after the "max-age" on the request expires', () => {
mockedRequests.push(mockFetchPublicKeys());
mockedRequests.push(mockFetchPublicKeys());
mockedRequests.push(mockFetchPublicKeys());
clock = sinon.useFakeTimers(1000);
return keyFetcher.fetchPublicKeys().then(() => {
expect(https.request).to.have.been.calledOnce;
clock!.tick(999);
return keyFetcher.fetchPublicKeys();
}).then(() => {
expect(https.request).to.have.been.calledOnce;
clock!.tick(1);
return keyFetcher.fetchPublicKeys();
}).then(() => {
// One second has passed
expect(https.request).to.have.been.calledTwice;
clock!.tick(999);
return keyFetcher.fetchPublicKeys();
}).then(() => {
expect(https.request).to.have.been.calledTwice;
clock!.tick(1);
return keyFetcher.fetchPublicKeys();
}).then(() => {
// Two seconds have passed
expect(https.request).to.have.been.calledThrice;
});
});
it('should be rejected if fetching the public keys fails', () => {
mockedRequests.push(mockFailedFetchPublicKeys());
return keyFetcher.fetchPublicKeys()
.should.eventually.be.rejectedWith('message');
});
it('should be rejected if fetching the public keys returns a response with an error message', () => {
mockedRequests.push(mockFetchPublicKeysWithErrorResponse());
return keyFetcher.fetchPublicKeys()
.should.eventually.be.rejectedWith('Error fetching public keys for Google certs: message (description)');
});
});
});
describe('JwksFetcher', () => {
let keyFetcher: JwksFetcher;
let clock: sinon.SinonFakeTimers | undefined;
let httpsSpy: sinon.SinonSpy;
beforeEach(() => {
keyFetcher = new JwksFetcher(
'https://firebaseappcheck.googleapis.com/v1alpha/jwks'
);
httpsSpy = sinon.spy(https, 'request');
});
afterEach(() => {
if (clock) {
clock.restore();
clock = undefined;
}
httpsSpy.restore();
});
after(() => {
nock.cleanAll();
});
describe('Constructor', () => {
it('should not throw when valid url is provided', () => {
expect(() => {
new JwksFetcher('https://www.example.com/publicKeys');
}).not.to.throw();
});
const invalidJwksURLs = [null, NaN, 0, 1, true, false, [], {}, { a: 1 }, _.noop, 'file://invalid'];
invalidJwksURLs.forEach((invalidJwksURL) => {
it('should throw given a non-URL jwks endpoint: ' + JSON.stringify(invalidJwksURL), () => {
expect(() => {
new JwksFetcher(invalidJwksURL as any);
}).to.throw('The provided JWKS URL is not a valid URL.');
});
});
});
describe('fetchPublicKeys', () => {
let mockedRequests: nock.Scope[] = [];
afterEach(() => {
_.forEach(mockedRequests, (mockedRequest) => mockedRequest.done());
mockedRequests = [];
});
it('should not fetch the public keys until the first time fetchPublicKeys() is called', () => {
mockedRequests.push(mockFetchJsonWebKeys());
const jwksFetcher = new JwksFetcher('https://firebaseappcheck.googleapis.com/v1alpha/jwks');
expect(https.request).not.to.have.been.called;
return jwksFetcher.fetchPublicKeys()
.then((result) => {
expect(https.request).to.have.been.calledOnce;
expect(result).to.have.key(mocks.jwksResponse.keys[0].kid);
});
});
it('should not re-fetch the public keys every time fetchPublicKeys() is called', () => {
mockedRequests.push(mockFetchJsonWebKeys());
return keyFetcher.fetchPublicKeys().then(() => {
expect(https.request).to.have.been.calledOnce;
return keyFetcher.fetchPublicKeys();
}).then(() => expect(https.request).to.have.been.calledOnce);
});
it('should refresh the public keys after the previous set of keys expire', () => {
mockedRequests.push(mockFetchJsonWebKeys());
mockedRequests.push(mockFetchJsonWebKeys());
mockedRequests.push(mockFetchJsonWebKeys());
clock = sinon.useFakeTimers(1000);
return keyFetcher.fetchPublicKeys().then(() => {
expect(https.request).to.have.been.calledOnce;
clock!.tick((SIX_HOURS_IN_SECONDS - 1) * 1000);
return keyFetcher.fetchPublicKeys();
}).then(() => {
expect(https.request).to.have.been.calledOnce;
clock!.tick(SIX_HOURS_IN_SECONDS * 1000); // 6 hours in milliseconds
return keyFetcher.fetchPublicKeys();
}).then(() => {
// App check keys do not contain cache headers so we cache the keys for 6 hours.
// 6 hours has passed
expect(https.request).to.have.been.calledTwice;
clock!.tick((SIX_HOURS_IN_SECONDS - 1) * 1000);
return keyFetcher.fetchPublicKeys();
}).then(() => {
expect(https.request).to.have.been.calledTwice;
clock!.tick(SIX_HOURS_IN_SECONDS * 1000);
return keyFetcher.fetchPublicKeys();
}).then(() => {
// 12 hours have passed
expect(https.request).to.have.been.calledThrice;
});
});
it('should be rejected if fetching the public keys fails', () => {
mockedRequests.push(mockFailedFetchJsonWebKeys());
return keyFetcher.fetchPublicKeys()
.should.eventually.be.rejectedWith('message');
});
it('should be rejected if fetching the public keys returns a response with an error message', () => {
mockedRequests.push(mockFetchJsonWebKeysWithErrorResponse());
return keyFetcher.fetchPublicKeys()
.should.eventually.be.rejectedWith('Error fetching Json Web Keys');
});
});
}); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
AFDEndpoint,
AFDEndpointsListByProfileOptionalParams,
Usage,
AFDEndpointsListResourceUsageOptionalParams,
AFDEndpointsGetOptionalParams,
AFDEndpointsGetResponse,
AFDEndpointsCreateOptionalParams,
AFDEndpointsCreateResponse,
AFDEndpointUpdateParameters,
AFDEndpointsUpdateOptionalParams,
AFDEndpointsUpdateResponse,
AFDEndpointsDeleteOptionalParams,
AfdPurgeParameters,
AFDEndpointsPurgeContentOptionalParams,
ValidateCustomDomainInput,
AFDEndpointsValidateCustomDomainOptionalParams,
AFDEndpointsValidateCustomDomainResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a AFDEndpoints. */
export interface AFDEndpoints {
/**
* Lists existing AzureFrontDoor endpoints.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param options The options parameters.
*/
listByProfile(
resourceGroupName: string,
profileName: string,
options?: AFDEndpointsListByProfileOptionalParams
): PagedAsyncIterableIterator<AFDEndpoint>;
/**
* Checks the quota and actual usage of endpoints under the given CDN profile.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param options The options parameters.
*/
listResourceUsage(
resourceGroupName: string,
profileName: string,
endpointName: string,
options?: AFDEndpointsListResourceUsageOptionalParams
): PagedAsyncIterableIterator<Usage>;
/**
* Gets an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
* subscription, resource group and profile.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
profileName: string,
endpointName: string,
options?: AFDEndpointsGetOptionalParams
): Promise<AFDEndpointsGetResponse>;
/**
* Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
* subscription, resource group and profile.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param endpoint Endpoint properties
* @param options The options parameters.
*/
beginCreate(
resourceGroupName: string,
profileName: string,
endpointName: string,
endpoint: AFDEndpoint,
options?: AFDEndpointsCreateOptionalParams
): Promise<
PollerLike<
PollOperationState<AFDEndpointsCreateResponse>,
AFDEndpointsCreateResponse
>
>;
/**
* Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
* subscription, resource group and profile.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param endpoint Endpoint properties
* @param options The options parameters.
*/
beginCreateAndWait(
resourceGroupName: string,
profileName: string,
endpointName: string,
endpoint: AFDEndpoint,
options?: AFDEndpointsCreateOptionalParams
): Promise<AFDEndpointsCreateResponse>;
/**
* Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
* subscription, resource group and profile. Only tags can be updated after creating an endpoint. To
* update origins, use the Update Origin operation. To update origin groups, use the Update Origin
* group operation. To update domains, use the Update Custom Domain operation.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param endpointUpdateProperties Endpoint update properties
* @param options The options parameters.
*/
beginUpdate(
resourceGroupName: string,
profileName: string,
endpointName: string,
endpointUpdateProperties: AFDEndpointUpdateParameters,
options?: AFDEndpointsUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<AFDEndpointsUpdateResponse>,
AFDEndpointsUpdateResponse
>
>;
/**
* Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
* subscription, resource group and profile. Only tags can be updated after creating an endpoint. To
* update origins, use the Update Origin operation. To update origin groups, use the Update Origin
* group operation. To update domains, use the Update Custom Domain operation.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param endpointUpdateProperties Endpoint update properties
* @param options The options parameters.
*/
beginUpdateAndWait(
resourceGroupName: string,
profileName: string,
endpointName: string,
endpointUpdateProperties: AFDEndpointUpdateParameters,
options?: AFDEndpointsUpdateOptionalParams
): Promise<AFDEndpointsUpdateResponse>;
/**
* Deletes an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
* subscription, resource group and profile.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
profileName: string,
endpointName: string,
options?: AFDEndpointsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
* subscription, resource group and profile.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
profileName: string,
endpointName: string,
options?: AFDEndpointsDeleteOptionalParams
): Promise<void>;
/**
* Removes a content from AzureFrontDoor.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param contents The list of paths to the content and the list of linked domains to be purged. Path
* can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory with a
* wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
* @param options The options parameters.
*/
beginPurgeContent(
resourceGroupName: string,
profileName: string,
endpointName: string,
contents: AfdPurgeParameters,
options?: AFDEndpointsPurgeContentOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Removes a content from AzureFrontDoor.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param contents The list of paths to the content and the list of linked domains to be purged. Path
* can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory with a
* wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
* @param options The options parameters.
*/
beginPurgeContentAndWait(
resourceGroupName: string,
profileName: string,
endpointName: string,
contents: AfdPurgeParameters,
options?: AFDEndpointsPurgeContentOptionalParams
): Promise<void>;
/**
* Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the CDN profile which is unique within the resource group.
* @param endpointName Name of the endpoint under the profile which is unique globally.
* @param customDomainProperties Custom domain to be validated.
* @param options The options parameters.
*/
validateCustomDomain(
resourceGroupName: string,
profileName: string,
endpointName: string,
customDomainProperties: ValidateCustomDomainInput,
options?: AFDEndpointsValidateCustomDomainOptionalParams
): Promise<AFDEndpointsValidateCustomDomainResponse>;
} | the_stack |
import cx from 'classnames';
import React from 'react';
import ReactDOM from 'react-dom';
import { Keyframes } from 'styled-components';
import { DOCUMENT_BODY, OverlayBehaviorContext, OverlayBehaviorContextType } from '../../providers';
import { mergeRefs } from '../../utils';
import { domUtils } from '../virtual-list/dom-utils';
import { ANIMATE_ANIMATED, ANIMATE_PREFIX, Disposable, startAnimate } from './overlay-utils/animate-utils';
import { animations } from './overlay-utils/animations';
import { batchedUpdates } from './overlay-utils/batchUpdate';
import { OverlayManager } from './overlay-utils/OverlayManager';
export interface IOverlayCloseActions {
/**
* 是否支持 esc 按键关闭弹层
* @category 浮层交互
* */
canCloseByEsc?: boolean;
/**
* 点击弹层外部区域是否关闭弹层(注意背景层也被认为是外部)
* @category 浮层交互
* */
canCloseByOutSideClick?: boolean;
}
// 浮层的相关生命周期定义
export interface IOverlayLifecycles {
/**
* 浮层即将被打开时的回调
* @category 浮层生命周期
*/
beforeOpen?(state?: any): Promise<IOverlayAnimationProps>;
/** 浮层打开时的回调
* @category 浮层生命周期
*/
onOpen?(): void;
/** 浮层打开时的回调
* @category 浮层生命周期
*/
afterOpen?(): void;
/**
* 浮层即将被关闭时的回调
* @category 浮层生命周期
*/
beforeClose?(): IOverlayAnimationProps;
/**
* 浮层关闭时的回调
* @category 浮层生命周期
*/
onClose?(): void;
/** 浮层关闭后的回调
* @category 浮层生命周期
*/
afterClose?(): void;
}
export interface IOverlayBackdropProps {
/**
* 是否展示背景层
* @category 背景层
* */
hasBackdrop?: boolean;
/** @category 背景层 */
backdropStyle?: React.CSSProperties;
/** @category 背景层 */
backdropClassName?: string;
}
export interface IOverlayAnimationProps {
/**
* 动画持续时间(注意该 prop 会作为 CSS 变量的值,使用时要带上单位,例如 `'500ms'`)
* @category 浮层动画
* @default 200ms
*/
animationDuration?: string;
/**
* 弹层的出现和消失的动画,可以用 Overlay.animations.{name} 来引用弹层组件内置的动画效果
* @category 浮层动画
* */
animation?:
| false
| {
in: string | Keyframes;
out: string | Keyframes;
};
}
export interface IOverlayPortalProps {
/** 是否使用 portal 来渲染弹层内容
* @category 浮层容器 */
usePortal?: boolean;
/** 渲染组件的容器
* @category 浮层容器 */
portalContainer?: HTMLElement | typeof DOCUMENT_BODY;
/** 是否禁用容器的滚动
* @category 浮层容器 */
disableScroll?: boolean | 'force';
}
export interface OverlayProps
extends IOverlayCloseActions,
IOverlayLifecycles,
IOverlayBackdropProps,
IOverlayAnimationProps,
IOverlayPortalProps {
overlayKey?: string;
/** 是否显示弹层 */
visible: boolean;
/** 弹层请求关闭时触发事件的回调函数 */
onRequestClose?(reason: any): void;
/** 弹层的根节点的样式类 */
className?: string;
/** 弹层的根节点的内联样式 */
style?: React.CSSProperties;
/** 弹层内容 */
children?: React.ReactNode;
/** 使用 render prop 的形式指定弹层内容,用于精确控制 DOM 结构 */
renderChildren(pass: { ref: React.RefObject<Element>; children: React.ReactNode }): React.ReactNode;
wrapperRef?: React.Ref<HTMLDivElement>;
safeNodes?: (Node | (() => Node))[];
/**
* 是否关联到 portalContainer 上的 overlay manager.
* 该属性一般保持默认即可。
*/
attachOverlayManager?: boolean;
}
interface OverlayState {
prevVisible: boolean;
exiting: boolean;
}
// overlay 内容的默认渲染方法
const defaultRenderChildren: OverlayProps['renderChildren'] = ({ ref, children }) => (
<div ref={ref as React.RefObject<HTMLDivElement>}>{children}</div>
);
/** Overlay 注释文档 */
export class Overlay extends React.Component<OverlayProps, OverlayState> {
static isCustomPortalContainer(portalContainer?: HTMLElement | typeof DOCUMENT_BODY) {
return portalContainer != null && portalContainer !== 'DOCUMENT_BODY' && !domUtils.isBody(portalContainer);
}
static readonly contextType = OverlayBehaviorContext;
context: OverlayBehaviorContextType;
static readonly defaultRenderChildren = defaultRenderChildren;
static readonly animations = animations;
static readonly DOCUMENT_BODY = DOCUMENT_BODY;
static defaultProps = {
usePortal: true,
safeNodes: [] as OverlayProps['safeNodes'],
canCloseByEsc: true,
canCloseByOutSideClick: true,
animation: { in: animations.fadeIn, out: animations.fadeOut },
renderChildren: Overlay.defaultRenderChildren,
disableScroll: false,
attachOverlayManager: true,
animationDuration: '200ms',
};
static getDerivedStateFromProps(props: Readonly<OverlayProps>, state: Readonly<OverlayState>): Partial<OverlayState> {
let nextExiting = state.exiting;
if (state.prevVisible && !props.visible) {
nextExiting = true;
} else if (!state.prevVisible && props.visible) {
nextExiting = false;
}
return {
prevVisible: props.visible,
exiting: nextExiting,
};
}
// 微应用场景下,每个 portalContainer 都需要一个 OverlayManager
// 故这里用一个 map 来管理所有的 manager
private static managerMap = new Map<Element, OverlayManager>();
// 获取 portalContainer 对应的 OverlayManager 实例
static getManager(portalContainer: HTMLElement | typeof DOCUMENT_BODY) {
if (portalContainer === DOCUMENT_BODY) {
portalContainer = typeof document === 'undefined' ? null : document.body;
}
if (portalContainer == null) {
console.warn('[@rexd/core] Overlay.getManager(portalContainer) 调用参数 portalContainer 为 null');
return;
}
if (!Overlay.managerMap.has(portalContainer)) {
Overlay.managerMap.set(portalContainer, new OverlayManager(portalContainer));
}
return Overlay.managerMap.get(portalContainer);
}
private resolvePortalContainer() {
let result = this.props.portalContainer ?? this.context.portalContainer;
if (result === DOCUMENT_BODY) {
// 这里判断 document 是为了兼容 SSR 的情况
result = typeof document !== 'undefined' ? document.body : null;
}
return result;
}
constructor(props: OverlayProps) {
super(props);
this.state = {
prevVisible: props.visible,
exiting: false,
};
}
private _wrapperRef = React.createRef<HTMLDivElement>();
private innerRef = React.createRef<Element>();
// overlay 元素动画的实例,用于「下一个动画开始前 取消上一个动画」
private overlayAnimateInst: Disposable = null;
componentDidMount() {
const { visible } = this.props;
if (visible) {
this.doOpenOverlay();
}
}
private resolveEnterAnimation(instruction: IOverlayAnimationProps): null | string | Keyframes {
const { animation: animationProp } = this.props;
if (animationProp === false || instruction?.animation === false) {
return null;
}
return instruction?.animation?.in ?? animationProp?.in ?? null;
}
// 处理打开浮层的动画
private async doOpenOverlay() {
const { beforeOpen, onOpen, afterOpen, attachOverlayManager } = this.props;
if (attachOverlayManager) {
Overlay.getManager(this.resolvePortalContainer()).add(this);
}
const inner = this.innerRef.current;
if (inner == null) {
return;
}
inner.classList.add('rex-overlay-inner');
const overlayOpenInstruction = await beforeOpen?.();
this.overlayAnimateInst?.dispose();
this.overlayAnimateInst = startAnimate(inner, this.resolveEnterAnimation(overlayOpenInstruction), () => {
afterOpen?.();
this.overlayAnimateInst = null;
});
onOpen?.();
}
private resolveExitAnimation(instruction: IOverlayAnimationProps): null | string | Keyframes {
const { animation: animationProp } = this.props;
if (animationProp === false || instruction?.animation === false) {
return null;
}
return instruction?.animation?.out ?? animationProp?.out ?? null;
}
private async doCloseOverlay(force = false) {
const { beforeClose, onClose, afterClose, attachOverlayManager } = this.props;
if (attachOverlayManager) {
Overlay.getManager(this.resolvePortalContainer()).delete(this);
}
const inner = this.innerRef.current;
if (inner == null) {
return;
}
const overlayCloseInstruction = beforeClose?.();
this.overlayAnimateInst?.dispose();
if (force) {
this.overlayAnimateInst = null;
onClose?.();
// 强制关闭的情况下,不再调用 afterClose()
} else {
this.overlayAnimateInst = startAnimate(inner, this.resolveExitAnimation(overlayCloseInstruction), () => {
batchedUpdates(() => {
this.setState({ exiting: false });
this.overlayAnimateInst = null;
afterClose?.();
});
});
onClose?.();
}
}
componentDidUpdate(prevProps: Readonly<OverlayProps>, prevState: Readonly<OverlayState>) {
if (prevProps.disableScroll !== this.props.disableScroll) {
console.warn('[@rexd/core] 浮层组件 props.disableScroll 不支持动态变化');
}
if (prevProps.attachOverlayManager !== this.props.attachOverlayManager) {
console.warn('[@rexd/core] 浮层组件 props.attachOverlayManager 不支持动态变化');
}
if (prevProps.visible && !this.props.visible) {
this.doCloseOverlay();
}
if (!prevProps.visible && this.props.visible) {
this.doOpenOverlay();
}
}
componentWillUnmount() {
if (this.props.visible) {
this.doCloseOverlay(true);
}
this.overlayAnimateInst?.dispose();
}
private composedWrapperRef = mergeRefs(this._wrapperRef, this.props.wrapperRef);
// 判断鼠标点击位置是否在浮层内部
public isInsideClick = (clickNode: Node) => {
// 背景层总是认为是外部
if ((clickNode as Element).classList?.contains?.('rex-overlay-backdrop')) {
return false;
}
const { safeNodes } = this.props;
const wrapper = this._wrapperRef.current;
return (
wrapper?.contains(clickNode) ||
safeNodes.some((safe) => {
if (typeof safe === 'function') {
safe = safe();
}
return safe?.contains(clickNode);
})
);
};
render() {
const {
usePortal,
children,
renderChildren,
animationDuration,
className,
style,
hasBackdrop,
visible,
overlayKey,
attachOverlayManager,
} = this.props;
const portalContainer = this.resolvePortalContainer();
if (portalContainer == null) {
// SSR 场景下可能会找不到 portalContainer,这里返回 null 即可
return null;
}
const { exiting } = this.state;
if (!visible && !exiting) {
return null;
}
let content = (
<div
className={cx('rex-overlay-wrapper', { exiting, detached: !attachOverlayManager }, className)}
style={{ '--animate-duration': animationDuration, ...style } as any}
ref={this.composedWrapperRef}
>
{hasBackdrop && (
<div
className={cx(
'rex-overlay-backdrop',
this.props.backdropClassName,
ANIMATE_ANIMATED,
exiting
? `${ANIMATE_PREFIX}${animations.fadeOut.getName()}`
: `${ANIMATE_PREFIX}${animations.fadeIn.getName()}`,
)}
style={{
position: Overlay.isCustomPortalContainer(portalContainer) ? 'absolute' : undefined,
...this.props.backdropStyle,
}}
/>
)}
{renderChildren({ ref: this.innerRef, children })}
</div>
);
if (usePortal) {
content = ReactDOM.createPortal(content, portalContainer, overlayKey);
}
return content;
}
} | the_stack |
class Core {
public readonly mapWidth: number;
public readonly mapHeight: number;
private readonly map: Direction[][];
private fromX: number;
private fromY: number;
public constructor(mapWidth: number, mapHeight: number) {
this.map = new Array<Direction[]>(mapHeight);
for (var y = 0; y < mapHeight; y++) {
this.map[y] = new Array<Direction>(mapWidth);
for (var x = 0; x < mapWidth; x++) {
this.map[y][x] = Direction.None;
}
}
this.mapWidth = mapWidth;
this.mapHeight = mapHeight;
this.fromX = NaN;
this.fromY = NaN;
}
public placeObstacle(x: number, y: number, obstacle: number): boolean {
if (y < 0 || y >= this.map.length || x < 0 || x >= this.map[0].length) {
return false;
}
if (this.map[y][x] < 0) {
this.map[y][x] = Direction.None; // clear obstacle
return false;
} else {
// less than zero -> obstacle
// 0 -> none
this.map[y][x] = 0 - Math.abs(obstacle);
return true;
}
}
public isObstacle(x: number, y: number): boolean {
if (y < 0 || y >= this.map.length || x < 0 || x >= this.map[0].length) {
return true;
}
return this.map[y][x] < 0;
}
public clearObstacles(): ReadonlyArray<Step> {
var obstacles = new Array<Step>();
for (var y = 0; y < this.map.length; y++) {
for (var x = 0; x < this.map[y].length; x++) {
if (this.map[y][x] < 0) { // obstacle
obstacles.push(new Step(x, y, this.map[y][x], this.map[y][x]));
this.map[y][x] = Direction.None;
}
}
}
return obstacles;
}
public createPathfindingRequestBody(body: PathfindingRequestBody, x: number, y: number): PathfindingRequestStatus {
if (isNaN(this.fromX) && isNaN(this.fromY)) {
this.fromX = x;
this.fromY = y;
return PathfindingRequestStatus.Initiated;
}
if (this.fromX == x && this.fromY == y) {
this.fromX = NaN;
this.fromY = NaN;
return PathfindingRequestStatus.None;
}
body.fromX = this.fromX;
body.fromY = this.fromY;
body.goalX = x;
body.goalY = y;
body.map = this.map;
this.fromX = NaN;
this.fromY = NaN;
return PathfindingRequestStatus.Ready; // Ready for sending request.
}
public assignDirection(step: Step) : Step {
var original = this.map[step.y][step.x];
var dir = step.direction;
if (original >= 0) { // less than zero -> Obstacle
dir = original | dir;
step.undo = original ^ dir; // What we should do if we want to undo
}
this.map[step.y][step.x] = dir;
return new Step(step.x, step.y, dir, step.undo);
}
public assignDirections(solution: Array<Step>): ReadonlyArray<Step> {
var assigned = new Array<Step>();
if (solution.length == 0) {
return assigned;
}
for (let i = 0; i < solution.length - 1; i++) {
let x1 = solution[i].x;
let y1 = solution[i].y;
let x2 = solution[i + 1].x;
let y2 = solution[i + 1].y;
if (typeof solution[i].direction === "undefined" || solution[i].direction == null || solution[i].direction < 0) { // less than zero -> Obstacle
solution[i].direction = Direction.None;
}
if (x1 > x2) {
solution[i].direction = solution[i].direction | Direction.Left;
solution[i + 1].direction = solution[i + 1].direction | Direction.Right;
}
else if (x1 < x2) {
solution[i].direction = solution[i].direction | Direction.Right;
solution[i + 1].direction = solution[i + 1].direction | Direction.Left;
}
if (y1 > y2) {
solution[i].direction = solution[i].direction | Direction.Up;
solution[i + 1].direction = solution[i + 1].direction | Direction.Down;
}
else if (y1 < y2) {
solution[i].direction = solution[i].direction | Direction.Down;
solution[i + 1].direction = solution[i + 1].direction | Direction.Up;
}
assigned.push(this.assignDirection(solution[i]));
}
assigned.push(this.assignDirection(solution[solution.length - 1]));
return assigned;
}
public removeDirection(step: Step) {
var original = this.map[step.y][step.x];
if (original >= 0) { // less than zero -> Obstacle
this.map[step.y][step.x] = original & ~step.undo;
}
step.direction = this.map[step.y][step.x];
}
public removeDirections(solution: Array<Step>): ReadonlyArray<Step> {
for (let i = 0; i < solution.length; i++) {
this.removeDirection(solution[i]);
}
return solution.map(step => new Step(step.x, step.y, step.direction, step.undo));
}
}
class Step {
public x: number; // unit: tile
public y: number; // unit: tile
public direction: Direction;
public undo: Direction;
constructor(x: number, y: number, dir: Direction, undo: Direction) {
this.x = x;
this.y = y;
this.direction = dir;
this.undo = undo;
}
public getDirectionShortName(): string {
var name = "";
if ((this.direction & Direction.Down) == Direction.Down)
name += "d";
if ((this.direction & Direction.Left) == Direction.Left)
name += "l";
if ((this.direction & Direction.Right) == Direction.Right)
name += "r";
if ((this.direction & Direction.Up) == Direction.Up)
name += "u";
switch (name) {
case "u":
case "d":
name = "du";
break;
case "l":
case "r":
name = "lr";
break;
}
return name;
}
}
enum PathfindingRequestStatus {
None = 0,
Initiated = 1,
Ready = 2,
}
enum Direction {
None = 0,
Up = 1,
Down = 2,
Left = 4,
Right = 8
}
interface Pathfinding {
heuristics: string[];
algorithm: string;
fromX: number;
fromY: number;
goalX: number;
goalY: number;
toSelectManyExpression(mapWidth: number, mapHeight: number): string[];
toExceptExpression(mapWidth: number, mapHeight: number): string[];
toWhereOnlyExpression(mapWidth: number, mapHeight: number): string[];
}
class PathfindingSettings {
}
class PathfindingRequestBody implements Pathfinding {
public fromX: number;
public fromY: number;
public goalX: number;
public goalY: number;
public map: number[][];
public heuristics: string[];
public algorithm: string;
public constructor() {
this.fromX = 0;
this.fromY = 0;
this.goalX = 0;
this.goalY = 0;
this.algorithm = "AStar";
this.heuristics = new Array<string>();
this.heuristics.push("GetManhattanDistance");
}
public toSelectManyExpression(mapWidth: number, mapHeight: number): string[] {
var linq = [
PathfindingRequestBody.getStartStatement(this.fromX, this.fromY),
PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY),
PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight),
PathfindingRequestBody.getInitializationStatement(this.algorithm)
];
linq.push("var solution = from p in queryable");
linq.push(" from obstacle in GetMapObstacles()");
linq.push(" where boundary.Contains(p) && p != obstacle");
if (this.heuristics.length > 0) {
linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics));
}
linq.push(" select p;");
return linq;
}
public toExceptExpression(mapWidth: number, mapHeight: number): string[] {
var linq = [
PathfindingRequestBody.getStartStatement(this.fromX, this.fromY),
PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY),
PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight),
PathfindingRequestBody.getInitializationStatement(this.algorithm)
];
linq.push("var solution = from p in queryable.Except(GetMapObstacles())");
linq.push(" where boundary.Contains(p)");
if (this.heuristics.length > 0) {
linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics));
}
linq.push(" select p;");
return linq;
}
public toWhereOnlyExpression(mapWidth: number, mapHeight: number): string[] {
var linq = [
PathfindingRequestBody.getStartStatement(this.fromX, this.fromY),
PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY),
PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight),
PathfindingRequestBody.getInitializationStatement(this.algorithm)
];
linq.push("var obstacles = GetMapObstacles();");
linq.push("var solution = from p in queryable");
linq.push(" where boundary.Contains(p) && !obstacles.Contains(p)");
if (this.heuristics.length > 0) {
linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics));
}
linq.push(" select p;");
return linq;
}
public static getStartStatement(fromX: number, fromY: number): string {
return "var start = new Point(" + fromX + ", " + fromY + ");"
}
public static getGoalStatement(goalX: number, goalY: number): string {
return "var goal = new Point(" + goalX + ", " + goalY + ");"
}
public static getBoundaryStatement(mapWidth: number, mapHeight: number): string {
return "var boundary = new Rectangle(0, 0, " + mapWidth + ", " + mapHeight + ");"
}
public static getInitializationStatement(algorithm: string): string {
switch (algorithm) {
case "AStar":
return "var queryable = HeuristicSearch.AStar(start, goal, (s, i) => s.GetFourDirections(unit));";
case "BestFirstSearch":
return "var queryable = HeuristicSearch.BestFirstSearch(start, goal, (s, i) => s.GetFourDirections(unit));";
case "IterativeDeepeningAStar":
return "var queryable = HeuristicSearch.IterativeDeepeningAStar(start, goal, (s, i) => s.GetFourDirections(unit));";
case "RecursiveBestFirstSearch":
return "var queryable = HeuristicSearch.RecursiveBestFirstSearch(start, goal, (s, i) => s.GetFourDirections(unit));";
}
return "var queryable = HeuristicSearch.AStar(start, goal, (s, i) => s.GetFourDirections(unit));";
}
public static getOrderByThenByStatement(heuristics: ReadonlyArray<string>): string {
var statement = "orderby ";
var statements = new Array<string>();
for (var i = 0; i < heuristics.length; i++) {
switch (heuristics[i]) {
case "GetChebyshevDistance":
statements.push("p.GetChebyshevDistance(goal)");
break;
case "GetEuclideanDistance":
statements.push("p.GetEuclideanDistance(goal)");
break;
case "GetManhattanDistance":
statements.push("p.GetManhattanDistance(goal)");
break;
default:
statements.push("p.GetManhattanDistance(goal)");
break;
}
}
return statement + statements.join(", ");
}
}
class Detail {
public level: number;
public step: Step;
public candidates: ReadonlyArray<Step>;
}
class PathfindingHistory implements Pathfinding {
public readonly fromX: number;
public readonly fromY: number;
public readonly goalX: number;
public readonly goalY: number;
public readonly steps: ReadonlyArray<Step>;
public readonly details: Array<Detail>;
public readonly path: ReadonlyArray<PathTile>;
public readonly unvisited: ReadonlyArray<UnvisitedTile>;
public readonly heuristics: string[];
public readonly algorithm: string;
public readonly algorithmShortName: string;
public readonly color: string;
public isVisible: boolean;
constructor(request: PathfindingRequestBody, steps: Array<Step>, details: Array<Detail>) {
this.fromX = request.fromX;
this.fromY = request.fromY;
this.goalX = request.goalX;
this.goalY = request.goalY;
this.color = PathfindingHistory.getAlgorithmPathColor(request.algorithm);
this.steps = steps.map(step => new Step(step.x, step.y, step.direction, step.undo));
this.details = details;
this.path = steps.map((p, i) => new PathTile(p.x, p.y, i, this.color));
this.unvisited = UnvisitedTile.merge(details.map(d => new UnvisitedTile(d.step.x, d.step.y, d.level, this.color)));
this.heuristics = request.heuristics;
this.algorithm = request.algorithm;
this.algorithmShortName = PathfindingHistory.getAlgorithmShortName(request.algorithm);
this.isVisible = false;
}
public findTileWithStep(s: Step): SolutionTile {
var index = this.path.findIndex(p => p.x === s.x && p.y === s.y);
if (index > -1) {
return this.path[index];
}
index = this.unvisited.findIndex(u => u.x === s.x && u.y === s.y);
if (index > -1) {
return this.unvisited[index];
}
return null;
}
public checkIfStepExists(s: Step): boolean {
return this.path.some(p => p.x === s.x && p.y === s.y) || this.unvisited.some(u => u.x === s.x && u.y === s.y);
}
public toSelectManyExpression(mapWidth: number, mapHeight: number): string[] {
var linq = [
PathfindingRequestBody.getStartStatement(this.fromX, this.fromY),
PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY),
PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight),
PathfindingRequestBody.getInitializationStatement(this.algorithm)
];
linq.push("var solution = from p in queryable");
linq.push(" from obstacle in GetMapObstacles()");
linq.push(" where boundary.Contains(p) && p != obstacle");
linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics));
linq.push(" select p;");
return linq;
}
public toExceptExpression(mapWidth: number, mapHeight: number): string[] {
var linq = [
PathfindingRequestBody.getStartStatement(this.fromX, this.fromY),
PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY),
PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight),
PathfindingRequestBody.getInitializationStatement(this.algorithm)
];
linq.push("var solution = from p in queryable.Except(GetMapObstacles())");
linq.push(" where boundary.Contains(p)");
linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics));
linq.push(" select p;");
linq.push(" // --"); // Keeps same number of lines.
return linq;
}
public toWhereOnlyExpression(mapWidth: number, mapHeight: number): string[] {
var linq = [
PathfindingRequestBody.getStartStatement(this.fromX, this.fromY),
PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY),
PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight),
PathfindingRequestBody.getInitializationStatement(this.algorithm)
];
linq.push("var obstacles = GetMapObstacles();");
linq.push("var solution = from p in queryable");
linq.push(" where boundary.Contains(p) && !obstacles.Contains(p)");
linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics));
linq.push(" select p;");
return linq;
}
public static getAlgorithmShortName(algorithm: string): string {
switch (algorithm) {
case "AStar":
return "A*";
case "BestFirstSearch":
return "BFS";
case "IterativeDeepeningAStar":
return "IDA*";
case "RecursiveBestFirstSearch":
return "RBFS";
default:
return "A*";
}
}
public static getAlgorithmPathColor(algorithm: string): string {
switch (algorithm) {
case "AStar":
return "#17a2b8";
case "BestFirstSearch":
return "#dc3545";
case "IterativeDeepeningAStar":
return "#343a40";
case "RecursiveBestFirstSearch":
return "#ffc107";
default:
return "#17a2b8";
}
}
} | the_stack |
'use strict';
import { inject, injectable } from 'inversify';
import { ProgressLocation, ConfigurationTarget, Uri, window, workspace } from 'vscode';
import { IApplicationShell, ICommandManager } from '../../../common/application/types';
import { traceInfo, traceError } from '../../../common/logger';
import { IConfigurationService, IDisposableRegistry } from '../../../common/types';
import { DataScience } from '../../../common/utils/localize';
import { StopWatch } from '../../../common/utils/stopWatch';
import { sendTelemetryEvent } from '../../../telemetry';
import { Commands, Telemetry } from '../../constants';
import { getNotebookMetadata } from '../../notebook/helpers/helpers';
import { trackKernelResourceInformation, sendKernelTelemetryEvent } from '../../telemetry/telemetry';
import {
IDataScienceCommandListener,
IInteractiveWindowProvider,
INotebookProvider,
InterruptResult,
IStatusProvider
} from '../../types';
import { JupyterKernelPromiseFailedError } from './jupyterKernelPromiseFailedError';
import { IKernel, IKernelProvider } from './types';
@injectable()
export class KernelCommandListener implements IDataScienceCommandListener {
private kernelInterruptedDontAskToRestart: boolean = false;
constructor(
@inject(IStatusProvider) private statusProvider: IStatusProvider,
@inject(IDisposableRegistry) private disposableRegistry: IDisposableRegistry,
@inject(IApplicationShell) private applicationShell: IApplicationShell,
@inject(IKernelProvider) private kernelProvider: IKernelProvider,
@inject(IInteractiveWindowProvider) private interactiveWindowProvider: IInteractiveWindowProvider,
@inject(IConfigurationService) private configurationService: IConfigurationService,
@inject(INotebookProvider) private notebookProvider: INotebookProvider
) {}
public register(commandManager: ICommandManager): void {
this.disposableRegistry.push(
commandManager.registerCommand(
Commands.NotebookEditorInterruptKernel,
(context?: { notebookEditor: { notebookUri: Uri } } | Uri) => {
if (context && 'notebookEditor' in context) {
void this.interruptKernel(context?.notebookEditor.notebookUri);
} else {
void this.interruptKernel(context);
}
}
)
);
this.disposableRegistry.push(
commandManager.registerCommand(
Commands.NotebookEditorRestartKernel,
(context?: { notebookEditor: { notebookUri: Uri } } | Uri) => {
if (context && 'notebookEditor' in context) {
void this.restartKernel(context?.notebookEditor.notebookUri);
} else {
void this.restartKernel(context);
}
}
)
);
this.disposableRegistry.push(
commandManager.registerCommand(
Commands.InterruptKernel,
(context?: { notebookEditor: { notebookUri: Uri } }) =>
this.interruptKernel(context?.notebookEditor.notebookUri)
)
);
this.disposableRegistry.push(
commandManager.registerCommand(
Commands.RestartKernel,
(context?: { notebookEditor: { notebookUri: Uri } }) =>
this.restartKernel(context?.notebookEditor.notebookUri)
)
);
}
public async interruptKernel(notebookUri: Uri | undefined): Promise<void> {
const uri =
notebookUri ??
window.activeNotebookEditor?.document.uri ??
this.interactiveWindowProvider.activeWindow?.notebookUri ??
(window.activeTextEditor?.document.uri &&
this.interactiveWindowProvider.get(window.activeTextEditor.document.uri)?.notebookUri);
const document = workspace.notebookDocuments.find((document) => document.uri.toString() === uri?.toString());
if (document === undefined) {
return;
}
const kernel = this.kernelProvider.get(document);
if (!kernel) {
traceInfo(`Interrupt requested & no kernel.`);
return;
}
trackKernelResourceInformation(kernel.resourceUri, { interruptKernel: true });
const status = this.statusProvider.set(DataScience.interruptKernelStatus());
try {
traceInfo(`Interrupt requested & sent for ${document.uri} in notebookEditor.`);
const result = await kernel.interrupt();
if (result === InterruptResult.TimedOut) {
const message = DataScience.restartKernelAfterInterruptMessage();
const yes = DataScience.restartKernelMessageYes();
const no = DataScience.restartKernelMessageNo();
const v = await this.applicationShell.showInformationMessage(message, { modal: true }, yes, no);
if (v === yes) {
this.kernelInterruptedDontAskToRestart = true;
await this.restartKernel(document.uri);
}
}
} catch (err) {
traceError('Failed to interrupt kernel', err);
void this.applicationShell.showErrorMessage(err);
} finally {
this.kernelInterruptedDontAskToRestart = false;
status.dispose();
}
}
private async restartKernel(notebookUri: Uri | undefined) {
const uri =
notebookUri ??
window.activeNotebookEditor?.document.uri ??
this.interactiveWindowProvider.activeWindow?.notebookUri ??
(window.activeTextEditor?.document.uri &&
this.interactiveWindowProvider.get(window.activeTextEditor.document.uri)?.notebookUri);
const document = workspace.notebookDocuments.find((document) => document.uri.toString() === uri?.toString());
if (document === undefined) {
return;
}
sendTelemetryEvent(Telemetry.RestartKernelCommand);
const kernel = this.kernelProvider.get(document);
if (kernel) {
trackKernelResourceInformation(kernel.resourceUri, { restartKernel: true });
if (await this.shouldAskForRestart(document.uri)) {
// Ask the user if they want us to restart or not.
const message = DataScience.restartKernelMessage();
const yes = DataScience.restartKernelMessageYes();
const dontAskAgain = DataScience.restartKernelMessageDontAskAgain();
const no = DataScience.restartKernelMessageNo();
const response = await this.applicationShell.showInformationMessage(
message,
{ modal: true },
yes,
dontAskAgain,
no
);
if (response === dontAskAgain) {
await this.disableAskForRestart(document.uri);
void this.applicationShell.withProgress(
{ location: ProgressLocation.Notification, title: DataScience.restartingKernelStatus() },
() => this.restartKernelInternal(kernel)
);
} else if (response === yes) {
void this.applicationShell.withProgress(
{ location: ProgressLocation.Notification, title: DataScience.restartingKernelStatus() },
() => this.restartKernelInternal(kernel)
);
}
} else {
void this.applicationShell.withProgress(
{ location: ProgressLocation.Notification, title: DataScience.restartingKernelStatus() },
() => this.restartKernelInternal(kernel)
);
}
}
}
private async restartKernelInternal(kernel: IKernel): Promise<void> {
// Set our status
const status = this.statusProvider.set(DataScience.restartingKernelStatus());
const stopWatch = new StopWatch();
try {
await kernel.restart();
sendKernelTelemetryEvent(kernel.resourceUri, Telemetry.NotebookRestart, stopWatch.elapsedTime);
} catch (exc) {
// If we get a kernel promise failure, then restarting timed out. Just shutdown and restart the entire server.
// Note, this code might not be necessary, as such an error is thrown only when interrupting a kernel times out.
sendKernelTelemetryEvent(
kernel.resourceUri,
Telemetry.NotebookRestart,
stopWatch.elapsedTime,
undefined,
exc
);
if (exc instanceof JupyterKernelPromiseFailedError && kernel) {
// Old approach (INotebook is not exposed in IKernel, and INotebook will eventually go away).
const notebook = await this.notebookProvider.getOrCreateNotebook({
resource: kernel.resourceUri,
identity: kernel.notebookDocument.uri,
getOnly: true
});
if (notebook) {
await notebook.dispose();
}
await this.notebookProvider.connect({
getOnly: false,
disableUI: false,
resource: kernel.resourceUri,
metadata: getNotebookMetadata(kernel.notebookDocument)
});
} else {
traceError('Failed to restart the kernel', exc);
if (exc) {
// Show the error message
void this.applicationShell.showErrorMessage(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
exc instanceof Error ? exc.message : (exc as any).toString()
);
}
}
} finally {
status.dispose();
}
}
private async shouldAskForRestart(notebookUri: Uri): Promise<boolean> {
if (this.kernelInterruptedDontAskToRestart) {
return false;
}
const settings = this.configurationService.getSettings(notebookUri);
return settings && settings.askForKernelRestart === true;
}
private async disableAskForRestart(notebookUri: Uri): Promise<void> {
const settings = this.configurationService.getSettings(notebookUri);
if (settings) {
this.configurationService
.updateSetting('askForKernelRestart', false, undefined, ConfigurationTarget.Global)
.ignoreErrors();
}
}
} | the_stack |
import * as lodash from "lodash";
import UpdateFeedInfo from "../types/UpdateFeedInfo";
define(function (require, exports, module) {
const _: typeof lodash = node.require("lodash");
const getLogger = node.require("./utils").getLogger;
const log = getLogger("UpdateNotification");
const Dialogs = require("widgets/Dialogs");
const DefaultDialogs = require("widgets/DefaultDialogs");
const ExtensionManager = require("extensibility/ExtensionManager");
const PreferencesManager = require("preferences/PreferencesManager");
const NativeApp = require("utils/NativeApp");
const Strings = require("strings");
const UpdateDialogTemplate = require("text!htmlContent/update-dialog.html");
const UpdateListTemplate = require("text!htmlContent/update-list.html");
const Mustache = require("thirdparty/mustache/mustache");
// make sure the global brackets variable is loaded
require("utils/Global");
// duration of one day in milliseconds
const ONE_DAY = 1000 * 60 * 60 * 24;
// duration of two minutes in milliseconds
const TWO_MINUTES = 1000 * 60 * 2;
// Extract current build number from package.json version field 0.0.0
// major and minor should match Brackets, last number is build version
let _buildNumber = Number(brackets.metadata.version.match(/[0-9]+$/)[0]);
// Init default last build number
PreferencesManager.stateManager.definePreference("lastNotifiedBuildNumber", "number", 0);
// Init default last info URL fetch time
PreferencesManager.stateManager.definePreference("lastInfoURLFetchTime", "number", 0);
// Time of last registry check for update
PreferencesManager.stateManager.definePreference("lastExtensionRegistryCheckTime", "number", 0);
// Data about available updates in the registry
PreferencesManager.stateManager.definePreference("extensionUpdateInfo", "Array", []);
// URL to load version info from. By default this is loaded no more than once a day. If
// you force an update check it is always loaded.
// Information on all posted builds of Brackets. This is an Array, where each element is
// an Object with the following fields:
//
// {Number} buildNumber Number of the build
// {String} versionString String representation of the build number (ie "Release 0.40")
// {String} dateString Date of the build
// {String} releaseNotesURL URL of the release notes for this build
// {String} downloadURL URL to download this build
// {Array} newFeatures Array of new features in this build. Each entry has two fields:
// {String} name Name of the feature
// {String} description Description of the feature
//
// This array must be reverse sorted by buildNumber (newest build info first)
/**
* @private
* Flag that indicates if we've added a click handler to the update notification icon.
*/
let _addedClickHandler = false;
function transformAtomFeed(obj: any): UpdateFeedInfo {
const currentVersion = node.require("./package.json").version;
const GH = `https://github.com/zaggino/brackets-electron`;
let entries = _.get(obj, "feed.entry", []);
if (!_.isArray(entries)) { entries = [ entries ] as any; }
return entries.map((entry: any) => {
const version = entry.title._;
return {
buildNumber: version,
versionString: version,
dateString: entry.updated,
releaseNotesURL: GH + `/compare/v${currentVersion}...v${version}`,
downloadURL: GH + "/releases",
newFeatures: []
};
});
}
/**
* Get a data structure that has information for all builds of Brackets.
*
* If force is true, the information is always fetched from _versionInfoURL.
* If force is false, we try to use cached information. If more than
* 24 hours have passed since the last fetch, or if cached data can't be found,
* the data is fetched again.
*
* If new data is fetched and dontCache is false, the data is saved in preferences
* for quick fetching later.
* _versionInfoUrl is used for unit testing.
*/
function _getUpdateInformation(
force: boolean,
dontCache: boolean,
_versionInfoUrl?: string
): JQueryPromise<UpdateFeedInfo> {
// Last time the versionInfoURL was fetched
let lastInfoURLFetchTime = PreferencesManager.getViewState("lastInfoURLFetchTime");
const result = $.Deferred();
let fetchData = false;
let data: UpdateFeedInfo;
// If force is true, always fetch
if (force) {
fetchData = true;
}
// If we don't have data saved in prefs, fetch
data = PreferencesManager.getViewState("updateInfo");
if (!data) {
fetchData = true;
}
// If more than 24 hours have passed since our last fetch, fetch again
if ((new Date()).getTime() > lastInfoURLFetchTime + ONE_DAY) {
fetchData = true;
}
if (fetchData) {
const autoUpdater = electron.remote.require("./auto-updater");
const parseXml = node.require("./xml-utils").parseXml;
const UPDATE_SERVER_HOST = autoUpdater.UPDATE_SERVER_HOST;
const url = `https://${UPDATE_SERVER_HOST}/feed/channel/all.atom`;
$.ajax({
url,
cache: false
}).done(async function (_response, _textStatus, jqXHR) {
let jsData: any;
try {
jsData = await parseXml(jqXHR.responseText);
} catch (err) {
log.error(`Error parsing update feed xml: ${err}`);
return;
}
const updateInfo = transformAtomFeed(jsData);
if (!dontCache) {
lastInfoURLFetchTime = (new Date()).getTime();
PreferencesManager.setViewState("lastInfoURLFetchTime", lastInfoURLFetchTime);
PreferencesManager.setViewState("updateInfo", updateInfo);
}
result.resolve(updateInfo);
}).fail(function (jqXHR, status, error) {
// When loading data for unit tests, the error handler is
// called but the responseText is valid. Try to use it here,
// but *don't* save the results in prefs.
if (!jqXHR.responseText) {
// Text is NULL or empty string, reject().
result.reject();
return;
}
try {
data = JSON.parse(jqXHR.responseText);
result.resolve(data);
} catch (e) {
result.reject();
}
});
} else {
result.resolve(data);
}
return result.promise();
}
/**
* Show a dialog that shows the update
*/
function _showUpdateNotificationDialog(updates: UpdateFeedInfo): void {
Dialogs.showModalDialogUsingTemplate(Mustache.render(UpdateDialogTemplate, Strings))
.done(function (id: string) {
if (id === Dialogs.DIALOG_BTN_DOWNLOAD) {
// The first entry in the updates array has the latest download link
NativeApp.openURLInDefaultBrowser(updates[0].downloadURL);
}
});
// Populate the update data
const $dlg = $(".update-dialog.instance");
const $updateList = $dlg.find(".update-info");
// Make the update notification icon clickable again
_addedClickHandler = false;
(updates as any).Strings = Strings;
$updateList.html(Mustache.render(UpdateListTemplate, updates));
}
/**
* Calculate state of notification everytime registries are downloaded - no matter who triggered the download
*/
function _onRegistryDownloaded() {
const availableUpdates = ExtensionManager.getAvailableUpdates();
PreferencesManager.setViewState("extensionUpdateInfo", availableUpdates);
PreferencesManager.setViewState("lastExtensionRegistryCheckTime", (new Date()).getTime());
$("#toolbar-extension-manager").toggleClass("updatesAvailable", availableUpdates.length > 0);
}
/**
* Every 24 hours downloads registry information to check for update, but only if the registry download
* wasn't triggered by another action (like opening extension manager)
* If there isn't 24 hours elapsed from the last download, use cached information from last download
* to determine state of the update notification.
*/
function checkForExtensionsUpdate() {
const lastExtensionRegistryCheckTime = PreferencesManager.getViewState("lastExtensionRegistryCheckTime");
const timeOfNextCheck = lastExtensionRegistryCheckTime + ONE_DAY;
const currentTime = (new Date()).getTime();
// update icon according to previously saved information
let availableUpdates = PreferencesManager.getViewState("extensionUpdateInfo");
availableUpdates = ExtensionManager.cleanAvailableUpdates(availableUpdates);
$("#toolbar-extension-manager").toggleClass("updatesAvailable", availableUpdates.length > 0);
if (availableUpdates.length === 0) {
// icon is gray, no updates available
if (currentTime > timeOfNextCheck) {
// downloadRegistry, will be resolved in _onRegistryDownloaded
ExtensionManager.downloadRegistry().done(function () {
// schedule another check in 24 hours + 2 minutes
setTimeout(checkForExtensionsUpdate, ONE_DAY + TWO_MINUTES);
});
} else {
// schedule the download of the registry in appropriate time
setTimeout(checkForExtensionsUpdate, (timeOfNextCheck - currentTime) + TWO_MINUTES);
}
}
}
/**
* Check for updates. If "force" is true, update notification dialogs are always displayed
* (if an update is available). If "force" is false, the update notification is only
* displayed for newly available updates.
*
* If an update is available, show the "update available" notification icon in the title bar.
*
* @param {boolean} force If true, always show the notification dialog.
* @param {Object} _testValues This should only be used for testing purposes. See comments for details.
* @return {$.Promise} jQuery Promise object that is resolved or rejected after the update check is complete.
*/
function checkForUpdate(force: boolean = false, _testValues?: any) {
// This is the last version we notified the user about. If checkForUpdate()
// is called with "false", only show the update notification dialog if there
// is an update newer than this one. This value is saved in preferences.
let lastNotifiedBuildNumber = PreferencesManager.getViewState("lastNotifiedBuildNumber");
// The second param, if non-null, is an Object containing value overrides. Values
// in the object temporarily override the local values. This should *only* be used for testing.
// If any overrides are set, permanent changes are not made (including showing
// the update notification icon and saving prefs).
let oldValues: any;
let usingOverrides = false; // true if any of the values are overridden.
const result = $.Deferred();
let versionInfoUrl: string | undefined;
if (_testValues) {
oldValues = {};
if (_testValues.hasOwnProperty("_buildNumber")) {
oldValues._buildNumber = _buildNumber;
_buildNumber = _testValues._buildNumber;
usingOverrides = true;
}
if (_testValues.hasOwnProperty("lastNotifiedBuildNumber")) {
oldValues.lastNotifiedBuildNumber = lastNotifiedBuildNumber;
lastNotifiedBuildNumber = _testValues.lastNotifiedBuildNumber;
usingOverrides = true;
}
if (_testValues.hasOwnProperty("_versionInfoURL")) {
versionInfoUrl = _testValues._versionInfoURL;
usingOverrides = true;
}
}
_getUpdateInformation(force || usingOverrides, usingOverrides, versionInfoUrl)
.done(function (allUpdates: UpdateFeedInfo = []) {
const semver = node.require("semver");
const currentVersion = node.require("./package.json").version;
// Get all available updates
const availableUpdates = allUpdates.filter((x) => semver.gt(x.versionString, currentVersion));
// When running directly from GitHub source (as opposed to
// an installed build), _buildNumber is 0. In this case, if the
// test is not forced, don't show the update notification icon or
// dialog.
if (_buildNumber === 0 && !force) {
result.resolve();
return;
}
if (availableUpdates && availableUpdates.length > 0) {
// Always show the "update available" icon if any updates are available
const $updateNotification = $("#update-notification");
$updateNotification.css("display", "block");
$updateNotification.on("click", function () {
// Block the click until the Notification Dialog opens
if (!_addedClickHandler) {
_addedClickHandler = true;
checkForUpdate(true);
}
});
// Only show the update dialog if force = true, or if the user hasn't been
// alerted of this update
if (force || availableUpdates[0].buildNumber > lastNotifiedBuildNumber) {
_showUpdateNotificationDialog(availableUpdates);
// Update prefs with the last notified build number
lastNotifiedBuildNumber = availableUpdates[0].buildNumber;
// Don't save prefs is we have overridden values
if (!usingOverrides) {
PreferencesManager.setViewState("lastNotifiedBuildNumber", lastNotifiedBuildNumber);
}
}
} else if (force) {
// No updates are available. If force == true, let the user know.
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.NO_UPDATE_TITLE,
Strings.NO_UPDATE_MESSAGE
);
}
if (oldValues) {
if (oldValues.hasOwnProperty("_buildNumber")) {
_buildNumber = oldValues._buildNumber;
}
if (oldValues.hasOwnProperty("lastNotifiedBuildNumber")) {
lastNotifiedBuildNumber = oldValues.lastNotifiedBuildNumber;
}
}
result.resolve();
})
.fail(function () {
// Error fetching the update data. If this is a forced check, alert the user
if (force) {
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.ERROR_FETCHING_UPDATE_INFO_TITLE,
Strings.ERROR_FETCHING_UPDATE_INFO_MSG
);
}
result.reject();
});
return result.promise();
}
/**
* Launches both check for Brackets update and check for installed extensions update
*/
function launchAutomaticUpdate() {
// launch immediately and then every 24 hours + 2 minutes
checkForUpdate();
checkForExtensionsUpdate();
window.setInterval(checkForUpdate, ONE_DAY + TWO_MINUTES);
}
// Events listeners
ExtensionManager.on("registryDownload", _onRegistryDownloaded);
// Define public API
exports.launchAutomaticUpdate = launchAutomaticUpdate;
exports.checkForUpdate = checkForUpdate;
}); | the_stack |
import _ from 'lodash'
import { nanoid } from 'nanoid'
import { EntityManager, getManager, getRepository, In, LessThan } from 'typeorm'
import { IsolationLevel } from 'typeorm/driver/types/IsolationLevel'
import { getIPermission, IPermission } from '../core/permission'
import { User } from '../core/user'
import { Workspace } from '../core/workspace'
import { WorkspaceMember } from '../core/workspace/workspaceMember'
import { WorkspaceView } from '../core/workspaceView'
import { UserEntity } from '../entities/user'
import { WorkspaceEntity } from '../entities/workspace'
import { WorkspaceMemberEntity } from '../entities/workspaceMember'
import { WorkspaceViewEntity } from '../entities/workspaceView'
import { InvalidArgumentError, NotFoundError } from '../error/error'
import { LoadMoreKey } from '../types/common'
import { PermissionWorkspaceRole } from '../types/permission'
import { AccountStatus } from '../types/user'
import { WorkspaceDTO, WorkspaceMemberStatus } from '../types/workspace'
import { WorkspaceViewDTO } from '../types/workspaceView'
import { string2Hex } from '../utils/common'
import { isAnonymous, isSaaS } from '../utils/env'
import { loadMore } from '../utils/loadMore'
import { canGetWorkspaceData, canUpdateWorkspaceData } from '../utils/permission'
// TODO: record activities
export class WorkspaceService {
protected permission: IPermission
protected isolationLevel: IsolationLevel = 'REPEATABLE READ'
constructor(p: IPermission) {
this.permission = p
}
async mustFindOneWithMembers(workspaceId: string, manager?: EntityManager): Promise<Workspace> {
const model = await (manager ?? getManager())
.getRepository(WorkspaceEntity)
.findOne(workspaceId, {
relations: ['members'],
})
if (!model) {
throw NotFoundError.resourceNotFound(workspaceId)
}
return Workspace.fromEntity(model)
}
/**
* get workspace detail
*/
async get(operatorId: string, workspaceId: string): Promise<WorkspaceDTO> {
await canGetWorkspaceData(this.permission, operatorId, workspaceId)
return this.mustFindOneWithMembers(workspaceId).then((w) => w.toDTO(operatorId))
}
async update(
operatorId: string,
workspaceId: string,
params: {
name?: string
avatar?: string
resetInviteCode?: boolean
},
): Promise<WorkspaceDTO> {
await canUpdateWorkspaceData(this.permission, operatorId, workspaceId)
const workspace = await getRepository(WorkspaceEntity).findOneOrFail(workspaceId)
const { name, avatar, resetInviteCode } = params
if (name) {
workspace.name = name
}
if (avatar) {
workspace.avatar = avatar
}
if (resetInviteCode) {
workspace.inviteCode = this.generateInviteCode()
}
await workspace.save()
const newWorkspace = await this.mustFindOneWithMembers(workspaceId)
return newWorkspace.toDTO(operatorId)
}
async list(
operatorId: string,
next?: LoadMoreKey,
): Promise<{ workspaces: WorkspaceDTO[]; next?: LoadMoreKey }> {
const { limit = 20, timestamp = _.now() } = next ?? {}
const query = await this.permission.getListWorkspacesQuery(operatorId)
const models = await getRepository(WorkspaceEntity).find({
where: {
...query,
createdAt: LessThan(new Date(timestamp)),
},
relations: ['members'],
order: { createdAt: 'DESC' },
take: limit,
})
const dtos = _(models)
.map((m) => Workspace.fromEntity(m).toDTO(operatorId))
.value()
const { data: workspaces, next: nextNext } = loadMore(dtos, limit, (q) => q.createdAt)
return {
workspaces,
next: nextNext,
}
}
async create(operatorId: string, name: string, avatar?: string): Promise<WorkspaceDTO> {
return getManager().transaction(this.isolationLevel, async (t) => {
const model = await t.getRepository(WorkspaceEntity).save({
name,
avatar: avatar || '/api/static/avatars/workspace-default.png',
inviteCode: this.generateInviteCode(),
})
const member = await t.getRepository(WorkspaceMemberEntity).save({
workspaceId: model.id,
userId: operatorId,
role: PermissionWorkspaceRole.ADMIN,
status: WorkspaceMemberStatus.ACTIVE,
joinAt: new Date(),
})
// set relations
model.members = [member]
return Workspace.fromEntity(model).toDTO(operatorId)
})
}
async join(
workspaceId: string,
userId: string,
inviteCode: string,
invitedById?: string,
): Promise<WorkspaceDTO> {
const model = await this.mustFindOneWithMembers(workspaceId)
if (model.inviteCode !== inviteCode) {
throw InvalidArgumentError.new('invalid invite code')
}
return getManager().transaction(this.isolationLevel, async (t) => {
const now = new Date()
// update user status from creating to confirmed
// TODO: add test cases
await t
.getRepository(UserEntity)
.update({ id: userId, status: AccountStatus.CREATING }, { status: AccountStatus.CONFIRMED })
let member = await t.getRepository(WorkspaceMemberEntity).findOne({ workspaceId, userId })
if (!member) {
member = getRepository(WorkspaceMemberEntity).create({
workspaceId,
userId,
role: PermissionWorkspaceRole.MEMBER,
status: WorkspaceMemberStatus.ACTIVE,
invitedAt: now,
joinAt: now,
invitedById,
})
} else {
member.status = WorkspaceMemberStatus.ACTIVE
member.joinAt = now
}
const newMember = await t.getRepository(WorkspaceMemberEntity).save(member)
model.members = _([...model.members, WorkspaceMember.fromEntity(newMember)])
.uniqBy('userId')
.value()
return model.toDTO(userId)
})
}
/**
* if there is no user left in this workspace, delete this workspace
*/
async leave(workspaceId: string, userId: string): Promise<void> {
await getManager().transaction(this.isolationLevel, async (t) => {
await t.getRepository(WorkspaceMemberEntity).delete({ workspaceId, userId })
const workspace = await this.mustFindOneWithMembers(workspaceId, t)
if (_.isEmpty(workspace.members)) {
await t.getRepository(WorkspaceEntity).delete(workspaceId)
}
})
}
async addMembers(
operatorId: string,
workspaceId: string,
usersWithRole: {
userId: string
role: PermissionWorkspaceRole
}[],
manager?: EntityManager,
): Promise<void> {
const entities = _(usersWithRole)
.map(({ userId, role }) =>
getRepository(WorkspaceMemberEntity).create({
workspaceId,
userId,
role,
status: WorkspaceMemberStatus.ACTIVE,
invitedAt: new Date(),
invitedById: operatorId,
}),
)
.value()
await (manager ?? getManager())
.createQueryBuilder()
.insert()
.into(WorkspaceMemberEntity)
.values(entities)
.orIgnore()
.execute()
}
async kickoutMembers(
operatorId: string,
workspaceId: string,
userIds: string[],
): Promise<WorkspaceDTO> {
await canUpdateWorkspaceData(this.permission, operatorId, workspaceId)
if (_(userIds).includes(operatorId)) {
throw InvalidArgumentError.new('cannot kickout your self')
}
await getRepository(WorkspaceMemberEntity).delete({
workspaceId,
userId: In(userIds),
})
const workspace = await this.mustFindOneWithMembers(workspaceId)
return workspace.toDTO(operatorId)
}
async updateRole(
operatorId: string,
workspaceId: string,
operateeId: string,
role: PermissionWorkspaceRole,
): Promise<WorkspaceDTO> {
await canUpdateWorkspaceData(this.permission, operatorId, workspaceId)
await getRepository(WorkspaceMemberEntity).update({ workspaceId, userId: operateeId }, { role })
const workspace = await this.mustFindOneWithMembers(workspaceId)
return workspace.toDTO(operatorId)
}
async syncWorkspaceView(operatorId: string, workspaceId: string): Promise<WorkspaceViewDTO> {
await canGetWorkspaceData(this.permission, operatorId, workspaceId)
let model = await getRepository(WorkspaceViewEntity).findOne({
userId: operatorId,
workspaceId,
})
if (!model) {
model = await getRepository(WorkspaceViewEntity).save({
userId: operatorId,
workspaceId,
pinnedList: [],
})
}
return WorkspaceView.fromEntity(model).toDTO()
}
async getWorkspaceViewByViewId(operatorId: string, viewId: string): Promise<WorkspaceViewDTO> {
const model = await getRepository(WorkspaceViewEntity).findOneOrFail(viewId)
await canGetWorkspaceData(this.permission, operatorId, model!.workspaceId)
return WorkspaceView.fromEntity(model!).toDTO()
}
private generateInviteCode() {
return string2Hex(nanoid())
}
async updateWorkspacePreferences(
operatorId: string,
workspaceId: string,
preferences: Record<string, unknown>,
): Promise<WorkspaceDTO> {
await canUpdateWorkspaceData(this.permission, operatorId, workspaceId)
await getRepository(WorkspaceEntity).update(workspaceId, { preferences })
const workspace = await this.mustFindOneWithMembers(workspaceId)
return workspace.toDTO(operatorId)
}
private getInvitedMembers(users: User[], workspace: Workspace): User[] {
return _(users)
.filter(
(u) =>
_(workspace.members).find((m) => m.userId === u.id)?.status ===
WorkspaceMemberStatus.INVITED,
)
.value()
}
}
export class AnonymousWorkspaceService extends WorkspaceService {
async leave(): Promise<void> {
throw InvalidArgumentError.notSupport('leaving workspace')
}
async create(): Promise<WorkspaceDTO> {
throw InvalidArgumentError.notSupport('creating workspace')
}
}
const service =
!isSaaS() && isAnonymous()
? new AnonymousWorkspaceService(getIPermission())
: new WorkspaceService(getIPermission())
export default service | the_stack |
import moment from "moment";
import { TFile,FileSystemAdapter } from "obsidian";
export class DailyNotesFolderMissingError extends Error {}
export async function getRemainingTasks(note: TFile): Promise<number> {
if (!note) {
return 0;
}
const { vault } = window.app;
const fileContents = await vault.cachedRead(note);
//eslint-disable-next-line
const matchLength = (fileContents.match(/(-|\*) (\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s)?/g) || []).length;
return matchLength;
}
export async function getTasksFromFiles(
file: TFile | null, dailyEvents: any[]
): Promise<any[]> {
if (!file) {
return [];
}
const { vault } = window.app;
const Tasks = await getRemainingTasks(file);
if (Tasks) {
let fileContents = await vault.cachedRead(file);
let fileLines = getAllLinesFromFile(fileContents);
for (let i = 0; i < fileLines.length; i++) {
const line = fileLines[i];
if (line.length === 0) continue
const rawText = extractTextFromTodoLine(line);
const dueDate = getDueDateFromBulletLine(line);
const scheduleDate = getScheduledDateFromBulletLine(line);
const startDate = getStartDateFromBulletLine(line);
if (dueDate && scheduleDate) {
if(lineIsValidTodoEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'TODO',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidDoneEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'DONE',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidAnotherEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'ANOTHER',
file: file,
originalText: line,
lineNum: i,
});
}else{
dailyEvents.push({
id: i,
title: rawText,
start: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'JOURNAL',
file: file,
originalText: line,
lineNum: i,
});
}
}else if(dueDate && startDate){
if(lineIsValidTodoEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'TODO',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidDoneEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'DONE',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidAnotherEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'ANOTHER',
file: file,
originalText: line,
lineNum: i,
});
}else{
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'JOURNAL',
file: file,
originalText: line,
lineNum: i,
});
}
}else if(dueDate && !startDate && !scheduleDate){
if(lineIsValidTodoEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'TODO',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidDoneEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'DONE',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidAnotherEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'ANOTHER',
file: file,
originalText: line,
lineNum: i,
});
}else{
dailyEvents.push({
id: i,
title: rawText,
start: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'JOURNAL',
file: file,
originalText: line,
lineNum: i,
});
}
}else if(scheduleDate && !dueDate && !startDate){
if(lineIsValidTodoEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'TODO',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidDoneEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'DONE',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidAnotherEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'ANOTHER',
file: file,
originalText: line,
lineNum: i,
});
}else{
dailyEvents.push({
id: i,
title: rawText,
start: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'JOURNAL',
file: file,
originalText: line,
lineNum: i,
});
}
}else if(scheduleDate && startDate){
if(lineIsValidTodoEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'TODO',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidDoneEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'DONE',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidAnotherEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getScheduledDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'ANOTHER',
file: file,
originalText: line,
lineNum: i,
});
}else{
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getDueDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'JOURNAL',
file: file,
originalText: line,
lineNum: i,
});
}
}else if(startDate && !dueDate && !scheduleDate){
if(lineIsValidTodoEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'TODO',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidDoneEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'DONE',
file: file,
originalText: line,
lineNum: i,
});
}else if(lineIsValidAnotherEvent(line)){
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'ANOTHER',
file: file,
originalText: line,
lineNum: i,
});
}else{
dailyEvents.push({
id: i,
title: rawText,
start: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
end: moment(getStartDateFromBulletLine(line), "YYYY-MM-DD").toDate(),
resourceId: i,
status: 'JOURNAL',
file: file,
originalText: line,
lineNum: i,
});
}
}
}
fileLines = null;
fileContents = null;
}
}
export function getPath(filePath: string): string | null {
const { vault } = window.app;
if (vault.adapter instanceof FileSystemAdapter) {
return (vault.adapter as FileSystemAdapter).getFullPath(filePath);
}
throw new Error('cannot determine base path');
}
// export function clear(clearbool: boolean) {
// if(clearbool) {
// dailyEvents.splice(0, dailyEvents.length);
// events.splice(0, events.length);
// }
// }
// export function getResults(dailyNotesFolder: TFolder,dailyNotes: Record<string, TFile>,dailyEvents: any[]){
// return new Promise((resolve,reject) => {
// Vault.recurseChildren(dailyNotesFolder, async (note) => {
// if (note instanceof TFile && note.extension === 'md') {
// const date = getDateFromFile(note, "day");
// if(date) {
// const file = getDailyNote(date, dailyNotes);
// await getTasksForDailyNote(file, dailyEvents);
// }
// }
// });
// })
// }
export async function outputTasksResults(): Promise<any[]> {
// const dailyEvents = [];
const events = [];
const { vault } = window.app;
const allFiles = vault.getMarkdownFiles();
for(let i = 0; i < allFiles.length; i++){
if(allFiles[i] instanceof TFile){
await getTasksFromFiles(allFiles[i], events);
// console.log(getPath(dailyNotes[string].path));
}
}
// dailyEvents.splice(0, dailyEvents.length);
return events;
}
//Kanban: @{2021-12-25} @@{19:00}
//Tasks startDateRegex = /🛫 ?(\d{4}-\d{2}-\d{2})$/u;
//Tasks scheduledDateRegex = /[⏳⌛] ?(\d{4}-\d{2}-\d{2})$/u;
//Taks dueDateRegex = /[📅📆🗓] ?(\d{4}-\d{2}-\d{2})$/u;
const getAllLinesFromFile = (cache: string) => cache.split(/\r?\n/)
//eslint-disable-next-line
// const lineIsValidTodo = (line: string) => {
// //eslint-disable-next-line
// return /^\s*(\-|\*)\s\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s?(.*)$/.test(line)
// }
const lineIsValidTodoEvent = (line: string) => {
//eslint-disable-next-line
return /^\s*(\-|\*)\s\[ \]\s?(.*)$/.test(line)
}
const lineIsValidDoneEvent = (line: string) => {
//eslint-disable-next-line
return /^\s*(\-|\*)\s\[x\]\s?(.*)$/.test(line)
}
const lineIsValidAnotherEvent = (line: string) => {
//eslint-disable-next-line
return /^\s*(\-|\*)\s\[(X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s?(.*)$/.test(line)
}
//eslint-disable-next-line
const lineContainsTime = (line: string) => {
//eslint-disable-next-line
return /^\s*(\-|\*)\s(\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s)?(\<time\>)?\d{1,2}\:\d{2}(.*)$/.test(line)
}
//eslint-disable-next-line
const extractTextFromTodoLine = (line: string) => /^(\s*)?(\-|\*)\s\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s?(\<time\>)?((\d{1,2})\:(\d{2}))?(\<\/time\>)?(.+?)(?=(⏫|🛫|📅|📆|(@{)|⏳|⌛|(\[due\:\:)|(\[created\:\:)))/.exec(line)?.[9]
//eslint-disable-next-line
// const extractHourFromBulletLine = (line: string) => /^\s*[\-\*]\s(\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s?)?(\<time\>)?(\d{1,2})\:(\d{2})(.*)$/.exec(line)?.[4]
//eslint-disable-next-line
// const extractMinFromBulletLine = (line: string) => /^\s*[\-\*]\s(\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s?)?(\<time\>)?(\d{1,2})\:(\d{2})(.*)$/.exec(line)?.[5]
//eslint-disable-next-line
const getStartDateFromBulletLine = (line: string) => /\s(🛫|(\[created\:\:)|➕) ?(\d{4}-\d{2}-\d{2})(\])?/.exec(line)?.[3]
//eslint-disable-next-line
const getDueDateFromBulletLine = (line: string) => /\s(📅|📆|(@{)|(\[due\:\:)) ?(\d{4}-\d{2}-\d{2})(\])?/.exec(line)?.[4]
//eslint-disable-next-line
const getScheduledDateFromBulletLine = (line: string) => /\s(⏳|⌛) ?(\d{4}-\d{2}-\d{2})/.exec(line)?.[2]
// thanks to Luke Leppan and the Better Word Count plugin
//eslint-disable-next-line
const tagFromLine = (line: string) => /\s(#\S{0,})\s/ | the_stack |
import { EditableDocumentData, EditableNodeType, EditableIndentType, EditableTextStyle, EditableAlignType, EditableSizeLevel } from '@wizdm/editable';
import { EditableInline, EditableDocument, EditableContent } from '@wizdm/editable';
import { timeInterval, map, filter } from 'rxjs/operators';
import { Subject, Subscription } from 'rxjs';
/** Virtual document selection mapping browser range selection to the internal document data tree */
export class EditableSelection {
private modified = false;
public start: EditableContent;
public startOfs: number;
public end: EditableContent;
public endOfs: number;
constructor(private root: EditableDocument) { }
/** Returns true on valid selection */
get valid(): boolean { return !!this.start && !!this.end; }
/** Returns true when the selection belongs within a single node */
get single(): boolean { return this.valid && (this.start === this.end); }
/** Returns true when the selection spread across moltiple nodes */
get multi(): boolean { return !this.single; }
/** Returns true when the selection includes the whole nodes */
get whole(): boolean { return this.valid && (this.startOfs === 0) && (this.endOfs === this.end.length); }
/** Returns true when the selection falls in the middle of node(s) */
get partial(): boolean { return !this.whole; }
/** Returns true when the selection is collpased in a cursor */
get collapsed(): boolean { return this.single && (this.startOfs === this.endOfs);}
/** Returns true when the selection fully belongs to a single container */
get contained(): boolean { return this.single || this.valid && this.start.container === this.end.container; }
/** Returns true whenever the selection has been modified */
get marked(): boolean { return this.valid && this.modified; }
/** Marks a seleciotn as modified */
public mark(modified = true): EditableSelection {
this.modified = this.valid && modified;
return this;
}
/** Sets the selection's start node */
public setStart(node: EditableContent, ofs: number) {
this.start = node;
this.startOfs = (!!node && ofs < 0) ? node.length : ofs;
this.modified = true;
}
/** Sets the selection's end node */
public setEnd(node: EditableContent, ofs: number) {
this.end = node;
this.endOfs = (!!node && ofs < 0) ? node.length : ofs;
this.modified = true;
}
/** Sets the selection range */
public set(start: EditableContent, startOfs: number, end: EditableContent, endOfs: number): EditableSelection {
this.setStart(start, startOfs);
this.setEnd(end, endOfs);
return this;
}
/** Collapses the selection to a cursor at the specified position */
public setCursor(node: EditableContent, ofs: number): EditableSelection {
return this.set(node, ofs, node, ofs);
}
/** Resets the selection as a cursor position at the very beginning of the document tree */
public reset(): EditableSelection {
return this.setCursor(this.root.firstDescendant() as any, 0);
}
/** Resets the selection as a cursor position at the very end of the document tree */
public endset(): EditableSelection {
const node = this.root.lastDescendant();
return this.setCursor(node, node.length);
}
/**
* Collapses the curernt selection to a cursor
* @param end (optional) when true, collapses the cursor to the end edge of the selection.
* It collapses to the start edge otherwise.
*/
public collapse(end?: boolean): EditableSelection {
return !!end ? this.setCursor(this.end, this.endOfs) : this.setCursor(this.start, this.startOfs);
}
/** Moves the selection start and end points by the specified offsets */
public move(deltaStart: number, deltaEnd?: number): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Move the selection points
const start = this.start.move(this.startOfs + deltaStart);
const end = (deltaEnd === undefined) ? start : this.end.move(this.endOfs + deltaEnd);
// Update the selection
return this.set(start[0], start[1], end[0], end[1]);
}
/** Jumps to the previous text node skipping non text ones*/
private previous(node: EditableContent, traverse: boolean = false): EditableContent {
let prev = node.previous(traverse) as any;
while(!!prev && !(prev instanceof EditableInline)) { prev = prev.previous(traverse); }
return prev;
}
/** Jumps to the next text node skipping non text ones*/
private next(node: EditableContent, traverse: boolean = false): EditableContent {
let next = node.next(traverse) as any;
while(!!next && !(next instanceof EditableInline)) { next = next.next(traverse); }
return next;
}
/** Saves the current selection into the document data to be eventually restored by calling @see restore() */
public save(document: EditableDocument): EditableDocument {
// Skips on invalid selection
if(!document || !this.valid) { return document; }
// Computes the absolute start offset
const start = this.start.offset;
// Saves the selection range in the root data
document.setRange(start + this.startOfs, (this.single ? start : this.end.offset) + this.endOfs );
return document;
}
/** Restores the selection range from the documenta data. @see save() */
public restore(document: EditableDocument): EditableSelection {
// Gets the range from the root data
const range = !!document && document.range;
// Updates the selection to reflect the absolute range
return !!range ? this.reset().move(range[0], range[0] !== range[1] ? range[1] : undefined) : this;
}
/** Returns true whenever the start node/offset comes after the end ones */
public get reversed(): boolean {
if(!this.valid) { return false; }
return this.start === this.end && this.startOfs > this.endOfs || this.start.compare(this.end) > 0;
}
/** Sort the start/end selection nodes, so, to make sure start comes always first */
public sort(): EditableSelection {
// Compares the points' position
if(this.reversed) {
const node = this.start;
this.start = this.end;
this.end = node;
const ofs = this.startOfs;
this.startOfs = this.endOfs;
this.endOfs = ofs;
}
return this;
}
/** Helper function to loop on all the text nodes within the selection */
private nodes(callbackfn: (node: EditableContent) => void): EditableSelection {
// Skips on invalid selection
if(!this.valid || !callbackfn) { return this; }
// Loops on the editable whithin the selection
let node = this.start;
while(!!node && node.compare(this.end) <= 0) {
// Callback on the container
callbackfn.call(this, node);
// Gets the next text node
node = this.next(node, true);
}
return this;
}
/** Helper function to loop on all the containers within the selection */
private containers(callbackfn: (container: EditableContent) => void): EditableSelection {
// Skips on invalid selection
if(!this.valid || !callbackfn) { return this; }
// Loops on the editable whithin the selection
let container = this.start.container;
while(!!container && container.compare(this.end) < 0) {
// Callback on the container
callbackfn.call(this, container);
// Makes sure to skip structural node levels
const next = container.lastChild().next();
// Gets the next container
container = !!next ? next.container : null;
}
return this;
}
/** Makes sure the selection falls within the inner nodes when on the edges. */
public trim(): EditableSelection {
// Skips on invalid selection
if(!this.valid || this.collapsed) { return this; }
// Retrive the end edge back
if(this.endOfs === 0) {
const end = this.previous(this.end, true);
if(!!end) { this.setEnd(end, -1);}
}
// Special case, if now the selection collapsed we are done.
if(this.collapsed) { return this; }
// Push the start edge ahead
if(this.startOfs === this.start.length) {
const start = this.next(this.start, true);
if(!!start) { this.setStart(start, 0);}
}
return this;
}
/** Forces the selection to wrap around the closes text word boundaries */
public wordWrap(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Seeks for the word edges around the cursor at start node
const edges = this.start.edges(this.startOfs);
// When collapsed, just set the selection at the given edges
if(this.collapsed) { return this.set(this.start, edges[0], this.start, edges[1]); }
// Seeks for the edges at the end node otherwise
this.startOfs = edges[0];
this.endOfs = this.end.edges(this.endOfs)[1];
return this.mark();
}
/** Insert new text at the cursor position */
public insert(char: string): EditableSelection {
// Skips on invalid selection or null string
if(!this.valid || !char) { return this; }
// Deletes the selection, if any
if(!this.collapsed) { this.delete(); }
// Store a snapshot for undo history
this.store();
// In case the selection is on the end edge of a link...
if(this.start.type !== 'text' && this.startOfs === this.start.length) {
// Jumps on the following text, if any or create a new text node otherwise
const next = this.next(this.start) || this.start.insertNext(this.start.create.text.set(''));
// Updates the new position
this.setCursor(next, 0);
}
// Inserts the new char at the specified position
this.start.insert(char, this.startOfs);
return this.move(char.length);
}
/** Deletes the selection from the document tree */
public delete(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Store a snapshot for undo history
this.store();
// Whenever the selection applies on a single node...
if(this.single) {
// Extracts the selected text within the node
this.start.extract(this.startOfs, this.endOfs);
// If the node is still containing text, we are done...
if(!this.start.empty) { return this.collapse(); }
}
//...otherwise we are dealing with multiple nodes, so...
else {
//...just cut the text away each side
this.start.cut(0, this.startOfs);
this.end.cut(this.endOfs);
}
// Moves the selection just outside the empty nodes, so, for merge to do its magic...
if(this.start.empty) { this.start = this.next(this.start) || this.start; }
if(this.end.empty) { this.end = this.next(this.end) || this.end; }
// Keeps the current text length...
const ofs = this.start.length;
// Merges the nodes
this.start.merge(this.end);
// Updates the cursor position
return this.setCursor(this.start, ofs);
}
/** Deletes the selection, if any, or the following char when collapsed */
public del(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// On collapsed...
if(this.collapsed) {
// Skips special cases when the cursor is at the edge...
if(this.start.length === this.startOfs) {
// Skips whenever the cursor falls within a cell or a caption
if(this.matchOne('cell', 'caption')){ return this; }
// Skips whenever the cusror would move within a cell or a caption
const next = this.next(this.start, true);
if(!next || !!next.climb('cell', 'caption')) {
return this;
}
}
// Select the following char
this.move(0, 1);
}
// Deletes the selection
return this.delete();
}
/** Deletes the selection, if any, or the preceeding char when collapsed */
public back(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// On collapsed...
if(this.collapsed) {
// Skips special cases when the cursor is at the edge...
if(this.startOfs === 0){
// Skips whenever the cursor falls within a cell or a caption
if(this.matchOne('cell', 'caption')) { return this; }
// Skips whenever the cusror would move within a cell or a caption
const prev = this.previous(this.start, true);
if(!prev || !!prev.climb('cell', 'caption')) {
return this;
}
}
// Select the preceeding char
this.move(-1, 0);
}
// Deletes the selection
return this.delete();
}
/**
* Breaks the selection by inserting a new line char or an entire new editable block
* @param newline when true, a new line charachter wil be used to break the selection,
* when false a new editable block will be created contening the follwoing text sibling
* nodes exlucing this one.
*/
public break(newline: boolean = false): EditableSelection {
// Deletes the selection, if any
if(!this.collapsed) { this.delete(); }
// Store a snapshot for undo history
this.store();
// Just insert a new line on request forcing it always on links, table cells and figure's caption
if(newline || this.matchOne('link', 'cell', 'caption')) {
this.start.insert('\n', this.startOfs);
return this.move(1);
}
// Inserts an extra empty text node on the end edge preserving the same style
if(this.start.last && this.startOfs === this.start.length) {
this.start.insertNext(this.start.clone().set(''));
}
// Inserts an extra empty text on the start edge preserving the same style
else if(this.start.first && this.startOfs === 0) {
this.start.insertPrevious(this.start.clone().set(''));
}
// Makes sure the cursor is on the right side of node's edges
if(this.startOfs === this.start.length) { this.setCursor(this.next(this.start), 0);}
// Breaks the content from this node foreward in a new editable container
const node = this.start.split(this.startOfs).break();
// Updates the cursor position
return this.setCursor(node, 0);
}
/** Splits the seleciton at the edges, so, the resulting selection will be including full nodes only */
public split(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
if(this.single) {
// Splits the single node both sides
const node = this.start.split(this.startOfs, this.endOfs);
this.set(node, 0, node, -1);
}
else {
// Splits the multi selection both ends
const start = this.start.split(this.startOfs);
const end = this.end.split(0, this.endOfs);
this.set(start, 0, end, -1);
}
return this;
}
/**
* Defragments the selections, so, minimizing the number of text nodes comprised in it
* by joining siblings sharing the same attributes.
*/
public defrag(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Save the current selection
this.save(this.root);
// Defrags the few editable containers between the nodes
this.containers( container => container.defrag() );
// Restores the selection
this.restore(this.root).trim();
// Returns the selection supporting chaining
return this;
}
/** Returns the current selection alignement (corresponding to the start node container's) */
public get align(): EditableAlignType {
return this.valid ? this.start.align : 'left';
}
/** Applies the given alignemnt to the selection */
public set align(align: EditableAlignType) {
this.store().containers( container => container.align = align ).mark();
}
/** Returns the current selection level (corresponding to the start node container's) */
public get level(): EditableSizeLevel {
return this.valid ? this.start.level : 0;
}
/** Applies a new level to the selection */
public set level(level: EditableSizeLevel) {
// Skips on invalid selection
if(!this.valid) { return; }
// Applies the level on the containers within the selection
this.store().containers( container => container.level = level ).mark();
}
/** Returns the style of the selection always corresponding to the style of the start node */
public get style(): EditableTextStyle[] {
return this.valid ? this.start.style : [];
}
/** Applies the given style to the selection */
public set style(style: EditableTextStyle[]) {
// Skips on invalid selection
if(this.valid) {
// Store a snapshot for undo history
this.store();
// Forces wordwrapping when collapsed
if(this.collapsed) { this.wordWrap(); }
// Applies the given style to all the nodes within the selection
this.trim().split().nodes( node => node.style = style ).defrag();
}
}
/** Resets the selection style removing all formatting */
public clear(): EditableSelection {
return this.style = [], this;
}
/**
* Applies (or removes) a given style set to the selection.
* @param style style array to be applied.
* @param remove when true, the requested style will be removed instead.
*/
public format(style: EditableTextStyle[], remove: boolean = false): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Store a snapshot for undo history
this.store();
// Forces wordwrapping when collapsed
if(this.collapsed) { this.wordWrap(); }
// Trims and splits the selection
this.trim().split();
// Formats all the nodes within the selection
this.nodes( node => {
if(remove) { node.unformat(style); }
else { node.format(style); }
});
// Defragments the text nodes when done
return this.defrag();
}
/** Toggles a single format style on/off */
public toggleFormat(style: EditableTextStyle): EditableSelection {
const remove = this.style.some( s => s === style );
return this.format([style], remove);
}
/** Turns the selection into a link node */
public link(url: string): EditableSelection {
// Performs unlinking when url is null
if(!url) { return this.unlink(); }
// Skips on invalid selection
if(!this.valid) { return this; }
// Store a snapshot for undo history
this.store();
// Forces wordwrapping when collapsed
if(this.collapsed) { this.wordWrap(); }
// Trims and splits the selection
this.trim().split();
// Join multiple nodes when needed
if(this.multi) {
let node = this.next(this.start, true);
while(!!node && node.compare(this.end) <= 0) {
this.start.join(node);
if(node === this.end) { break; }
node = this.next(this.start, true);
}
}
// Turns the resulting node into a link
this.start.link(url);
// Updates the selection
return this.set(this.start, 0, this.start, -1);
}
/** Removes the links falling into the selection */
public unlink(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Turns links into plain text
return this.store().nodes( node => node.link(null) ).defrag();
}
/** Picks the first selection's parent matching the specified types */
public pick(...types: EditableNodeType[]): EditableContent {
return this.valid ? this.start.climb(...types) : null;
}
/** Removes an indentation level when applicable */
public outdent(): EditableSelection {
// Guesses which indentation the selection belongs to
const indent = this.pick('blockquote', 'bulleted', 'numbered');
if(!indent) { return this; }
// outdent all the containers within the selection
this.store().containers( container => container.outdent(indent.type as EditableIndentType) );
// Mark the selection to update on the next rendering round
return this.mark();
}
/** Applies an indentation of the requested type or increase the indentation level when applicable */
public indent(): EditableSelection {
// Guesses which list the selection belongs to
const list = this.pick('bulleted', 'numbered');
// At this point, skips indentation when type is not specified
if(!list) { return this; }
// Indent all the containers within the selection
this.store().containers( item => item.indent(list.type as EditableIndentType) );
// Mark the selection to update on the next rendering round
return this.mark();
}
/** Toggles selection in/out of a list */
public toggleList(type: 'bulleted'|'numbered'): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Store a snapshot for undo history
this.store();
// Verifies if the selection already belongs to a list
const list = this.start.climb('bulleted', 'numbered');
if(!!list) {
// If so, outdent the list it belongs to
this.containers( item => item.outdent(list.type as EditableIndentType) );
// Stop on toggle off
if(list.type === type) { return this.mark(); }
}
// Apply the requested list identation excluding table cells
this.containers( item => { if(item.type !== 'cell') { item.indent(type); } });
// Mark the selection to update on the next rendering round
return this.mark();
}
/** Toggles selection in/out of a blockquote */
public toggleQuote(): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Store a snapshot for undo history
this.store();
const block = this.start.climb('blockquote');
if(!!block) {
return this.containers( item => item.outdent('blockquote') ).mark();
}
let node = this.start.ancestor(1);
while(!!node && node.compare(this.end) < 0) {
node = node.indent('blockquote').nextSibling();
}
// Mark the selection to update on the next rendering round
return this.mark();
}
/** Returns true if the current selection fully belongs to a single specified node or branch */
public belongsTo(type: EditableNodeType): boolean {
// Skips on invalid selection
if(!this.valid) { return false; }
// Perform the check
switch(type) {
// Evevrything belongs to the document
case 'document': return true;
// Inline types
case 'text': case 'link':
return this.single && this.start.type === type && this.startOfs < this.start.length;
// Editable container types
case 'heading': case 'paragraph': case 'cell': case 'caption':
return this.contained && this.start.container.type === type;
// General case
default:
// Climbs up to the specified ancestor
const block = this.start.climb(type);
// Returns false when not there
if(!block) { return false; }
// Return true when there on a single node selection
if(this.single) { return true; }
// Compares the start and end node ancestors otherwise
return block === this.end.climb(type);
}
return false;
}
public matchOne(...types: EditableNodeType[]): boolean {
return !!types && types.some( type => this.belongsTo(type) );
}
/** Returns true whenever the inspected node falls within the current selection */
public includes(node: EditableContent): boolean {
// Skips on invalid selection
return this.valid && !!node && (
// Node matches the selection itself
node === this.start ||
// Node is the selection's ancestor of the matching type
node === this.start.climb(node.type) ||
// Node falls within the selection range
this.start.compare(node) <= 0 && this.end.compare(node) >= 0
);
}
/** Returns a tree fragment containing a copy of the selection */
public copy(): EditableContent {
// Skips on invalid selection
if(!this.valid) { return null; }
// Forces wordwrapping when collapsed
if(this.collapsed) { this.wordWrap(); }
// Trims the selection's edges
this.trim();
// Clones the selection into a tree fragment
const fragment = this.start.fragment(this.end);
// Skips any further process on whole selection
if(this.whole) { return fragment; }
// Gets the starting text node
const start = fragment.firstDescendant();
// Trims the text according to the selection offsets
if(this.single) { start.cut(this.startOfs, this.endOfs); }
// In case of multiple node selection
else {
// Trims both ends separately
const end = fragment.lastDescendant();
start.cut(this.startOfs);
end.cut(0, this.endOfs);
}
// Returns the fragments
return fragment;
}
/** Pastes a data fragment to the current selection */
public paste(source: EditableDocumentData): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Builds the fragment to paste from
const fragment = this.root.create.document.load(source);
if(!!fragment) {
// Paste the content as text within links or table cells
if(this.matchOne('link', 'cell', 'caption')) {
return this.insert(fragment.value);
}
// Breaks the selection at the current position otherwise
this.break().move(-1, 0);
// Cleaves the tree and inserts the new content in between
this.start.cleave()
.insertNext(fragment)
.unwrap();
// Merges the new content first node with start
const first = fragment.firstDescendant();
this.start.merge(first);
// Merges the new content last node with end
const last = fragment.lastDescendant();
last.merge(this.end);
// Collapses the selection in a cursor at the end edge
this.collapse(true);
}
// Done
return this;
}
/* TODO: Implement FIGURES edititng
public tableNew(rows: number, cols: number): EditableSelection {
// Skips on invalid selection
if(!this.valid) { return this; }
// Creates a new empty figure first
const figure = this.root.create.figure;
// Appends a table to the figure
figure.appendChild( this.root.create.table.initTable(rows, cols) );
// Store the current snapshot in the history
this.store();
// Cleaves the tree and inserts the new figure in between
this.start.cleave().insertNext(figure);
// Done
return this;
}
public tableRow(where: 'above'|'below'): EditableSelection {
const table = this.pick('table') as EditableTable;
if(!table) { return this; }
this.store();
table.insertRow(this.pick('row') as EditableRow, where);
return this;
}
public tableColumn(where: 'left'|'right'): EditableSelection {
const table = this.pick('table') as EditableTable;
if(!table) { return this; }
this.store();
table.insertColumn(this.pick('cell') as EditableCell, where);
return this;
}
public tableDelete(what: 'row'|'column'|'table') {
const table = this.pick('table') as EditableTable;
if(!table) { return this; }
this.store();
switch(what) {
case 'row':
table.removeRow(this.pick('row') as EditableRow);
break;
case 'column':
table.removeColumn(this.pick('cell') as EditableCell);
break;
case 'table':
table.remove() as EditableTable;
}
return this;
}
*/
/***** HISTORY UNDO/REDO *****/
private store$ = new Subject<EditableDocument>();
private history: EditableDocumentData[] = [];
private timeIndex: number = 0;
private sub$: Subscription;
/** Clears the history buffer */
public clearHistory(): EditableSelection {
// Unsubscribe the previous subscription, if any
if(!!this.sub$) { this.sub$.unsubscribe(); }
// Initializes the history buffer
this.timeIndex = 0;
this.history = [];
return this;
}
/** Initilizes the history buffer */
public enableHistory(debounce: number = 2000, limit: number = 128): EditableSelection {
// Clears the history buffer
this.clearHistory();
// Builts up the stream optimizing the amout of snapshot saved in the history
this.sub$ = this.store$.pipe(
// Append a time interval between storing emissions
timeInterval(),
// Filters requests coming to fast (within 'debounce time')
filter( payload => this.history.length === 0 || payload.interval > debounce),
// Gets a snapshot of the document with updated selection
map( payload => this.save( payload.value.clone() ).data ),
// Subscribes the history save handler
).subscribe( snapshot => {
// Wipes the further future undoed snapshots since they are now
if(this.timeIndex > 0) {
// Save the last snapshot wiping the further future undoed once
this.history.splice(0, this.timeIndex + 1, snapshot);
// Resets the time index
this.timeIndex = 0;
}
// Saves the last snapshot in the history
else { this.history.unshift(snapshot); }
// Removes the oldest snapshot when exceeeding the history limit
if(this.history.length > limit) { this.history.pop(); }
});
return this;
}
/** Stores a snapshot in the undo/redo history buffer
* @param force (option) when true forces the storage unconditionally.
* Storage will be performed conditionally to the time elapsed since
* the last modification otherwise.
*/
public store(force?: boolean): EditableSelection {
if(!this.root || !this.root.data) { debugger; }
if(!!force) {
// Pushes a snapshot into the history buffer unconditionally
this.history.unshift( this.save( this.root.clone() ).data );
// Return this for chaining
return this;
}
// Pushes the document for conditional history save
return this.store$.next(this.root), this;
}
/** Returns true whenever the last modifications can be undone */
get undoable(): boolean { return this.history.length > 0 && this.timeIndex < this.history.length - (!!this.timeIndex ? 1 : 0); }
/** Undoes the latest changes. It requires enableHistory() to be called */
public undo(): EditableSelection {
// Stops undoing when history is finished
if(!this.undoable) { return this; }
// Saves the present moment to be restored eventually
if(this.timeIndex === 0) { this.store(true); }
// Gets the latest snapshot from the history
const snapshot = this.history[++this.timeIndex];
// Reloads the snapshot's content restoring the selection too
return this.restore( this.root.load(snapshot) as EditableDocument );
}
/** Returns true whenever the last undone modifications can be redone */
get redoable(): boolean { return this.history.length > 0 && this.timeIndex > 0; }
/** Redoes the last undone modifications. It requires enableHistory() to be called */
public redo(): EditableSelection {
// Stops redoing when back to the present
if(!this.redoable) { return this; }
// Gets the previous snapshot from the history
const snapshot = this.history[--this.timeIndex];
// Removes the newest snapshot when back to the present
if(this.timeIndex === 0) { this.history.shift(); }
// Reloads the snapshot's content restoring the selection too
return this.restore( this.root.load(snapshot) as EditableDocument );
}
} | the_stack |
import type { SearchParams } from 'elasticsearch';
import * as ts from '@terascope/utils';
import * as p from 'xlucene-parser';
import {
SortOrder,
GeoDistanceUnit,
xLuceneVariables,
xLuceneTypeConfig,
xLuceneFieldType
} from '@terascope/types';
import { CachedTranslator } from '../translator';
import * as i from './interfaces';
export class QueryAccess<T extends ts.AnyObject = ts.AnyObject> {
readonly excludes: (keyof T)[];
readonly includes: (keyof T)[];
readonly constraints?: string[];
readonly preventPrefixWildcard: boolean;
readonly allowImplicitQueries: boolean;
readonly defaultGeoField?: string;
readonly defaultGeoSortOrder?: SortOrder;
readonly defaultGeoSortUnit?: GeoDistanceUnit|string;
readonly allowEmpty: boolean;
readonly typeConfig: xLuceneTypeConfig;
readonly parsedTypeConfig: xLuceneTypeConfig;
readonly variables: xLuceneVariables;
private readonly _parser: p.CachedParser = new p.CachedParser();
private readonly _translator: CachedTranslator = new CachedTranslator();
constructor(config: i.QueryAccessConfig<T> = {}, options: i.QueryAccessOptions = {}) {
const {
excludes = [],
includes = [],
constraint,
allow_empty_queries: allowEmpty = true,
} = config;
const typeConfig = config.type_config || options.type_config || {};
const variables = options.variables || {};
if (ts.isEmpty(typeConfig)) throw new Error('Configuration for type_config must be provided');
this.typeConfig = { ...typeConfig };
this.excludes = excludes?.slice();
this.includes = includes?.slice();
this.constraints = ts.castArray(constraint).filter(Boolean) as string[];
this.allowEmpty = Boolean(allowEmpty);
this.preventPrefixWildcard = Boolean(config.prevent_prefix_wildcard);
this.allowImplicitQueries = Boolean(config.allow_implicit_queries);
this.defaultGeoField = config.default_geo_field;
this.defaultGeoSortOrder = config.default_geo_sort_order;
this.defaultGeoSortUnit = config.default_geo_sort_unit;
this.parsedTypeConfig = this._restrictTypeConfig();
this.variables = variables;
}
clearCache(): void {
this._parser.reset();
this._translator.reset();
}
/**
* Validate and restrict a xlucene query
*
* @returns a restricted xlucene query
*/
restrict(q: string): string {
return this._restrict(q).query;
}
/**
* Validate and restrict a xlucene query
*
* @returns a restricted xlucene query
*/
private _restrict(q: string, _overrideParsedQuery?: p.Node): p.Parser {
let parser: p.Parser;
const parserOptions: p.ParserOptions = {
type_config: this.typeConfig,
};
try {
parser = this._parser.make(q, parserOptions, _overrideParsedQuery);
} catch (err) {
throw new ts.TSError(err, {
reason: 'Query could not be parsed',
statusCode: 422,
context: {
q,
safe: true
}
});
}
if (p.isEmptyNode(parser.ast)) {
if (!this.allowEmpty) {
throw new ts.TSError('Empty queries are restricted', {
statusCode: 403,
context: {
q,
safe: true
}
});
}
return this._addConstraints(parser, parserOptions);
}
parser.forTermTypes((node: p.TermLikeNode) => {
// restrict when a term is specified without a field
if (!node.field) {
if (this.allowImplicitQueries) return;
throw new ts.TSError('Implicit fields are restricted, please specify the field', {
statusCode: 403,
context: {
q,
safe: true
}
});
}
if (this._isFieldRestricted(node.field)) {
throw new ts.TSError(`Field ${node.field} in query is restricted`, {
statusCode: 403,
context: {
q,
safe: true
}
});
}
if (p.isWildcard(node)) {
const value = p.getFieldValue(node.value, this.variables);
if (this.preventPrefixWildcard && startsWithWildcard(value)) {
throw new ts.TSError("Wildcard queries of the form 'fieldname:*value' or 'fieldname:?value' in query are restricted", {
statusCode: 403,
context: {
q,
safe: true
}
});
}
}
});
return this._addConstraints(parser, parserOptions);
}
private _restrictTypeConfig(): xLuceneTypeConfig {
const parsedConfig: xLuceneTypeConfig = {};
for (const [typeField, value] of Object.entries(this.typeConfig)) {
const excluded = this.excludes.filter((restrictField) => matchTypeField(
typeField,
restrictField as string
));
if (excluded.length) continue;
if (this.includes.length) {
const included = this.includes.filter((restrictField) => matchTypeField(
typeField,
restrictField as string
));
if (!included.length) continue;
}
parsedConfig[typeField] = value;
}
return parsedConfig;
}
/**
* Converts a restricted xlucene query to an elasticsearch search query
*
* @returns a restricted elasticsearch search query
*/
async restrictSearchQuery(
query: string,
opts: i.RestrictSearchQueryOptions = {},
_overrideParsedQuery?: p.Node
): Promise<SearchParams> {
const {
params: _params = {},
elasticsearch_version: esVersion = 6,
...translateOptions
} = opts;
const variables = Object.assign({}, this.variables, opts.variables);
if (_params._source) {
throw new Error('Cannot include _source in params, use _sourceInclude or _sourceExclude');
}
const params = { ..._params };
const parser = this._restrict(query, _overrideParsedQuery);
await ts.pImmediate();
const translator = this._translator.make(parser, {
type_config: this.parsedTypeConfig,
default_geo_field: this.defaultGeoField,
default_geo_sort_order: this.defaultGeoSortOrder,
default_geo_sort_unit: this.defaultGeoSortUnit,
variables
});
const translated = translator.toElasticsearchDSL(translateOptions);
const { includes, excludes } = this.restrictSourceFields(
params._sourceInclude as (keyof T)[],
params._sourceExclude as (keyof T)[]
);
delete params._sourceInclude;
delete params._sourceExclude;
const excludesKey: any = esVersion >= 7 ? '_sourceExcludes' : '_sourceExclude';
const includesKey: any = esVersion >= 7 ? '_sourceIncludes' : '_sourceInclude';
const searchParams: SearchParams = {
...params,
body: { ...params.body, ...translated },
[excludesKey]: excludes,
[includesKey]: includes,
};
if (searchParams != null) {
delete searchParams.q;
}
return searchParams;
}
/**
* Restrict requested source to all or subset of the ones available
*
* **NOTE:** this will remove restricted fields and will not throw
*/
restrictSourceFields(includes?: (keyof T)[], excludes?: (keyof T)[]): {
includes: (keyof T)[]|undefined,
excludes: (keyof T)[]|undefined,
} {
const all = Object.keys(this.parsedTypeConfig)
.map((field) => field.split('.', 1)[0]) as (keyof T)[];
return {
includes: this._getSourceFields(this.includes, all, includes),
excludes: this._getSourceFields(this.excludes, all, excludes),
};
}
private _getSourceFields(
restricted: (keyof T)[],
all: (keyof T)[],
override?: (keyof T)[] | boolean | (keyof T),
): (keyof T)[] | undefined {
const fields = ts.uniq(ts.parseList(override) as (keyof T)[]);
if (fields.length) {
if (restricted.length) {
return restricted.filter((field) => fields.includes(field));
}
if (all.length) {
return fields.filter((field) => all.includes(field));
}
return fields;
}
return restricted.slice();
}
private _isFieldRestricted(field: string): boolean {
return !Object.entries(this.parsedTypeConfig).some(([typeField, fieldType]) => {
if (fieldType === xLuceneFieldType.Object) return false;
const parts = typeField.split('.');
if (parts.length > 1) {
const firstPart = parts.slice(0, -1).join('.');
if (this.typeConfig[firstPart] === xLuceneFieldType.Object) {
return matchFieldObject(typeField, field);
}
}
return matchField(typeField, field);
});
}
private _addConstraints(parser: p.Parser, options: p.ParserOptions): p.Parser {
if (this.constraints?.length) {
const queries = ts.concat(this.constraints, [parser.query]).filter(Boolean) as string[];
if (queries.length === 1) return this._parser.make(queries[0], options);
return this._parser.make(`(${queries.join(') AND (')})`, options);
}
return parser;
}
}
function matchFieldObject(typeField: string, field: string) {
let s = '';
for (const part of typeField.split('.')) {
s += part;
if (ts.matchWildcard(field, s)) {
return true;
}
s += '.';
}
return false;
}
function matchField(typeField: string, field: string) {
let s = '';
for (const part of field.split('.')) {
s += part;
if (ts.matchWildcard(s, typeField)) {
return true;
}
s += '.';
}
return false;
}
function matchTypeField(typeField: string, restrictField: string) {
let s = '';
for (const part of typeField.split('.')) {
s += part;
if (s === restrictField) {
return true;
}
s += '.';
}
return false;
}
function startsWithWildcard(input?: string | number) {
if (!input) return false;
if (!ts.isString(input)) return false;
return ['*', '?'].includes(ts.getFirstChar(input));
} | the_stack |
import { normalizePath, Plugin } from 'vite'
import { crawl } from 'recrawl-sync'
import imagemin from 'imagemin'
import webp, { Options as WebpOptions } from 'imagemin-webp'
import pngquant, { Options as PngOptions } from 'imagemin-pngquant'
import { minify as minifyHtml } from 'html-minifier-terser'
import { minifyCss, MinifyCSSOption } from './css'
import createDebug from 'debug'
import globRegex from 'glob-regex'
import chalk from 'chalk'
import SVGO from 'svgo'
import zlib from 'zlib'
import path from 'path'
import fs from 'fs'
const fsp = fs.promises
const debug = createDebug('vite:plugin-compress')
type HtmlMinifyOptions = import('html-minifier-terser').Options extends infer Options
? Omit<Options, 'minifyCSS'> & { minifyCSS?: MinifyCSSOption }
: never
type PluginOptions = {
/**
* Log compressed files and their compression ratios.
*/
verbose?: boolean
/**
* Set false to disable Brotli compression.
* Useful when your web server handles compression.
* @default true
*/
brotli?: boolean | { exclude?: string[] }
/**
* Brotli compression quality (from `0` to `11`).
* @default 11
*/
quality?: number
/**
* Minimum file size before compression is used.
* @default 1501
*/
threshold?: number
/**
* Globs to exclude certain files from being compressed.
*/
exclude?: string[]
/**
* Additional extensions for Brotli compression.
*/
extensions?: string[]
/**
* Set false to disable the SVG optimizer.
*/
svgo?: SvgOptions | false
/**
* Set false to disable the PNG optimizer.
*/
pngquant?: PngOptions | false
/**
* Set to convert PNG images to WEBP format.
* This also sets the `pngquant` option to false.
*/
webp?: WebpOptions | true
/**
* Set to minify HTML outputs using `html-minifier-terser` and
* optionally `clean-css`.
*/
minifyHtml?: HtmlMinifyOptions | true
}
const mtimeCache = new Map<string, number>()
const defaultExts = ['html', 'js', 'css', 'svg', 'json']
const dataUriPrefix = 'data:image/svg+xml,'
const htmlExt = /\.html$/
const pngExt = /\.png$/
const svgExt = /\.svg$/
export default (opts: PluginOptions = {}): Plugin[] => {
const excludeRegex = opts.exclude ? globRegex(opts.exclude) : /^$/
const brotliExcludeRegex =
opts.brotli && opts.brotli !== true && opts.brotli.exclude
? globRegex(opts.brotli.exclude)
: opts.brotli !== false
? /^$/
: /.+/
const extensionRegex = new RegExp(
'\\.(png|' +
defaultExts
.concat(opts.extensions || [])
.map(ext => ext.replace(/^\./, ''))
.join('|') +
')$'
)
let pngOptimizer: any
let webpGenerator: any
let svgOptimizer: SVGO
async function optimizeSvg(content: string, filePath: string) {
svgOptimizer ??= new SVGO({
plugins: Object.entries({
removeViewBox: false,
removeDimensions: true,
...opts.svgo,
}).map(([name, value]): any => ({ [name]: value })),
})
try {
const svg = await svgOptimizer.optimize(content, { path: filePath })
return svg.data
} catch (err) {
debug(`Failed to optimize "${filePath}". ` + err.message)
return content
}
}
let outRoot: string
const prePlugin: Plugin = {
name: 'vite:compress',
apply: 'build',
enforce: 'pre',
configResolved({ root, publicDir, build: { outDir, ssr } }) {
if (ssr) return
outRoot = normalizePath(path.resolve(root, outDir))
if (publicDir && opts.webp) {
const pngFiles = crawl(publicDir, {
only: ['*.png'],
})
this.resolveBuiltUrl = url => {
if (url[0] === '/' && pngFiles.includes(url.slice(1))) {
return url.replace(pngExt, '.webp')
}
}
}
if (opts.svgo !== false)
// Optimize any inlined SVGs. Non-inlined SVGs are optimized
// in the `closeBundle` phase.
this.transform = async function (code, id) {
if (svgExt.test(id)) {
let exported = /^export default (".+?")$/.exec(code)?.[1]
if (!exported) return
const isRaw = /(\?|&)raw(?:&|$)/.test(id)
try {
let content = JSON.parse(exported)
if (!isRaw) {
if (!content.startsWith(dataUriPrefix)) return
content = decodeURIComponent(
content.slice(dataUriPrefix.length)
)
}
let optimized = await optimizeSvg(content, id)
if (!isRaw) {
optimized = dataUriPrefix + encodeURIComponent(optimized)
}
console.log('optimizeSvg:', { id, content, optimized })
return code.replace(exported, JSON.stringify(optimized))
} catch (err) {
debug(`Failed to transform "${id}". ` + err.message)
}
}
}
},
}
const postPlugin: Plugin = {
name: 'vite:compress',
apply: 'build',
enforce: 'post',
configResolved({ root, logger, build: { ssr } }) {
if (ssr) return
const threshold = opts.threshold ?? 1501
this.buildStart = () => {
this.closeBundle = closeBundle
}
this.buildEnd = error => {
if (error) this.closeBundle = undefined
}
let htmlOpts: HtmlMinifyOptions | undefined
if (opts.minifyHtml) {
const overrides = opts.minifyHtml === true ? {} : opts.minifyHtml
htmlOpts = {
collapseBooleanAttributes: true,
collapseWhitespace: true,
keepClosingSlash: true,
minifyJS: true,
removeAttributeQuotes: true,
removeComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
...overrides,
minifyCSS: minifyCss(overrides.minifyCSS),
}
}
async function closeBundle() {
const files = crawl(outRoot, {
skip: ['.DS_Store'],
})
const compressed = new Map<string, number>()
await Promise.all(
files.map(
async (name): Promise<any> => {
if (!extensionRegex.test(name) || excludeRegex.test(name)) return
let filePath = path.posix.join(outRoot, name)
if (excludeRegex.test(filePath)) return
let { mtimeMs, size: oldSize } = await fsp.stat(filePath)
if (mtimeMs <= (mtimeCache.get(filePath) || 0)) return
let newFilePath: string | undefined
let compress:
| ((content: Buffer) => Buffer | Promise<Buffer>)
| undefined
if (pngExt.test(name)) {
if (opts.webp) {
webpGenerator ??= webp(
opts.webp === true ? undefined : opts.webp
)
newFilePath = filePath.replace(pngExt, '.webp')
compress = content =>
imagemin.buffer(content, {
plugins: [webpGenerator],
})
} else if (opts.pngquant !== false) {
pngOptimizer ??= pngquant(opts.pngquant)
compress = content =>
imagemin.buffer(content, {
plugins: [pngOptimizer],
})
}
} else {
const useBrotli =
oldSize >= threshold &&
!brotliExcludeRegex.test(name) &&
!brotliExcludeRegex.test(filePath)
if (opts.minifyHtml && htmlExt.test(name)) {
compress = content => {
const html = minifyHtml(content.toString('utf8'), htmlOpts)
content = Buffer.from(html)
return useBrotli && content.byteLength >= threshold
? brotli(content)
: content
}
} else if (useBrotli) {
compress = brotli
}
}
let content: Buffer | undefined
if (opts.svgo !== false && svgExt.test(name)) {
content = await fsp.readFile(filePath)
content = Buffer.from(
await optimizeSvg(content.toString('utf8'), filePath)
)
} else if (compress) {
content = await fsp.readFile(filePath)
content = await compress(content)
}
if (content) {
mtimeCache.set(filePath, Date.now())
if (newFilePath) {
await fsp.unlink(filePath)
name = path.relative(outRoot, (filePath = newFilePath))
}
await fsp.writeFile(filePath, content)
compressed.set(name, 1 - content.byteLength / oldSize)
}
}
)
)
if (opts.verbose) {
logger.info('\nFiles compressed:')
const lengths = Array.from(compressed.keys(), name => name.length)
const maxLength = Math.max(...lengths)
const outDir = path.posix.relative(root, outRoot)
compressed.forEach((ratio, name) => {
logger.info(
' ' +
chalk.gray(outDir + '/') +
chalk.green(name) +
' '.repeat(2 + maxLength - name.length) +
chalk.blueBright(`${Math.floor(100 * ratio)}% smaller`)
)
})
logger.info('')
}
}
function brotli(content: Buffer) {
const params = {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]:
opts.quality ?? zlib.constants.BROTLI_MAX_QUALITY,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: content.byteLength,
}
return new Promise<Buffer>((resolve, reject) => {
zlib.brotliCompress(content, { params }, (err, result) =>
err ? reject(err) : resolve(result)
)
})
}
},
}
return [prePlugin, postPlugin]
}
export { PngOptions }
export type SvgOptions = Partial<
Remap<UnionToIntersection<import('svgo').PluginConfig>>
>
type Remap<T> = {} & { [P in keyof T]: T[P] }
type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (
x: infer R
) => any
? R
: never | the_stack |
import {PureComponent, createElement as $, RefObject, createRef} from 'react';
import {
StyleSheet,
Text,
View,
Platform,
ViewStyle,
TextStyle,
TouchableWithoutFeedback,
TouchableOpacity,
FlatList,
TextInput,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
const groupBy = require('just-group-by/index.js');
const mapValues = require('just-map-values/index.js');
const noop = () => {};
interface Emoji {
category: string;
unified: string;
short_name: string;
added_in: string;
_score: number;
}
// Conversion of codepoints and surrogate pairs. See more here:
// https://mathiasbynens.be/notes/javascript-unicode
// https://mathiasbynens.be/notes/javascript-escapes#unicode-code-point
// and `String.fromCodePoint` on MDN
function charFromUtf16(utf16: string) {
return String.fromCodePoint(
...(utf16.split('-').map((u) => '0x' + u) as any),
);
}
function charFromEmojiObj(obj: Emoji): string {
return charFromUtf16(obj.unified);
}
type LocalizedCategories = [
string, // Smileys & Emotion
string, // People & Body
string, // Animals & Nature
string, // Food & Drink
string, // Activities
string, // Travel & Places
string, // Objects
string, // Symbols
string, // Flags
];
const CATEGORIES: LocalizedCategories = [
'Smileys & Emotion',
'People & Body',
'Animals & Nature',
'Food & Drink',
'Activities',
'Travel & Places',
'Objects',
'Symbols',
'Flags',
];
function categoryToIcon(cat: string) {
if (cat === 'Smileys & Emotion') return 'emoticon';
if (cat === 'People & Body') return 'human-greeting';
if (cat === 'Animals & Nature') return 'cat';
if (cat === 'Food & Drink') return 'food-apple';
if (cat === 'Activities') return 'tennis-ball';
if (cat === 'Travel & Places') return 'car';
if (cat === 'Objects') return 'lightbulb';
if (cat === 'Symbols') return 'alert';
if (cat === 'Flags') return 'flag-variant';
return 'emoticon-cool';
}
const DEFAULT_EMOJI_SIZE = 32;
const SHORTCUT_SIZE = DEFAULT_EMOJI_SIZE * 0.75;
const SEARCH_ICON_SIZE = DEFAULT_EMOJI_SIZE * 0.625;
const PADDING = 5;
const DEFAULT_COLUMNS = 7;
const ROWS_VISIBLE = DEFAULT_COLUMNS;
const EMOJI_GROUP_PADDING_BOTTOM = PADDING * 3;
const TOTAL_HEIGHT = DEFAULT_EMOJI_SIZE * ROWS_VISIBLE + PADDING * 2;
const styles = StyleSheet.create({
modal: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
background: {
backgroundColor: '#00000077',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
zIndex: -1,
},
container: {
backgroundColor: 'white',
padding: 0,
borderRadius: 10,
flexDirection: 'column',
},
scrollerContainer: {
minHeight: TOTAL_HEIGHT,
maxHeight: TOTAL_HEIGHT,
...Platform.select({
web: {
overflowY: 'scroll',
},
}),
},
scroller: {
flexDirection: 'column',
minHeight: TOTAL_HEIGHT,
maxHeight: TOTAL_HEIGHT,
paddingHorizontal: PADDING,
},
searchContainer: {
position: 'relative',
flexDirection: 'row',
paddingTop: PADDING,
paddingHorizontal: PADDING,
paddingBottom: 2,
},
search: {
flex: 1,
backgroundColor: '#f2f2f2',
marginTop: 3,
marginHorizontal: 3,
height: 4 + 20 + 4,
paddingVertical: 4,
paddingLeft: 32,
paddingRight: 12,
borderRadius: 3,
color: '#2f2f2f',
zIndex: 10,
},
searchIcon: {
position: 'absolute',
left: 16,
top: PADDING + 3 + 4,
zIndex: 20,
},
headerText: {
padding: PADDING,
color: 'black',
fontWeight: 'bold',
justifyContent: 'center',
textAlignVertical: 'center',
},
categoryOuter: {
flexDirection: 'column',
alignItems: 'flex-start',
},
emojiGroup: {
marginBottom: EMOJI_GROUP_PADDING_BOTTOM,
alignItems: 'center',
flexWrap: 'wrap',
flexDirection: 'row',
},
shortcutsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: PADDING,
},
shortcut: {
padding: PADDING,
},
});
class EmojiGroup extends PureComponent<{
emojis: Array<string>;
onEmojiSelected: (e: string) => void;
emojiSize?: number;
emojiStyle?: TextStyle;
columns?: number;
}> {
public render() {
const emojis = this.props.emojis;
const size = this.props.emojiSize || DEFAULT_EMOJI_SIZE;
const style = {
width: size,
height: size,
boxSizing: 'content-box',
fontSize: size * 0.8,
textAlign: 'center' as const,
lineHeight: size,
margin: PADDING,
} as TextStyle;
const cols = this.props.columns ?? 7;
const maxWidth = (size + PADDING * 2) * cols + 2;
const minWidth = maxWidth;
return $(
View,
{style: [styles.emojiGroup, {minWidth, maxWidth}]},
...emojis
.filter((e) => !!e)
.map((e) =>
$(
Text,
{
style: [style, this.props.emojiStyle],
key: e,
onPress: () => this.props.onEmojiSelected(e),
},
e,
),
),
);
}
}
class EmojiCategory extends PureComponent<{
category: string;
emojisByCategory: Record<string, Array<string>>;
onEmojiSelected: (e: string) => void;
emojiSize?: number;
emojiStyle?: TextStyle;
columns?: number;
headerStyle?: TextStyle;
localizedCategories?: LocalizedCategories;
}> {
public render() {
const {
onEmojiSelected,
emojiSize,
emojiStyle,
columns,
category,
emojisByCategory,
localizedCategories,
headerStyle,
} = this.props;
const emojis = emojisByCategory[category];
const categoryText = localizedCategories
? localizedCategories[CATEGORIES.indexOf(category)]
: category;
return $(
View,
{style: styles.categoryOuter},
$(Text, {style: [styles.headerText, headerStyle]}, categoryText),
$(EmojiGroup, {
emojis,
onEmojiSelected,
emojiSize,
emojiStyle,
columns,
}),
);
}
}
class SearchField extends PureComponent<{
customStyle?: ViewStyle;
iconColor?: any;
onChanged: (str: string) => void;
}> {
public render() {
const {customStyle, iconColor, onChanged} = this.props;
return $(
View,
{style: styles.searchContainer},
$(Icon, {
key: 'a',
size: SEARCH_ICON_SIZE,
style: styles.searchIcon,
color: iconColor ?? '#bcbcbc',
name: 'magnify',
}),
$(TextInput, {
key: 'b',
style: [styles.search, customStyle],
onChangeText: onChanged,
autoFocus: false,
multiline: false,
returnKeyType: 'search',
underlineColorAndroid: 'transparent',
}),
);
}
}
class CategoryShortcuts extends PureComponent<{
show: boolean;
activeCategory: string;
iconColor?: any;
activeIconColor?: any;
onPressCategory?: (cat: string) => void;
}> {
public render() {
// Scroll doesn't work on react-native-web due to bad FlatList support
if (Platform.OS === 'web') {
return $(View, {style: styles.shortcutsContainer});
}
const {onPressCategory, iconColor, activeCategory, activeIconColor, show} =
this.props;
return $(
View,
{style: styles.shortcutsContainer},
...CATEGORIES.map((category) => {
if (show) {
return $(
TouchableOpacity,
{onPress: () => onPressCategory?.(category)},
$(Icon, {
key: category,
size: SHORTCUT_SIZE,
style: styles.shortcut,
color:
category === activeCategory
? activeIconColor ?? '#0c0c0c'
: iconColor ?? '#bcbcbc',
name: categoryToIcon(category),
}),
);
} else {
return $(Icon, {
key: category,
size: SHORTCUT_SIZE,
style: styles.shortcut,
name: categoryToIcon(category),
color: 'transparent',
});
}
}),
);
}
}
function normalize(str: string) {
return str
.toLocaleLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/ +/g, '')
.replace(/_+/g, ' ')
.trim();
}
export default class EmojiModal extends PureComponent<
{
onEmojiSelected: (e: string | null) => void;
onPressOutside?: () => void;
columns?: number;
localizedCategories?: LocalizedCategories;
emojiSize?: number;
emojiStyle?: TextStyle;
modalStyle?: ViewStyle;
backgroundStyle?: ViewStyle;
containerStyle?: ViewStyle;
scrollStyle?: ViewStyle;
headerStyle?: TextStyle;
searchStyle?: ViewStyle;
shortcutColor?: any;
activeShortcutColor?: any;
},
{
searchResults: Array<string>;
activeCategory: string;
}
> {
constructor(props: any) {
super(props);
this.state = {searchResults: [], activeCategory: CATEGORIES[0]};
this.prepareEmojisByCategory();
this.calculateLayouts(props);
}
private emojisByCategory: Record<string, Array<string>> = {};
private filteredEmojis: Array<Emoji> = [];
private layouts: Array<{length: number; offset: number; index: number}>;
private readonly ref: RefObject<FlatList<unknown>> = createRef();
private readonly viewabilityConfig = {
minimumViewTime: 1,
viewAreaCoveragePercentThreshold: 51,
};
private prepareEmojisByCategory() {
const emojiDB = require('./emoji.json') as Array<Emoji>;
const blocklistedEmojis = ['white_frowning_face', 'keycap_star', 'eject'];
this.filteredEmojis = emojiDB.filter((emoji: Emoji) => {
if (blocklistedEmojis.includes(emoji.short_name)) return false;
if (Platform.OS === 'android') {
const addedIn = parseFloat(emoji.added_in);
if (Number.isNaN(addedIn)) return true;
if (addedIn < 2) return true;
if (addedIn === 2) return Platform.Version >= 23;
if (addedIn <= 4) return Platform.Version >= 24;
if (addedIn <= 5) return Platform.Version >= 26;
if (addedIn <= 11) return Platform.Version >= 28;
else return Platform.Version >= 29;
} else {
return true;
}
});
const groupedEmojis = groupBy(
this.filteredEmojis,
(emoji: Emoji) => emoji.category,
);
this.emojisByCategory = mapValues(groupedEmojis, (group: Array<Emoji>) =>
group.map(charFromEmojiObj),
);
}
private calculateLayouts(props: EmojiModal['props']) {
let heightsSoFar = 0;
this.layouts = CATEGORIES.map((category, i) => {
const numEmojis = this.emojisByCategory[category].length;
const numColumns = props.columns ?? DEFAULT_COLUMNS;
const emojiSize = props.emojiSize ?? DEFAULT_EMOJI_SIZE;
const numRows = Math.ceil(numEmojis / numColumns);
const headerHeight = 16 + 2 * PADDING;
const offset = heightsSoFar;
const rowHeight = emojiSize + 2 * PADDING;
const bottomPadding = EMOJI_GROUP_PADDING_BOTTOM;
const height = headerHeight + numRows * rowHeight + bottomPadding;
heightsSoFar += height;
return {length: height, offset, index: i};
});
}
private renderItem = ({item}: any) => {
const {searchResults} = this.state;
if (searchResults.length > 0) {
return $(EmojiGroup, {...this.props, emojis: searchResults});
} else {
const category = item;
return $(EmojiCategory, {
...this.props,
emojisByCategory: this.emojisByCategory,
category,
key: category,
});
}
};
private onSearchChanged = (input: string) => {
if (input.length === 0) {
if (this.state.searchResults.length > 0) {
this.setState({searchResults: []});
}
return;
}
if (input.length < 2) {
return;
}
const searchResults = this.filteredEmojis
.map((emoji) => {
const shortName = normalize(emoji.short_name);
const query = normalize(input);
const score =
shortName === query
? 3
: shortName.startsWith(query)
? 2
: shortName.includes(query)
? 1
: 0;
emoji._score = score;
return emoji;
})
.filter((emoji) => emoji._score > 0)
.sort((a, b) => b._score - a._score)
.map(charFromEmojiObj);
if (searchResults.length === 0) searchResults.push('');
this.setState({searchResults});
};
private onPressCategory = (category: string) => {
// Scroll doesn't work on react-native-web due to bad FlatList support
if (Platform.OS === 'web') return;
const index = CATEGORIES.indexOf(category);
if (index >= 0) {
this.ref.current?.scrollToIndex({
animated: true,
index,
viewPosition: 0,
viewOffset: 0,
});
}
};
private onPressBackground = () => {
this.props.onPressOutside?.();
};
getItemLayout = (data: Array<unknown> | null | undefined, index: number) => {
if (data?.[0] === null) return {length: TOTAL_HEIGHT, offset: 0, index: 0};
return this.layouts[index];
};
onViewableItemsChanged = ({viewableItems}: any) => {
if (viewableItems.length === 0) return;
const category = viewableItems[0].key;
this.setState({activeCategory: category});
};
public render() {
const {
modalStyle,
backgroundStyle,
containerStyle,
scrollStyle,
searchStyle,
shortcutColor,
activeShortcutColor,
} = this.props;
const {searchResults, activeCategory} = this.state;
return $(
View,
{style: [styles.modal, modalStyle]},
$(
View,
{style: [styles.container, containerStyle]},
$(SearchField, {
customStyle: searchStyle,
onChanged: this.onSearchChanged,
iconColor: shortcutColor,
}),
$(
View,
{style: styles.scrollerContainer},
$(FlatList, {
['ref' as any]: this.ref,
data: searchResults.length > 0 ? [null] : CATEGORIES,
horizontal: false,
numColumns: 1,
onEndReachedThreshold: Platform.OS === 'web' ? 1 : 1000,
onScrollToIndexFailed: noop,
style: [styles.scroller, scrollStyle],
initialNumToRender: 1,
maxToRenderPerBatch: 1,
keyExtractor: (category) => category as string,
getItemLayout: this.getItemLayout,
onViewableItemsChanged: this.onViewableItemsChanged,
viewabilityConfig: this.viewabilityConfig,
renderItem: this.renderItem,
}),
),
$(CategoryShortcuts, {
show: searchResults.length === 0,
activeCategory: activeCategory,
iconColor: shortcutColor,
activeIconColor: activeShortcutColor,
onPressCategory: this.onPressCategory,
}),
),
$(
TouchableWithoutFeedback,
{onPress: this.onPressBackground},
$(View, {style: [styles.background, backgroundStyle]}),
),
);
}
} | the_stack |
import {Component, Input, Output, EventEmitter, OnChanges, AfterViewChecked, ViewChild} from '@angular/core';
import {Select2OptionData} from 'ng2-select2';
import {ModalComponent} from 'ng2-bs3-modal/ng2-bs3-modal';
import * as $ from "jquery"
import {downgradeComponent} from '@angular/upgrade/static';
declare var angular:any
import edge = require("selenium-webdriver/edge");
@Component({
selector: 'detail-panel',
templateUrl: "./detailpanel.component.html",
styles: [
'.propAndColumnTable {max-width: 480px; table-layout: fixed}',
'.propAndColumnTable td, .propAndColumnTable th {overflow-x:auto; height: 40px; text-align: center; vertical-align: middle;}',
'.firstColumn {width: 45%;}',
'.secondColumn {width: 25%;}',
'.thirdColumn {width: 30%;}',
'.hideOverflow {max-width: 100%; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; display: inline-block}',
'.OneNRelTable {width: 150px; empty-cells: show}',
'.NNRelTable {width: 100px; empty-cells: show}',
'.OneNRelInfoTable {width: 150px; empty-cells: show;table-layout:fixed;}',
'.NNRelInfoTable {width: 100px; empty-cells: show; table-layout:fixed;}',
'.OneNRelTableLabel {width: 150px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: inline-block;}',
'.NNRelTableLabel {width: 100px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: inline-block;}',
'.OneNRelInfoTable ul, .NNRelInfoTable ul {padding-left: 2px;}',
'.OneNRelInfoTable li, .NNRelInfoTable li {padding-left: 2px; list-style-type: disc; list-style-position: inside; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }',
'.actions-dropdown-item:hover {cursor: pointer}',
'modal .control-label {text-align: right}'
]
})
class DetailPanelComponent implements OnChanges, AfterViewChecked {
@Input() modellingConfig = this.modellingConfig !== 'undefined' ? this.modellingConfig : 'no config from parent.';
@Output() onElementRenamed = new EventEmitter();
@Input() selectedElement = this.selectedElement !== 'undefined' ? this.selectedElement : {name: undefined, properties: undefined}; // needed the second initialization because of renameModal
@Output() onSelectedElementRemoved = new EventEmitter();
private propertiesName;
private edgeName;
private selectedElementPropsUpdated:boolean = false;
// 1-N Relationships Info
private fromTableInfo;
private toTableInfo;
// N-N Relationship Info
private leftTableInfo;
private joinTableInfo;
private rightTableInfo;
// Modals' variables
@ViewChild('renameModal') renameModal: ModalComponent;
@ViewChild('addPropModal') addPropertyModal: ModalComponent;
@ViewChild('editPropertyModal') editPropertyModal: ModalComponent;
@ViewChild('dropPropertyModal') dropPropertyModal: ModalComponent;
@ViewChild('dropClassModal') dropClassModal: ModalComponent;
@ViewChild('dropEdgeInstanceModal') dropEdgeInstanceModal: ModalComponent;
private tmpClassName; // used during class renaming
private tmpPropertyDefinition= {
originalName: undefined,
name: undefined,
type: undefined,
mandatory: false,
readOnly: false,
notNull: false,
ordinalPosition: undefined
};
private fullListTypes = ['BINARY', 'BOOLEAN', 'BYTE', 'EMBEDDED', 'EMBEDDEDLIST', 'EMBEDDEDMAP', 'EMBEDDEDSET', 'DECIMAL', 'FLOAT', 'DATE', 'DATETIME', 'DOUBLE', 'INTEGER', 'LINK', 'LINKLIST', 'LINKMAP', 'LINKSET', 'LONG', 'SHORT', 'STRING'];
private partialListTypes = ['BINARY', 'BOOLEAN', 'BYTE', 'DECIMAL', 'FLOAT', 'DATE', 'DATETIME', 'DOUBLE', 'INTEGER', 'LONG', 'SHORT', 'STRING'];
private tmpIncludedPropertiesNames = [];
private activeFormNewProp = '1';
public excludedPropertiesName: Array<Select2OptionData>;
public propsSelectOptions: Select2Options;
public selectedPropertiesToInclude: string[];
constructor() {
this.edgeName = undefined;
this.propertiesName = [];
this.excludedPropertiesName = [];
this.selectedPropertiesToInclude = [];
this.propsSelectOptions = {
multiple: true
}
}
setSelectedElementPropsUpdated(updated:boolean) {
this.selectedElementPropsUpdated = updated;
}
ngAfterViewChecked() {
this.enablePopovers();
// needed when properties of the current selected element are excluded through the checkbox
if(this.selectedElementPropsUpdated) {
this.updateSelectedElementInfo();
this.selectedElementPropsUpdated = false;
}
}
enablePopovers() {
(<any>$('[data-toggle="popover"]')).popover();
}
ngOnChanges(changes) {
if(changes.selectedElement && this.selectedElement) {
this.updateSelectedElementInfo();
}
}
getEdgeClassName(link) {
var edgeClassName = undefined;
var firstLevelKeys = Object.keys(link);
for(var key of firstLevelKeys) {
if(key !== 'source' && key !== 'target') {
edgeClassName = key;
break;
}
}
return edgeClassName;
}
/**
* Updates the set of properties to include back in a vertex or edge class when the input value changes.
* @param e
*/
updatedSelectedValue(e: any) {
this.selectedPropertiesToInclude = e.value;
}
// called after the update of the current selected element: it updates all info about the selected element
updateSelectedElementInfo() {
if(this.selectedElement) {
if (!this.selectedElement.name) {
// when an edge is selected we store the edge name
this.edgeName = this.getEdgeClassName(this.selectedElement);
// filling properties array
this.propertiesName = [];
this.excludedPropertiesName = [];
var props = this.selectedElement[this.edgeName].properties;
var propsNames = Object.keys(props);
for (var i = 0; i < propsNames.length; i++) {
this.propertiesName.push(propsNames[i]);
if (!props[propsNames[i]].include) {
var currOption = {
id: propsNames[i],
text: propsNames[i]
}
this.excludedPropertiesName.push(currOption);
}
}
}
else {
// when a vertex is selected we delete the edge name
this.edgeName = undefined;
// filling properties array
this.propertiesName = [];
this.excludedPropertiesName = [];
var props = this.selectedElement.properties;
var propsNames = Object.keys(props);
for (var i = 0; i < propsNames.length; i++) {
this.propertiesName.push(propsNames[i]);
if (!props[propsNames[i]].include) {
var currOption = {
id: propsNames[i],
text: propsNames[i]
}
this.excludedPropertiesName.push(currOption);
}
}
}
}
}
renderNNRelationshipInfo(relationship, direction) {
if(direction === "left") {
// deleting rightTableInfo
this.rightTableInfo = undefined;
this.leftTableInfo = {label: "ToColumns", columns: []};
for (var i = 0; i < relationship.fromColumns.length; i++) {
this.leftTableInfo.columns.push(relationship.fromColumns[i]);
}
}
else if(direction === "right") {
// deleting leftTableInfo
this.leftTableInfo = undefined;
this.rightTableInfo = {label: "ToColumns", columns: []};
for (var i = 0; i < relationship.toColumns.length; i++) {
this.rightTableInfo.columns.push(relationship.toColumns[i]);
}
}
this.joinTableInfo = {label: "FromColumns", columns: []};
if(direction === "left") {
for (var i = 0; i < relationship.joinTable.fromColumns.length; i++) {
this.joinTableInfo.columns.push(relationship.joinTable.fromColumns[i]);
}
}
else if(direction === "right") {
for (var i = 0; i < relationship.joinTable.toColumns.length; i++) {
this.joinTableInfo.columns.push(relationship.joinTable.toColumns[i]);
}
}
}
changeSelectedElement(e) {
// deleting info about Relationships
this.leftTableInfo = undefined;
this.joinTableInfo = undefined;
this.rightTableInfo = undefined;
this.fromTableInfo = undefined;
this.toTableInfo = undefined;
}
render1NRelationshipInfo(relationship) {
this.fromTableInfo = {label: "FromColumns", columns: []};
for (var i = 0; i < relationship.fromColumns.length; i++) {
this.fromTableInfo.columns.push(relationship.fromColumns[i]);
}
this.toTableInfo = {label: "ToColumns", columns: []};
for (var i = 0; i < relationship.toColumns.length; i++) {
this.toTableInfo.columns.push(relationship.toColumns[i]);
}
}
/**
* It calculates the next available property ordinal position for the current selected element.
*/
calculateNextOrdinalPosition() {
var maxOrdinalPosition = 0;
if(this.selectedElement.properties) {
var props = this.selectedElement.properties;
var propsNames = Object.keys(props);
for (var i = 0; i < propsNames.length; i++) {
var currOrdinalPosition = this.selectedElement.properties[propsNames[i]].ordinalPosition;
if (currOrdinalPosition > maxOrdinalPosition) {
maxOrdinalPosition = currOrdinalPosition;
}
}
return maxOrdinalPosition + 1;
}
else {
return 1;
}
}
/**
* Sets the default values back for the temporary property definition
*/
cleanTmpPropertyDefinition() {
this.tmpPropertyDefinition = {
originalName: undefined,
name: undefined,
type: undefined,
mandatory: false,
readOnly: false,
notNull: false,
ordinalPosition: undefined
};
}
canBeExcluded(propertyName) {
if(this.selectedElement.externalKey) {
// looking for the property among the current selected element's external key list.
for (var currExternalKey of this.selectedElement.externalKey) {
if (currExternalKey === propertyName) {
return false;
}
}
return true;
}
else {
return true;
}
}
/**
* ----------------------------------------------------------
*
* Modals' methods
*
* ----------------------------------------------------------
*/
/**
* It prepares and opens a drop property modal.
*/
prepareAndOpenDropPropertyModal(propertyName) {
// setting the propertyName in the temporary property definition
this.tmpPropertyDefinition.name = propertyName;
// opening the modal
this.dropPropertyModal.open();
}
/**
* It's called when a drop property modal closing or dismissing occurs.
* It cleans the temporary property definition and closes/dismisses the modal according to the action passed as param.
*/
dismissOrCloseDropPropModal(action) {
if(action === 'close') {
this.dropPropertyFromSelectedClass();
// closing the modal
this.dropPropertyModal.close();
}
else if(action === 'dismiss') {
// dismissing the modal
this.dropPropertyModal.dismiss();
}
// setting default values back for the temporary property definition
this.tmpPropertyDefinition = {
originalName: undefined,
name: undefined,
type: undefined,
mandatory: false,
readOnly: false,
notNull: false,
ordinalPosition: undefined
};
this.cleanTmpPropertyDefinition();
}
/**
* It drops a property from the selected element according to the property name of the temporary property definition.
* If we are dropping a property in an edge class, it will deleted automatically from all the instances of the current selected edge class.
*/
dropPropertyFromSelectedClass() {
var propertyNameToDrop = this.tmpPropertyDefinition.name;
if(this.selectedElement.name) { // dropping from a vertex class
for (var currentPropName in this.selectedElement.properties) {
if (currentPropName === propertyNameToDrop) {
if (this.selectedElement.properties[currentPropName].mapping) {
// removing a property present in the source table means excluding it
this.selectedElement.properties[currentPropName].include = false;
}
else {
// removing a property NOT present in the source table means deleting it
delete this.selectedElement.properties[currentPropName];
}
break;
}
}
}
else {
// dropping the property from all the instances of the current selected edge class
for(var edge of this.modellingConfig.edges) {
if (this.getEdgeClassName(edge) === this.edgeName) {
for (var currentPropName in edge[this.edgeName].properties) {
if (currentPropName === propertyNameToDrop) {
if (edge[this.edgeName].properties[currentPropName].mapping) {
// removing a property present in the source table means excluding it
edge[this.edgeName].properties[currentPropName].include = false;
}
else {
// removing a property NOT present in the source table means deleting it
delete edge[this.edgeName].properties[currentPropName];
}
break;
}
}
}
}
}
this.updateSelectedElementInfo(); // maybe not needed
}
/**
* It drops the class corresponding to the selected element.
*/
dropClass() {
var className;
var classType;
// setting the selected element and the current edge name (if we are dropping an edge class) to undefined
if(this.selectedElement.name) {
// removing a vertex class
className = this.selectedElement.name;
classType = "vertexClass";
}
else {
// removing an edge class
className = this.getEdgeClassName(this.selectedElement);
classType = "edgeClass";
this.edgeName = undefined;
}
// cleaning the current selected element
this.selectedElement = undefined;
// emitting event for the graph update
this.onSelectedElementRemoved.emit({className: className, classType: classType});
}
/**
* It drops the current selected edge class instance.
*/
dropEdgeClassInstance() {
var className = this.getEdgeClassName(this.selectedElement);
var sourceName = this.selectedElement.source.name;
var targetName = this.selectedElement.target.name;
this.edgeName = undefined;
// cleaning the current selected element
this.selectedElement = undefined;
// emitting event for the graph update
this.onSelectedElementRemoved.emit({dropEdgeInstance: true, edgeClassName: className, sourceName: sourceName, targetName: targetName});
}
/**
* It prepares the 'rename class' modal
*/
prepareAndOpenRenameClassModal(className) {
// setting the class name in the temporary class name
this.tmpClassName = className;
// opening the modal
this.renameModal.open();
}
/**
* Renames the selected vertex class.
*/
renameSelectedVertexClass() {
var oldVertexName = this.selectedElement.name;
this.selectedElement.name = this.tmpClassName;
this.onElementRenamed.emit({oldClassName: oldVertexName, newClassName: this.tmpClassName, classType: "vertexClass"});
this.tmpClassName = undefined; // maybe not needed, tmpClassName overwritten in prepareAndOpenRenameClassModal !!! check
this.updateSelectedElementInfo();
this.renameModal.close();
}
/**
* Renames the selected edge class, automatically updating all the instances of the class.
*/
renameSelectedEdgeClass() {
var oldEdgeName = this.getEdgeClassName(this.selectedElement);
var edgeDef = undefined;
// update potential all the instances of the edge class
for(var i=0; i<this.modellingConfig.edges.length; i++) {
var currEdge = this.modellingConfig.edges[i];
var currEdgeName = this.getEdgeClassName(currEdge);
if(oldEdgeName === currEdgeName) {
edgeDef = currEdge[currEdgeName];
delete currEdge[currEdgeName];
currEdge[this.tmpClassName] = edgeDef;
}
}
// emitting event for the graph update
this.onElementRenamed.emit({oldClassName: oldEdgeName, newClassName: this.tmpClassName, classType: "edgeClass"});
this.tmpClassName = undefined; // maybe not needed, tmpClassName overwritten in prepareAndOpenRenameClassModal !!!! check
this.updateSelectedElementInfo();
this.renameModal.close();
}
/**
* It prepares and opens a drop class modal.
*/
prepareAndOpenDropClassModal() {
// opening the modal
this.dropClassModal.open();
}
prepareAndOpenDropEdgeModal() {
// opening the modal
this.dropEdgeInstanceModal.open();
}
/**
* It's called when a drop class modal closing or dismissing occurs.
* It drops the selected class and closes/dismisses the modal.
*/
dismissOrCloseDropClassModal(action) {
if(action === 'close') {
this.dropClass();
// closing the modal
this.dropClassModal.close();
}
else if(action === 'dismiss') {
// dismissing the modal
this.dropClassModal.dismiss();
}
}
/**
* It's called when a drop class modal closing or dismissing occurs.
* It drops the selected edge class instance and closes/dismisses the modal.
*/
dismissOrCloseDropEdgeInstanceModal(action) {
if(action === 'close') {
this.dropEdgeClassInstance();
// closing the modal
this.dropEdgeInstanceModal.close();
}
else if(action === 'dismiss') {
// dismissing the modal
this.dropEdgeInstanceModal.dismiss();
}
}
/**
* It opens the 'add property' Modal
*/
prepareAndOpenAddPropertyModal() {
// opening the modal
this.addPropertyModal.open();
}
/**
* Add the defined property in the selected class, so if the current selected element is an edge the property will be added:
* - in the current selected element
* - in all the other instances of the selected edge class
*/
addNewPropToSelectedClass() {
if (this.activeFormNewProp === '1') {
// property to be added in the selected element properties list
var newProp = {include: true, type: undefined, mandatory: undefined, readOnly: undefined, notNull: undefined, ordinalPosition: undefined};
newProp.type = this.tmpPropertyDefinition.type;
newProp.mandatory = this.tmpPropertyDefinition.mandatory;
newProp.readOnly = this.tmpPropertyDefinition.readOnly;
newProp.notNull = this.tmpPropertyDefinition.notNull;
newProp.ordinalPosition = this.calculateNextOrdinalPosition();
if(this.selectedElement.name) { // setting the newProp in a vertex class
// if properties field is not present, it will be added
if(!this.selectedElement.properties) {
this.selectedElement.properties = {};
}
this.selectedElement.properties[this.tmpPropertyDefinition.name] = newProp;
}
else {
// setting the newProp in an edgeClass
// setting the property in all the instances of the current selected edge class
for(var edge of this.modellingConfig.edges) {
if(this.getEdgeClassName(edge) === this.edgeName) {
// if properties field is not present, it will be added
if(!edge[this.edgeName].properties) {
edge[this.edgeName].properties = {};
}
edge[this.edgeName].properties[this.tmpPropertyDefinition.name] = newProp;
}
}
}
this.cleanTmpPropertyDefinition();
}
else if(this.activeFormNewProp === '2') {
for(var currProp of this.excludedPropertiesName) {
if(this.selectedPropertiesToInclude.indexOf(currProp.id) >= 0) { // if current excluded properties is contained in the selected properties to include again then...
if (this.selectedElement.name) { // including the prop in a vertex class
this.selectedElement.properties[currProp.id].include = true;
}
else { // including the prop in an edge class
this.selectedElement[this.edgeName].properties[currProp.id].include = true;
}
}
}
// the just included prop will be removed from excludedProperties during the updateSelectElementInfo() method execution
// setting default input value
this.selectedPropertiesToInclude = [];
}
//setting again the default choose for the modal
this.activeFormNewProp = '1';
// setting default values back for the temporary property definition
this.cleanTmpPropertyDefinition();
this.updateSelectedElementInfo();
// closing modal
this.addPropertyModal.close();
}
dismissPropertyAdding() {
// setting again the default choose for the modal
this.activeFormNewProp = '1';
// setting default input value
this.selectedPropertiesToInclude = [];
// setting default values back for the temporary property definition
this.cleanTmpPropertyDefinition();
// dismissing modal
this.addPropertyModal.dismiss();
}
/**
* It prepares the info for the 'Edit Property Modal', then it open it:
* - the current property is copied in a temporary property definition
* - the modal is opened
*/
prepareAndOpenPropertyEditingModal(propertyName) {
var property;
if(this.selectedElement.name) { // preparing property editing in a vertex class
property = this.selectedElement.properties[propertyName];
}
else { // preparing property editing in an edge class
property = this.selectedElement[this.edgeName].properties[propertyName];
}
// cloning original property into temporary property definition
this.tmpPropertyDefinition = JSON.parse(JSON.stringify(property));
this.tmpPropertyDefinition.name = propertyName;
this.tmpPropertyDefinition.originalName = propertyName;
// opening modal
this.editPropertyModal.open();
}
/**
* When the 'Edit Property Modal' is dismissed this method in invoked to clean the temporary property definition
* and close the modal.
*/
dismissEditPropertyModal() {
// setting default values back for the temporary property definition
this.cleanTmpPropertyDefinition();
// closing the modal
this.editPropertyModal.close();
}
/**
* It copies the temporary property definition into the current property being edited,
* then it closes the modal.
* If we are editing a property in an edge class, it will updated automatically in all the instances of the current selected edge class.
*/
closeEditPropertyModal() {
var newPropertyName = this.tmpPropertyDefinition.name;
var oldPropertyName = this.tmpPropertyDefinition.originalName;
// deleting 'name' and 'originalName' fields from the temporary property definition (so when copied in the selected element the fields won't be present)
delete this.tmpPropertyDefinition.originalName;
delete this.tmpPropertyDefinition.name;
if(this.selectedElement.name) { // editing a property in a vertex class
// deleting old property (delete is needed in case of property renaming)
delete this.selectedElement.properties[oldPropertyName];
// copying temporary property definition into the current property being edited
this.selectedElement.properties[newPropertyName] = JSON.parse(JSON.stringify(this.tmpPropertyDefinition));
// if the current editing property is an external key property, update it also the other JSON declaration
for(var i=0; i<this.selectedElement.externalKey.length; i++) {
var currExternalKey = this.selectedElement.externalKey[i];
if(oldPropertyName === currExternalKey) {
// update it with the new property name
this.selectedElement.externalKey[i] = newPropertyName;
break;
}
}
}
else { // editing a property in an edge class
for(var edge of this.modellingConfig.edges) {
if(this.getEdgeClassName(edge) === this.edgeName) {
// deleting old property (delete is needed in case of property renaming)
delete edge[this.edgeName].properties[oldPropertyName];
// copying temporary property definition into the current property being edited
edge[this.edgeName].properties[newPropertyName] = JSON.parse(JSON.stringify(this.tmpPropertyDefinition));
}
}
}
// setting default values back for the temporary property definition
this.cleanTmpPropertyDefinition();
// closing the modal
this.editPropertyModal.close();
this.updateSelectedElementInfo();
}
}
angular.module('detailpanel.component', []).directive(
`detail-panel`,
downgradeComponent({component: DetailPanelComponent}));
export {DetailPanelComponent}; | the_stack |
import React from 'react';
import { IActa, TActaValue } from './types';
import { isObject } from './isObject';
const actaStoragePrefix = '__acta__';
const actaStoragePrefixLength = actaStoragePrefix.length;
const actaEventPrefix = '__actaEvent__';
const actaEventPrefixLength = actaEventPrefix.length;
const isInDOM = typeof window !== 'undefined';
let tempStateHooksId = 0;
let tempEventHooksId = 0;
const Acta: IActa = {
/**
* Boolean to know if acta has been initialized before
*/
initialized: false,
/**
* states will hold values, subscribers list and history indexed by keys
* events will hold subscribers list indexed by events keys
* actions will hold actions function indexed by actions keys
* actaIDs will be an array of unique ids
*/
actaIDs: [],
events: {},
states: {},
/**
* The init function will search for any previousely acta states in the local
* and session storage and will start listening on the changes in the storages
* to update itself if the storage is updated from another tab
*/
init(): void {
/**
* Acta is now initialized
*/
this.initialized = true;
/**
* Attach to the window for global public access
*/
(window as any).Acta = Acta;
/**
* Listen to the storage to synchronise Acta between tabs
*/
window.addEventListener(
'storage',
(event) => {
const key = event.key;
const newValue = event.newValue;
if (
key &&
key.slice(0, actaStoragePrefixLength) === actaStoragePrefix
) {
if (newValue !== null && newValue !== '' && newValue !== 'null') {
this.setState({
[key.slice(actaStoragePrefixLength)]: JSON.parse(newValue),
});
} else {
this.setState({
[key.slice(actaStoragePrefixLength)]: null,
});
}
} else if (
newValue !== null &&
key?.slice(0, actaEventPrefixLength) === actaEventPrefix
) {
this.dispatchEvent(
key.slice(actaEventPrefixLength),
newValue ? JSON.parse(newValue) : newValue,
false
);
localStorage.removeItem(key);
}
},
false
);
/**
* Load the data from local and session storage
*/
const storage = {
...localStorage,
...sessionStorage,
};
const storageKeys = Object.keys(storage);
for (const storageKey of storageKeys) {
if (storageKey.slice(0, actaStoragePrefixLength) === actaStoragePrefix) {
const value = JSON.parse(storage[storageKey]);
if (value !== undefined && value !== null) {
this.setState({
[storageKey.slice(actaStoragePrefixLength)]: value,
});
}
}
}
},
/**
* This method will subscribe a react functionnal component to
* an Acta state.
*
* @param { String } actaStateKey - the state key
* @param { TActaValue } defaultValue - optionnal - the initial value
* if not set, the initial value will be undefined
*/
useActaState(actaStateKey: string, defaultValue?: TActaValue) {
/* Ensure the arguments */
if (actaStateKey === '' || typeof actaStateKey !== 'string') {
throw new Error(
`Acta.useActaState params =>
[0]: string,
[1]: optionnal, string | number | object | boolean | null | undefined`
);
}
/* Update the interal id for future reference */
const internalID = tempStateHooksId++;
/**
* Try to get an initial value in Acta if the state already exists
* of in the optional defaultValue
*/
const initialValue = this.hasState(actaStateKey)
? this.getState(actaStateKey)
: defaultValue;
/**
* Init the state hook that wll return the value and
* trigger a re-render for the component
*/
const [actaValue, setActaValue] = React.useState(initialValue);
/* If this state does not already exists, creates it */
this.states[actaStateKey] = this.states[actaStateKey] || {
value: defaultValue,
defaultValue: defaultValue,
subscribtions: {},
};
/**
* Add the life cycle hook to subscribe to the state when
* the component is rendered and unsubscribe when the component
* is unmounted
*/
React.useEffect(
() => {
/* Subscribe to the acta state */
this.states[actaStateKey].subscribtions[`__${internalID}`] = {
callback: (value) => setActaValue(value),
};
/* Unsubscribe when the component will unmount */
return () => {
delete this.states[actaStateKey].subscribtions[`__${internalID}`];
};
},
/* This empty array makes that the return triggers only on the final unmount */
[]
);
/* Returns the initial value for immediate use */
return actaValue;
},
/**
* subscribeState is called from a react component with a callback
* when that state will be set, its value will be send
* to the component by the callback
*
* that subsribtion can be destroyed manually and will be
* destroyed automatically when the
*
* @param {String} actaStateKey - The key to name the state
* @param {Function | String} callbackOrLocalStateKey - Reference to the callback
* that will be called when the state change or to the state key to set
* @param {Object} context - Reference to the react component from
* wich the subscribtion is made => that will be needed to unsubscribe
* when the compnent will unmount
* @param {TActaValue} defaultValue - Optionnal, set a default value for
* the state if there is none
*/
subscribeState(
actaStateKey,
callbackOrLocalStateKey,
context,
defaultValue = undefined
) {
/* Ensure the arguments */
if (
actaStateKey === '' ||
typeof actaStateKey !== 'string' ||
(typeof callbackOrLocalStateKey !== 'function' &&
typeof callbackOrLocalStateKey !== 'string') ||
!isObject(context)
) {
throw new Error(
`Acta.subscribeState params =>
[0]: string,
[1]: function or string,
[2]: mounted react component`
);
}
/* If the component does not have an acta id, get him one */
this.ensureActaID(context);
/* If this state does not already exists, creates it */
this.states[actaStateKey] = this.states[actaStateKey] || {
value: defaultValue,
defaultValue: defaultValue,
subscribtions: {},
};
/**
* If a subscribtion for this context on this state
* already exists, stop here
*/
if (this.states[actaStateKey].subscribtions[context.actaID as string]) {
return;
}
/**
* Extend the componentWillUnmount hook on the context
* with a state unsubscribtion, so when
* the component unmounts, all its states subscribtions
* will be destroyed
*/
if (context.componentWillUnmount) {
const oldComponentWillUnmount = context.componentWillUnmount;
context.componentWillUnmount = () => {
this.unsubscribeState(actaStateKey, context);
oldComponentWillUnmount.bind(context)();
};
}
/**
* If the callback is not a function, it sets the state
* in the component
*/
let passedCallback;
if (typeof callbackOrLocalStateKey === 'string') {
passedCallback = (value: TActaValue) =>
context.setState({
[callbackOrLocalStateKey]: value,
});
} else {
passedCallback = callbackOrLocalStateKey;
}
/**
* Add the callback and the context to the subscribtion list
* of the state
*/
this.states[actaStateKey].subscribtions[context.actaID as string] = {
callback: passedCallback,
context,
};
/* Dispatch the initial or current value to the subscriber
if initialize is not set to false and if there is a valid
non circular state to dispatch */
try {
if (this.states[actaStateKey].value !== undefined) {
passedCallback(
JSON.parse(JSON.stringify(this.states[actaStateKey].value))
);
}
} catch (err) {
console.error(`Error in subscribeState for "${actaStateKey}":`, err);
}
},
/**
* unsubscribeState will simply remove the target context form
* the subscribtions of the target state
*
* @param {String} stateKey - The key to name the state
* @param {Object} context - Reference to the target react component
*/
unsubscribeState(stateKey, context) {
/* Ensure the arguments */
if (typeof stateKey !== 'string' || !isObject(context)) {
throw new Error(
`Acta.unsubscribeState params =>
[0]: string,
[2]: mounted react component`
);
}
/* Delete the subscribtion */
if (this.states[stateKey])
delete this.states[stateKey].subscribtions[context.actaID as string];
},
/**
* set state will save the value in the the tagret state
* and will dispatch that update to all the subscriber
* by he provided callback
*
* @param {Object} states - mandatory - an object where the keys are states to set and
* values the target values
* @param {String} persistenceType - optionnal - can be "sessionStorage" or "localStorage"
* if set, the state will be saved into the corresponding storage
*/
setState(states, persistenceType) {
/* Ensure the arguments */
if (!isObject(states) || Object.keys(states).length === 0) {
throw new Error('Acta.setState params => [0]: object with 1+ key');
}
/**
* Loop over the states
*/
for (const state of Object.entries(states)) {
const stateKey = state[0];
const value = state[1];
/* If this state does not already exists, creates it */
if (!this.states[stateKey]) {
this.states[stateKey] = this.states[stateKey] || {
value: value || undefined,
defaultValue: undefined,
subscribtions: {},
};
}
/* Save the value */
this.states[stateKey].value = value;
/* If persistence is configured and we have a window, store the value */
if (isInDOM && persistenceType) {
if (persistenceType === 'localStorage') {
localStorage.setItem(
`${actaStoragePrefix}${stateKey}`,
JSON.stringify(value)
);
} else if (persistenceType === 'sessionStorage') {
sessionStorage.setItem(
`${actaStoragePrefix}${stateKey}`,
JSON.stringify(value)
);
} else {
throw new Error(
'Acta.setState params => [1]: "sessionStorage" | "localStorage".'
);
}
}
/**
* Try to dispatch to all subscribers & kill the
* subscribtion if the subscriber has been destroyed
*/
if (this.states[stateKey].subscribtions) {
Object.keys(this.states[stateKey].subscribtions).forEach((actaID) => {
try {
this.states[stateKey].subscribtions[actaID].callback(value);
// eslint-disable-next-line no-empty
} catch (err) {}
});
}
}
},
/**
* Delete a state
*
* @param {String} state the state to target
*/
deleteState(stateKey, persistenceType) {
/* Ensure the arguments */
if (typeof stateKey !== 'string' || stateKey === '') {
throw new Error('Acta.deleteState params => [0]: string');
}
delete this.states[stateKey];
/**
* If the persistance type is set and we have a window, remove the
* value from the storage
*/
if (isInDOM && persistenceType) {
if (persistenceType === 'sessionStorage') {
sessionStorage.removeItem(`${actaStoragePrefix}${stateKey}`);
} else if (persistenceType === 'localStorage') {
localStorage.removeItem(`${actaStoragePrefix}${stateKey}`);
} else {
throw new Error(
'Acta.deleteState params => [1]: "sessionStorage" | "localStorage".'
);
}
}
},
/**
* return the state form its name
*
* @param {String} stateKey - the key to identify the target state
* @return {*} can be anything
*/
getState(stateKey) {
/* Check the parameter */
if (typeof stateKey !== 'string') {
throw new Error('Acta.deleteState params => [0]: string');
}
return (
this.states[stateKey]?.value ||
this.states[stateKey]?.defaultValue ||
undefined
);
},
/**
* check the existence of a state
*
* @param {String} stateKey - the key to identify the target state
*/
hasState(stateKey) {
/**
* Check param
*/
if (typeof stateKey !== 'string') {
throw new Error('Acta.hasState params => [0]: string');
}
// eslint-disable-next-line no-prototype-builtins
return this.states.hasOwnProperty(stateKey);
},
/**
* Creates an event hook. A functional component can subscribe to
* and event. The functionnal passes a callback and when the
* event is dispatched from anywhere in the application,
* the callback is triggered.
*
* @param { String } eventKey - the event key
* @param { Function } callback - the callback after the event is dispatched
*/
useActaEvent(eventKey, callback) {
/* Ensure the arguments */
if (
eventKey === '' ||
typeof eventKey !== 'string' ||
typeof callback !== 'function'
) {
throw new Error(
`Acta.useActaEvent params =>
[0]: string,
[1]: function`
);
}
/* Update the interal id for future reference */
const internalID = tempEventHooksId++;
/* If this state does not already exists, creates it */
this.events[eventKey] = this.events[eventKey] || {};
/**
* Add the life cycle hook to subscribe to the state when
* the component is rendered and unsubscribe when the component
* is unmounted
*/
React.useEffect(
() => {
/* Subscribe to the event */
this.events[eventKey][`__${internalID}`] = {
callback,
};
/* Unsubscribe */
return () => {
delete this.events[eventKey][`__${internalID}`];
};
},
/* This empty array makes that the return triggers only on the final unmount */
[]
);
},
/**
* subscribeEvent is called from a react component with a callback
* when the corresponding event is dispatched, the callback is called
* passing any argument set in the dispatcher
*
* that subsribtion can be destroyed manually and will be
* destroyed automatically when the component unmount
*
* @param {String} eventKey - The key to name the event
* @param {Function} callback - Reference to the callback that will
* be called when the state change
* @param {React.Component} context - Reference to the react component from
* wich the subscribtion is made => that will be needed to unsubscribe
* when the compnent woll unmount
*/
subscribeEvent(eventKey, callback, context) {
/* Ensure the arguments */
if (
eventKey === '' ||
typeof eventKey !== 'string' ||
typeof callback !== 'function' ||
!isObject(context)
) {
throw new Error(
`Acta.subscribeEvent params =>
[0]: string,
[1]: function,
[2]: mounted react component`
);
}
/* If this event does not already exists, creates it */
this.events[eventKey] = this.events[eventKey] || {};
/* If the component does not have an acta id, get him one */
this.ensureActaID(context);
/* If this context already listen to that event already exists, stop here */
if (this.events[eventKey][context.actaID as string]) {
return false;
}
/**
* Extend the componentWillUnmount hook on the context
* with a event unsubscribtion, so when
* the component unmounts, all its events subscribtions
* will be destroyed
*/
if (context.componentWillUnmount) {
const oldComponentWillUnmount = context.componentWillUnmount;
context.componentWillUnmount = () => {
this.unsubscribeEvent(eventKey, context);
oldComponentWillUnmount.bind(context)();
};
}
/**
* Add the callback and the context to the event listener list
* of the event
*/
this.events[eventKey][context.actaID as string] = {
callback,
context,
};
return;
},
/**
* unsubscribeEvent will remove the target context form
* the subscribtions of the target eve,t
*
* @param {String} eventKey - The key to name the eventKey
* @param {Object} context - Reference to the target react component
*/
unsubscribeEvent(eventKey, context) {
/* Ensure the arguments */
if (typeof eventKey !== 'string' || !isObject(context)) {
throw new Error(
`Acta.subscribeEvent params =>
[0]: string,
[2]: mounted react component`
);
}
/* Delete the subscribtion */
if (this.events[eventKey])
delete this.events[eventKey][String(context.actaID)];
},
/**
* Dispatch an event : check if the event exists and has subscribers
* if it does, call the callback of each subscriber
*
* @param {String} eventKey - the key to target the event
* @param {TActaValue} data - the data passed with the event
* @param {Boolean} isShared - if the event should be shared accross tabs and windows
*/
dispatchEvent(eventKey, data, isShared) {
/* Ensure the arguments */
if (typeof eventKey !== 'string') {
throw new Error(
'Acta.dispatchEvent params => [0]: string & must exist in Acta.events'
);
}
/**
* If this is a shared message, send it to the local storage;
* it will come back instantly
*/
if (isShared && isInDOM) {
localStorage.setItem(actaEventPrefix + eventKey, JSON.stringify(data));
}
/**
* Call each subscriber callback
*/
Object.keys(this.events[eventKey] || {}).forEach((actaID) => {
try {
this.events[eventKey][actaID].callback(data || null);
// eslint-disable-next-line no-empty
} catch (err) {}
});
},
/**
* ensureActaID is a small utility function to
* inject a unique id to all subscribers contexts
*/
ensureActaID(context) {
/* Stops there if there is already an ID */
if (!context || context.actaID) return false;
/* Insert a new ID in the list and inject it int the context */
const newId = `_${this.actaIDs.length}`;
this.actaIDs.unshift(newId);
context.actaID = newId;
return newId;
},
};
/**
* If Acta has not been initialized, init Acta
*/
if (!Acta.initialized && isInDOM) Acta.init();
export default Acta; | the_stack |
module formFor {
/**
* SelectField $scope.
*/
interface SelectFieldScope extends ng.IScope {
/**
* Allow an empty/blank option in the <select>.
* Note that this is a display setting only and is not related to form validation.
* (Fields with blank options may still be required.)
*/
allowBlank:boolean;
/**
* Name of the attribute within the parent form-for directive's model object.
* This attributes specifies the data-binding target for the input.
* Dot notation (ex "address.street") is supported.
*/
attribute:string;
/**
* Set of options the directive template should bind to.
* This set contains all of the "options" as well as an empty/placeholder option under certain conditions.
*/
bindableOptions:Array<Object>;
/**
* Views must call this callback to notify of the <select> menu having been closed.
*/
close:Function;
/**
* Disable input element.
* Note the name is disable and not disabled to avoid collisions with the HTML5 disabled attribute.
* This attribute defaults to 'auto' which means that the menu will drop up or down based on its position within the viewport.
*/
disable:boolean;
/**
* Empty option created if select menu allows empty selection.
*/
emptyOption:any;
/**
* Optional help tooltip to display on hover.
* By default this makes use of the Angular Bootstrap tooltip directive and the Font Awesome icon set.
*/
help?:string;
/**
* Select menu is currently open.
*/
isOpen:boolean;
/**
* Key-down event handler to be called by view template.
*/
keyDown:(event:any) => void;
/**
* Optional field label displayed before the drop-down.
* (Although not required, it is strongly suggested that you specify a value for this attribute.) HTML is allowed for this attribute.
*/
label?:string;
/**
* Optional override for label key in options array.
* Defaults to "label".
*/
labelAttribute?:string;
/**
* Optional class-name for field <label>.
*/
labelClass?:string;
/**
* Shared between formFor and SelectField directives.
*/
model:BindableFieldWrapper;
/**
* Updates mouse-over index.
* Called in response to arrow-key navigation of select menu options.
*/
mouseOver:(index:number) => void;
/**
* Moused-over option.
*/
mouseOverOption:any;
/**
* Index of moused-over option.
*/
mouseOverIndex:number;
/**
* Drop-down list should allow multiple selections.
*/
multiple?:boolean;
/**
* Views must call this callback to notify of the <select> menu having been opened.
*/
open:Function;
/**
* Set of options, each containing a label and value key.
* The label is displayed to the user and the value is assigned to the corresponding model attribute on selection.
*/
options:Array<Object>;
/**
* Optional placeholder text to display if no value has been selected.
* The text "Select" will be displayed if no placeholder is provided.
*/
placeholder?:string;
/**
* Optional attribute to override default selection of the first list option.
* Without this attribute, lists with `allow-blank` will default select the first option in the options array.
*/
preventDefaultOption:boolean;
/**
* Used to share data between main select-field template and ngIncluded templates.
*/
scopeBuster:any;
/**
* Selects the specified option.
*/
selectOption:(option:any) => void;
/**
* Optional custom tab index for input; by default this is 0 (tab order chosen by the browser)
*/
tabIndex?:number;
/**
* Optional ID to assign to the inner <input type="checkbox"> element;
* A unique ID will be auto-generated if no value is provided.
*/
uid?:string;
/**
* Optional override for value key in options array.
* Defaults to "value".
*/
valueAttribute:string;
}
var MIN_TIMEOUT_INTERVAL:number = 10;
var $document_:ng.IAugmentedJQuery;
var $log_:ng.ILogService;
var $timeout_:ng.ITimeoutService;
var fieldHelper_:FieldHelper;
var formForConfiguration_:FormForConfiguration;
/**
* Renders a drop-down <select> menu along with an input label.
* This type of component works with large enumerations and can be configured to allow for a blank/empty selection
* by way of an allow-blank attribute.
*
* The following HTML attributes are supported by this directive:
* <ul>
* <li>allow-blank: The presence of this attribute indicates that an empty/blank selection should be allowed.
* <li>prevent-default-option: Optional attribute to override default selection of the first list option.
* Without this attribute, lists with `allow-blank` will default select the first option in the options array.
*</ul>
*
* @example
* // To use this component you'll first need to define a set of options. For instance:
* $scope.genders = [
* { value: 'f', label: 'Female' },
* { value: 'm', label: 'Male' }
* ];
*
* // To render a drop-down input using the above options:
* <select-field attribute="gender"
* label="Gender"
* options="genders">
* </select-field>
*
* // If you want to make this attribute optional you can use the allow-blank attribute as follows:
* <select-field attribute="gender"
* label="Gender"
* options="genders"
* allow-blank>
* </select-field>
*
* @param $document $injector-supplied $document service
* @param $log $injector-supplied $log service
* @param $timeout $injector-supplied $timeout service
* @param fieldHelper
* @param formForConfiguration
*/
export class SelectFieldDirective implements ng.IDirective {
require:string = '^formFor';
restrict:string = 'EA';
templateUrl:string = ($element, $attributes) => {
return $attributes['template'] || 'form-for/templates/select-field.html';
};
scope:any = {
attribute: '@',
disable: '=',
help: '@?',
multiple: '=?',
options: '='
};
/* @ngInject */
constructor($document:ng.IAugmentedJQuery,
$log:ng.ILogService,
$timeout:ng.ITimeoutService,
fieldHelper:FieldHelper,
formForConfiguration:FormForConfiguration) {
$document_ = $document;
$log_ = $log;
$timeout_ = $timeout;
fieldHelper_ = fieldHelper;
formForConfiguration_ = formForConfiguration;
}
/* @ngInject */
link($scope:SelectFieldScope,
$element:ng.IAugmentedJQuery,
$attributes:ng.IAttributes,
formForController:FormForController):void {
if (!$scope.attribute) {
$log_.error('Missing required field "attribute"');
return;
}
$scope.allowBlank = $attributes.hasOwnProperty('allowBlank');
$scope.preventDefaultOption = $attributes.hasOwnProperty('preventDefaultOption');
// Read from $attributes to avoid getting any interference from $scope.
$scope.labelAttribute = $attributes['labelAttribute'] || 'label';
$scope.valueAttribute = $attributes['valueAttribute'] || 'value';
$scope.placeholder = $attributes.hasOwnProperty('placeholder') ? $attributes['placeholder'] : 'Select';
$scope.tabIndex = $attributes['tabIndex'] || 0;
$scope.scopeBuster = {};
fieldHelper_.manageLabel($scope, $attributes, false);
fieldHelper_.manageFieldRegistration($scope, $attributes, formForController);
$scope.close = () => {
$timeout_(() => {
$scope.isOpen = false;
});
};
$scope.open = () => {
if ($scope.disable || $scope.model.disabled) {
return;
}
$timeout_(() => {
$scope.isOpen = true;
});
};
$scope.bindableOptions = [];
$scope.emptyOption = {};
$scope.emptyOption[$scope.labelAttribute] = $scope.placeholder;
$scope.emptyOption[$scope.valueAttribute] = formForConfiguration_.defaultSelectEmptyOptionValue;
/*****************************************************************************************
* The following code manages setting the correct default value based on bindable model.
*****************************************************************************************/
$scope.selectOption = (option:any) => {
$scope.model.bindable = option && option[$scope.valueAttribute];
};
var updateDefaultOption:(value?:any) => any = () => {
var numOptions:number = $scope.options && $scope.options.length;
// Default select the first item in the list
// Do not do this if a blank option is allowed OR if the user has explicitly disabled this function
if (!$scope.model.bindable && !$scope.allowBlank && !$scope.preventDefaultOption && numOptions) {
$scope.selectOption($scope.options[0]);
}
// Certain falsy values may indicate a non-selection.
// In this case, the placeholder (empty) option needs to match the falsy selected value,
// Otherwise the Angular select directive will generate an additional empty <option> ~ see #110
// Angular 1.2.x-1.3.x may generate an empty <option> regardless, unless the non-selection is undefined.
if ($scope.model.bindable === null ||
$scope.model.bindable === undefined ||
$scope.model.bindable === '') {
// Rather than sanitizing `$scope.model.bindable` to undefined, update the empty option's value.
// This way users are able to choose between undefined, null, and empty string ~ see #141
$scope.model.bindable = formForConfiguration_.defaultSelectEmptyOptionValue;
$scope.emptyOption[$scope.valueAttribute] = $scope.model.bindable;
}
$scope.bindableOptions.splice(0);
if (!$scope.model.bindable || $scope.allowBlank) {
$scope.bindableOptions.push($scope.emptyOption);
}
$scope.bindableOptions.push.apply($scope.bindableOptions, $scope.options);
// Once a value has been selected, clear the placeholder prompt.
if ($scope.model.bindable) {
$scope.emptyOption[$scope.labelAttribute] = '';
}
};
// Allow the current $digest cycle (if we're in one) to complete so that the FormForController has a chance to set
// the bindable model attribute to that of the external formData field. This way we won't overwrite the default
// value with one of our own.
$timeout_(() => {
$scope.$watch('model.bindable', updateDefaultOption);
$scope.$watch('options.length', updateDefaultOption);
});
/*****************************************************************************************
* The following code deals with toggling/collapsing the drop-down and selecting values.
*****************************************************************************************/
var documentClick = (event) => {
$scope.close();
};
var pendingTimeoutId:ng.IPromise<any>;
$scope.$watch('isOpen', () => {
if (pendingTimeoutId) {
$timeout_.cancel(pendingTimeoutId);
}
pendingTimeoutId = $timeout_(() => {
pendingTimeoutId = null;
if ($scope.isOpen) {
$document_.on('click', documentClick);
} else {
$document_.off('click', documentClick);
}
}, MIN_TIMEOUT_INTERVAL);
});
$scope.$on('$destroy', () => {
$document_.off('click', documentClick);
});
/*****************************************************************************************
* The following code responds to keyboard events when the drop-down is visible
*****************************************************************************************/
$scope.mouseOver = (index:number) => {
$scope.mouseOverIndex = index;
$scope.mouseOverOption = index >= 0 ? $scope.options[index] : null;
};
// Listen to key down, not up, because ENTER key sometimes gets converted into a click event.
$scope.keyDown = (event:KeyboardEvent) => {
switch (event.keyCode) {
case 27: // Escape key
$scope.close();
break;
case 13: // Enter key
if ($scope.isOpen) {
$scope.selectOption($scope.mouseOverOption);
$scope.close();
} else {
$scope.open();
}
event.preventDefault();
break;
case 38: // Up arrow
if ($scope.isOpen) {
$scope.mouseOver( $scope.mouseOverIndex > 0 ? $scope.mouseOverIndex - 1 : $scope.options.length - 1 );
} else {
$scope.open();
}
break;
case 40: // Down arrow
if ($scope.isOpen) {
$scope.mouseOver( $scope.mouseOverIndex < $scope.options.length - 1 ? $scope.mouseOverIndex + 1 : 0 );
} else {
$scope.open();
}
break;
case 9: // Tabbing (in or out) should close the menu.
case 16:
$scope.close();
break;
default: // But all other key events should (they potentially indicate a changed type-ahead filter value).
$scope.open();
break;
}
};
}
}
angular.module('formFor').directive('selectField',
($document, $log, $timeout, FieldHelper, FormForConfiguration) => {
return new SelectFieldDirective($document, $log, $timeout, FieldHelper, FormForConfiguration);
});
} | the_stack |
namespace ts {
const _chai: typeof import("chai") = require("chai");
const expect: typeof _chai.expect = _chai.expect;
describe("unittests:: services:: languageService", () => {
const files: {[index: string]: string} = {
"foo.ts": `import Vue from "./vue";
import Component from "./vue-class-component";
import { vueTemplateHtml } from "./variables";
@Component({
template: vueTemplateHtml,
})
class Carousel<T> extends Vue {
}`,
"variables.ts": `export const vueTemplateHtml = \`<div></div>\`;`,
"vue.d.ts": `export namespace Vue { export type Config = { template: string }; }`,
"vue-class-component.d.ts": `import Vue from "./vue";
export function Component(x: Config): any;`
};
function createLanguageService() {
return ts.createLanguageService({
getCompilationSettings() {
return {};
},
getScriptFileNames() {
return ["foo.ts", "variables.ts", "vue.d.ts", "vue-class-component.d.ts"];
},
getScriptVersion(_fileName) {
return "";
},
getScriptSnapshot(fileName) {
if (fileName === ".ts") {
return ScriptSnapshot.fromString("");
}
return ScriptSnapshot.fromString(files[fileName] || "");
},
getCurrentDirectory: () => ".",
getDefaultLibFileName(options) {
return getDefaultLibFilePath(options);
},
fileExists: name => !!files[name],
readFile: name => files[name]
});
}
// Regression test for GH #18245 - bug in single line comment writer caused a debug assertion when attempting
// to write an alias to a module's default export was referrenced across files and had no default export
it("should be able to create a language service which can respond to deinition requests without throwing", () => {
const languageService = createLanguageService();
const definitions = languageService.getDefinitionAtPosition("foo.ts", 160); // 160 is the latter `vueTemplateHtml` position
expect(definitions).to.exist; // eslint-disable-line @typescript-eslint/no-unused-expressions
});
it("getEmitOutput on language service has way to force dts emit", () => {
const languageService = createLanguageService();
assert.deepEqual(
languageService.getEmitOutput(
"foo.ts",
/*emitOnlyDtsFiles*/ true
),
{
emitSkipped: true,
diagnostics: emptyArray,
outputFiles: emptyArray,
exportedModulesFromDeclarationEmit: undefined
}
);
assert.deepEqual(
languageService.getEmitOutput(
"foo.ts",
/*emitOnlyDtsFiles*/ true,
/*forceDtsEmit*/ true
),
{
emitSkipped: false,
diagnostics: emptyArray,
outputFiles: [{
name: "foo.d.ts",
text: "export {};\r\n",
writeByteOrderMark: false
}],
exportedModulesFromDeclarationEmit: undefined
}
);
});
describe("detects program upto date correctly", () => {
function verifyProgramUptoDate(useProjectVersion: boolean) {
let projectVersion = "1";
const files = new Map<string, { version: string, text: string; }>();
files.set("/project/root.ts", { version: "1", text: `import { foo } from "./other"` });
files.set("/project/other.ts", { version: "1", text: `export function foo() { }` });
files.set("/lib/lib.d.ts", { version: "1", text: projectSystem.libFile.content });
const host: LanguageServiceHost = {
useCaseSensitiveFileNames: returnTrue,
getCompilationSettings: getDefaultCompilerOptions,
fileExists: path => files.has(path),
readFile: path => files.get(path)?.text,
getProjectVersion: !useProjectVersion ? undefined : () => projectVersion,
getScriptFileNames: () => ["/project/root.ts"],
getScriptVersion: path => files.get(path)?.version || "",
getScriptSnapshot: path => {
const text = files.get(path)?.text;
return text ? ScriptSnapshot.fromString(text) : undefined;
},
getCurrentDirectory: () => "/project",
getDefaultLibFileName: () => "/lib/lib.d.ts"
};
const ls = ts.createLanguageService(host);
const program1 = ls.getProgram()!;
const program2 = ls.getProgram()!;
assert.strictEqual(program1, program2);
verifyProgramFiles(program1);
// Change other
projectVersion = "2";
files.set("/project/other.ts", { version: "2", text: `export function foo() { } export function bar() { }` });
const program3 = ls.getProgram()!;
assert.notStrictEqual(program2, program3);
verifyProgramFiles(program3);
// change root
projectVersion = "3";
files.set("/project/root.ts", { version: "2", text: `import { foo, bar } from "./other"` });
const program4 = ls.getProgram()!;
assert.notStrictEqual(program3, program4);
verifyProgramFiles(program4);
function verifyProgramFiles(program: Program) {
assert.deepEqual(
program.getSourceFiles().map(f => f.fileName),
["/lib/lib.d.ts", "/project/other.ts", "/project/root.ts"]
);
}
}
it("when host implements getProjectVersion", () => {
verifyProgramUptoDate(/*useProjectVersion*/ true);
});
it("when host does not implement getProjectVersion", () => {
verifyProgramUptoDate(/*useProjectVersion*/ false);
});
});
describe("detects program upto date when new file is added to the referenced project", () => {
function setup(useSourceOfProjectReferenceRedirect: (() => boolean) | undefined) {
const config1: TestFSWithWatch.File = {
path: `${tscWatch.projectRoot}/projects/project1/tsconfig.json`,
content: JSON.stringify({
compilerOptions: {
module: "none",
composite: true
},
exclude: ["temp"]
})
};
const class1: TestFSWithWatch.File = {
path: `${tscWatch.projectRoot}/projects/project1/class1.ts`,
content: `class class1 {}`
};
const class1Dts: TestFSWithWatch.File = {
path: `${tscWatch.projectRoot}/projects/project1/class1.d.ts`,
content: `declare class class1 {}`
};
const config2: TestFSWithWatch.File = {
path: `${tscWatch.projectRoot}/projects/project2/tsconfig.json`,
content: JSON.stringify({
compilerOptions: {
module: "none",
composite: true
},
references: [
{ path: "../project1" }
]
})
};
const class2: TestFSWithWatch.File = {
path: `${tscWatch.projectRoot}/projects/project2/class2.ts`,
content: `class class2 {}`
};
const system = projectSystem.createServerHost([config1, class1, class1Dts, config2, class2, projectSystem.libFile]);
const result = getParsedCommandLineOfConfigFile(`${tscWatch.projectRoot}/projects/project2/tsconfig.json`, /*optionsToExtend*/ undefined, {
useCaseSensitiveFileNames: true,
fileExists: path => system.fileExists(path),
readFile: path => system.readFile(path),
getCurrentDirectory: () => system.getCurrentDirectory(),
readDirectory: (path, extensions, excludes, includes, depth) => system.readDirectory(path, extensions, excludes, includes, depth),
onUnRecoverableConfigFileDiagnostic: noop,
})!;
const host: LanguageServiceHost = {
useCaseSensitiveFileNames: returnTrue,
useSourceOfProjectReferenceRedirect,
getCompilationSettings: () => result.options,
fileExists: path => system.fileExists(path),
readFile: path => system.readFile(path),
getScriptFileNames: () => result.fileNames,
getScriptVersion: path => {
const text = system.readFile(path);
return text !== undefined ? system.createHash(path) : "";
},
getScriptSnapshot: path => {
const text = system.readFile(path);
return text ? ScriptSnapshot.fromString(text) : undefined;
},
readDirectory: (path, extensions, excludes, includes, depth) => system.readDirectory(path, extensions, excludes, includes, depth),
getCurrentDirectory: () => system.getCurrentDirectory(),
getDefaultLibFileName: () => projectSystem.libFile.path,
getProjectReferences: () => result.projectReferences,
};
const ls = ts.createLanguageService(host);
return { system, ls, class1, class1Dts, class2 };
}
it("detects program upto date when new file is added to the referenced project", () => {
const { ls, system, class1, class2 } = setup(returnTrue);
assert.deepEqual(
ls.getProgram()!.getSourceFiles().map(f => f.fileName),
[projectSystem.libFile.path, class1.path, class2.path]
);
// Add new file to referenced project
const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`;
system.writeFile(class3, `class class3 {}`);
const program = ls.getProgram()!;
assert.deepEqual(
program.getSourceFiles().map(f => f.fileName),
[projectSystem.libFile.path, class1.path, class3, class2.path]
);
// Add excluded file to referenced project
system.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` });
assert.strictEqual(ls.getProgram(), program);
// Add output from new class to referenced project
system.writeFile(`${tscWatch.projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`);
assert.strictEqual(ls.getProgram(), program);
});
it("detects program upto date when new file is added to the referenced project without useSourceOfProjectReferenceRedirect", () => {
const { ls, system, class1Dts, class2 } = setup(/*useSourceOfProjectReferenceRedirect*/ undefined);
const program1 = ls.getProgram()!;
assert.deepEqual(
program1.getSourceFiles().map(f => f.fileName),
[projectSystem.libFile.path, class1Dts.path, class2.path]
);
// Add new file to referenced project
const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`;
system.writeFile(class3, `class class3 {}`);
assert.notStrictEqual(ls.getProgram(), program1);
assert.deepEqual(
ls.getProgram()!.getSourceFiles().map(f => f.fileName),
[projectSystem.libFile.path, class1Dts.path, class2.path]
);
// Add class3 output
const class3Dts = `${tscWatch.projectRoot}/projects/project1/class3.d.ts`;
system.writeFile(class3Dts, `declare class class3 {}`);
const program2 = ls.getProgram()!;
assert.deepEqual(
program2.getSourceFiles().map(f => f.fileName),
[projectSystem.libFile.path, class1Dts.path, class3Dts, class2.path]
);
// Add excluded file to referenced project
system.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` });
assert.strictEqual(ls.getProgram(), program2);
// Delete output from new class to referenced project
system.deleteFile(class3Dts);
assert.deepEqual(
ls.getProgram()!.getSourceFiles().map(f => f.fileName),
[projectSystem.libFile.path, class1Dts.path, class2.path]
);
// Write output again
system.writeFile(class3Dts, `declare class class3 {}`);
assert.deepEqual(
ls.getProgram()!.getSourceFiles().map(f => f.fileName),
[projectSystem.libFile.path, class1Dts.path, class3Dts, class2.path]
);
});
});
});
} | the_stack |
import { fabric } from 'fabric';
/**
* Edit and render videos.
*
* @param config - Config.
*/
declare function Editly(config: Editly.Config): Promise<void>;
declare namespace Editly {
/** Little utility */
type OptionalPromise<T> = Promise<T> | T;
type OriginX = 'left' | 'center' | 'right';
type OriginY = 'top' | 'center' | 'bottom';
/**
* How to fit image to screen. Can be one of:
* - `'contain'` - All the video will be contained within the frame and letterboxed.
* - `'contain-blur'` - Like contain, but with a blurred copy as the letterbox.
* - `'cover'` - Video be cropped to cover the whole screen (aspect ratio preserved).
* - `'stretch'` - Video will be stretched to cover the whole screen (aspect ratio ignored).
*
* @default 'contain-blur'
* @see [Example 'image.json5']{@link https://github.com/mifi/editly/blob/master/examples/image.json5}
* @see [Example 'videos.json5']{@link https://github.com/mifi/editly/blob/master/examples/videos.json5}
*/
type ResizeMode = 'contain' | 'contain-blur' | 'cover' | 'stretch';
/**
* An object, where `{ x: 0, y: 0 }` is the upper left corner of the screen and `{ x: 1, y: 1 }` is the lower right corner.
*/
interface PositionObject {
/**
* X-position relative to video width.
*/
x: number;
/**
* Y-position relative to video height.
*/
y: number;
/**
* X-anchor position of the object.
*/
originX?: OriginX;
/**
* Y-anchor position of the object.
*/
originY?: OriginY;
}
/**
* Certain layers support the position parameter.
*
* @see [Position parameter]{@link https://github.com/mifi/editly#position-parameter}
* @see [Example 'position.json5']{@link https://github.com/mifi/editly/blob/master/examples/position.json5}
*/
type Position =
| 'top'
| 'top-left'
| 'top-right'
| 'center'
| 'center-left'
| 'center-right'
| 'bottom'
| 'bottom-left'
| 'bottom-right'
| PositionObject;
/**
* @see [Curve types]{@link https://trac.ffmpeg.org/wiki/AfadeCurves}
*/
type CurveType =
| 'tri'
| 'qsin'
| 'hsin'
| 'esin'
| 'log'
| 'ipar'
| 'qua'
| 'cub'
| 'squ'
| 'cbr'
| 'par'
| 'exp'
| 'iqsin'
| 'ihsin'
| 'dese'
| 'desi'
| 'losi'
| 'nofade'
| string;
/**
* @see [Transition types]{@link https://github.com/mifi/editly#transition-types}
*/
type TransitionType =
| 'directional-left'
| 'directional-right'
| 'directional-up'
| 'directional-down'
| 'random'
| 'dummy'
| string;
/**
* WARNING: Undocumented feature!
*/
interface GLTextureLike {
bind: (unit: number) => number;
shape: [ number, number ];
}
/**
* WARNING: Undocumented feature!
*/
interface TransitionParams {
/**
* WARNING: Undocumented feature!
*/
[key: string]: number | boolean | GLTextureLike | number[];
}
interface Transition {
/**
* Transition duration.
*
* @default 0.5
*/
duration?: number;
/**
* Transition type.
*
* @default 'random'
* @see [Transition types]{@link https://github.com/mifi/editly#transition-types}
*/
name?: TransitionType;
/**
* [Fade out curve]{@link https://trac.ffmpeg.org/wiki/AfadeCurves} in audio cross fades.
*
* @default 'tri'
*/
audioOutCurve?: CurveType;
/**
* [Fade in curve]{@link https://trac.ffmpeg.org/wiki/AfadeCurves} in audio cross fades.
*
* @default 'tri'
*/
audioInCurve?: CurveType;
/**
* WARNING: Undocumented feature!
*/
easing?: string | null;
/**
* WARNING: Undocumented feature!
*/
params?: TransitionParams;
}
/**
* @see [Arbitrary audio tracks]{@link https://github.com/mifi/editly#arbitrary-audio-tracks}
*/
interface AudioTrack {
/**
* File path for this track.
*/
path: string;
/**
* Relative volume for this track.
*
* @default 1
*/
mixVolume?: number | string;
/**
* Time value to cut source file from (in seconds).
*
* @default 0
*/
cutFrom?: number;
/**
* Time value to cut source file to (in seconds).
*/
cutTo?: number;
/**
* How many seconds into video to start this audio track.
*
* @default 0
*/
start?: number;
}
/**
* @see [Ken Burns parameters]{@link https://github.com/mifi/editly#ken-burns-parameters}
*/
interface KenBurns {
/**
* Zoom direction for Ken Burns effect.
* Use `null` to disable.
*/
zoomDirection?: 'in' | 'out' | null;
/**
* Zoom amount for Ken Burns effect.
*
* @default 0.1
*/
zoomAmount?: number;
}
type LayerType =
| 'video'
| 'audio'
| 'detached-audio'
| 'image'
| 'image-overlay'
| 'title'
| 'subtitle'
| 'title-background'
| 'news-title'
| 'slide-in-text'
| 'fill-color'
| 'pause'
| 'radial-gradient'
| 'linear-gradient'
| 'rainbow-colors'
| 'canvas'
| 'fabric'
| 'gl'
| 'editly-banner';
interface BaseLayer {
/**
* Layer type.
*/
type: LayerType;
/**
* What time into the clip should this layer start (in seconds).
*/
start?: number;
/**
* What time into the clip should this layer stop (in seconds).
*/
stop?: number;
}
/**
* For video layers, if parent `clip.duration` is specified, the video will be slowed/sped-up to match `clip.duration`.
* If `cutFrom`/`cutTo` is set, the resulting segment (`cutTo`-`cutFrom`) will be slowed/sped-up to fit `clip.duration`.
* If the layer has audio, it will be kept (and mixed with other audio layers if present).
*/
interface VideoLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'video';
/**
* Path to video file.
*/
path: string;
/**
* How to fit video to screen.
*
* @default 'contain-blur'
* @see [Resize modes]{@link https://github.com/mifi/editly#resize-modes}
*/
resizeMode?: ResizeMode;
/**
* Time value to cut from (in seconds).
*
* @default 0
*/
cutFrom?: number;
/**
* Time value to cut to (in seconds).
* Defaults to *end of video*.
*/
cutTo?: number;
/**
* Width relative to screen width.
* Must be between 0 and 1.
*
* @default 1
*/
width?: number;
/**
* Height relative to screen height.
* Must be between 0 and 1.
*
* @default 1
*/
height?: number;
/**
* X-position relative to screen width.
* Must be between 0 and 1.
*
* @default 0
*/
left?: number;
/**
* Y-position relative to screen height.
* Must be between 0 and 1.
*
* @default 0
*/
top?: number;
/**
* X-anchor.
*
* @default 'left'
*/
originX?: OriginX;
/**
* Y-anchor.
*
* @default 'top'
*/
originY?: OriginY;
/**
* Relative volume when mixing this video's audio track with others.
*
* @default 1
*/
mixVolume?: number | string;
}
/**
* Audio layers will be mixed together.
* If `cutFrom`/`cutTo` is set, the resulting segment (`cutTo`-`cutFrom`) will be slowed/sped-up to fit `clip.duration`.
* The slow down/speed-up operation is limited to values between `0.5x` and `100x`.
*/
interface AudioLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'audio';
/**
* Path to audio file.
*/
path: string;
/**
* Time value to cut from (in seconds).
*
* @default 0
*/
cutFrom?: number;
/**
* Time value to cut to (in seconds).
* Defaults to `clip.duration`.
*/
cutTo?: number;
/**
* Relative volume when mixing this audio track with others.
*
* @default 1
*/
mixVolume?: number | string;
}
/**
* This is a special case of `audioTracks` that makes it easier to start the audio relative to clips start times,
* without having to calculate global start times.
*
* This layer has the exact same properties as [`audioTracks`]{@link https://github.com/mifi/editly#arbitrary-audio-tracks},
* except `start` time is relative to the clip's start.
*/
interface DetachedAudioLayer extends BaseLayer, AudioTrack {
/**
* Layer type.
*/
type: 'detached-audio';
}
/**
* Full screen image.
*/
interface ImageLayer extends BaseLayer, KenBurns {
/**
* Layer type.
*/
type: 'image';
/**
* Path to image file.
*/
path: string;
/**
* How to fit image to screen.
*/
resizeMode?: ResizeMode;
/**
* WARNING: Undocumented feature!
*/
duration?: number;
}
/**
* Image overlay with a custom position and size on the screen.
*/
interface ImageOverlayLayer extends BaseLayer, KenBurns {
/**
* Layer type.
*/
type: 'image-overlay';
/**
* Path to image file.
*/
path: string;
/**
* Position.
*/
position?: Position;
/**
* Width (from 0 to 1) where 1 is screen width.
*/
width?: number;
/**
* Height (from 0 to 1) where 1 is screen height.
*/
height?: number;
}
interface TitleLayer extends BaseLayer, KenBurns {
/**
* Layer type.
*/
type: 'title';
/**
* Title text to show, keep it short.
*/
text: string;
/**
* Text color.
* Defaults to '#ffffff'.
*/
textColor?: string;
/**
* Set font (`.ttf`).
* Defaults to system font.
*/
fontPath?: string;
/**
* Position.
*/
position?: Position;
}
interface SubtitleLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'subtitle';
/**
* Subtitle text to show.
*/
text: string;
/**
* Text color.
* Defaults to '#ffffff'.
*/
textColor?: string;
/**
* Set font (`.ttf`).
* Defaults to system font.
*/
fontPath?: string;
/**
* WARNING: Undocumented feature!
*/
backgroundColor?: string;
}
/**
* Title with background.
*/
interface TitleBackgroundLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'title-background';
/**
* Title text to show, keep it short.
*/
text: string;
/**
* Text color.
* Defaults to '#ffffff'.
*/
textColor?: string;
/**
* Set font (`.ttf`).
* Defaults to system font.
*/
fontPath?: string;
/**
* Background layer.
* Defaults to random background.
*/
background?: BackgroundLayer;
}
interface NewsTitleLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'news-title';
/**
* Title text to show, keep it short.
*/
text: string;
/**
* Text color.
* Defaults to '#ffffff'.
*/
textColor?: string;
/**
* Set font (`.ttf`).
* Defaults to system font.
*/
fontPath?: string;
/**
* Background color.
* Defaults to '#d02a42'.
*/
backgroundColor?: string;
/**
* Position.
*/
position?: Position;
}
interface SlideInTextLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'slide-in-text';
/**
* Title text to show, keep it short.
*/
text: string;
/**
* Set font (`.ttf`).
* Defaults to system font.
*/
fontPath?: string;
/**
* Font size.
*/
fontSize?: number;
/**
* Char spacing.
*/
charSpacing?: number;
/**
* Color.
*/
color?: string;
/**
* Position.
*/
position?: Position;
}
interface FillColorLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'fill-color';
/**
* Color to fill background.
* Defaults to random color.
*/
color?: string;
}
interface PauseLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'pause';
/**
* Color to fill background.
* Defaults to random color.
*/
color?: string;
}
interface RadialGradientLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'radial-gradient';
/**
* Array of two colors.
* Defaults to random colors.
*/
colors?: [string, string];
}
interface LinearGradientLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'linear-gradient';
/**
* Array of two colors.
* Defaults to random colors.
*/
colors?: [string, string];
}
interface RainbowColorsLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'rainbow-colors';
}
type OnRenderCallback = (progress: number, canvas: fabric.Canvas) => OptionalPromise<void>;
type OnCloseCallback = () => OptionalPromise<void>;
interface CustomFunctionCallbacks {
onRender: OnRenderCallback;
onClose?: OnCloseCallback;
}
interface CustomCanvasFunctionArgs {
width: number;
height: number;
canvas: fabric.Canvas;
}
type CustomCanvasFunction = (args: CustomCanvasFunctionArgs) => OptionalPromise<CustomFunctionCallbacks>;
interface CanvasLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'canvas';
/**
* Custom JavaScript function.
*/
func: CustomCanvasFunction;
}
interface CustomFabricFunctionArgs {
width: number;
height: number;
fabric: typeof fabric;
canvas: fabric.Canvas;
params: any;
}
type CustomFabricFunction = (args: CustomFabricFunctionArgs) => OptionalPromise<CustomFunctionCallbacks>;
interface FabricLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'fabric';
/**
* Custom JavaScript function.
*/
func: CustomFabricFunction;
}
interface GlLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'gl';
/**
* Fragment path (`.frag` file)
*/
fragmentPath: string;
/**
* Vertex path (`.vert` file).
*/
vertexPath?: string;
/**
* WARNING: Undocumented feature!
*/
speed?: number;
}
/**
* WARNING: Undocumented feature!
*/
interface EditlyBannerLayer extends BaseLayer {
/**
* Layer type.
*/
type: 'editly-banner';
}
/**
* @see [Examples]{@link https://github.com/mifi/editly/tree/master/examples}
* @see [Example 'commonFeatures.json5']{@link https://github.com/mifi/editly/blob/master/examples/commonFeatures.json5}
*/
type Layer =
| VideoLayer
| AudioLayer
| DetachedAudioLayer
| ImageLayer
| ImageOverlayLayer
| TitleLayer
| SubtitleLayer
| TitleBackgroundLayer
| NewsTitleLayer
| SlideInTextLayer
| FillColorLayer
| PauseLayer
| RadialGradientLayer
| LinearGradientLayer
| RainbowColorsLayer
| CanvasLayer
| FabricLayer
| GlLayer
| EditlyBannerLayer;
/**
* Special layers that can be used f.e. in the 'title-background' layer.
*/
type BackgroundLayer = RadialGradientLayer | LinearGradientLayer | FillColorLayer;
interface Clip {
/**
* List of layers within the current clip that will be overlaid in their natural order (final layer on top).
*/
layers: Layer[] | Layer;
/**
* Clip duration.
* If unset, the clip duration will be that of the first video layer.
* Defaults to `defaults.duration`.
*/
duration?: number;
/**
* Specify transition at the end of this clip.
* Defaults to `defaults.transition`.
* Set to `null` to disable transitions.
*/
transition?: Transition | null;
}
interface DefaultLayerOptions {
/**
* Set default font (`.ttf`).
* Defaults to system font.
*/
fontPath?: string;
/**
* Set any layer parameter that all layers will inherit.
*/
[key: string]: any;
}
type DefaultLayerTypeOptions = {
/**
* Set any layer parameter that all layers of the same type (specified in key) will inherit.
*/
[P in LayerType]?: Partial<Omit<Extract<Layer, { type: P }>, 'type'>>;
};
interface DefaultOptions {
/**
* Set default clip duration for clips that don't have an own duration (in seconds).
*
* @default 4
*/
duration?: number;
/**
* An object describing the default layer options.
*/
layer?: DefaultLayerOptions;
/**
* Defaults for each individual layer types.
*/
layerType?: DefaultLayerTypeOptions;
/**
* An object describing the default transition.
* Set to `null` to disable transitions.
*/
transition?: Transition | null;
}
/**
* You can enable audio normalization of the final output audio.
* This is useful if you want to achieve Audio Ducking (e.g. automatically lower volume of all other tracks when voice-over speaks).
*
* @see [Dynaudnorm]{@link https://ffmpeg.org/ffmpeg-filters.html#dynaudnorm}
* @see [Example of audio ducking]{@link https://github.com/mifi/editly/blob/master/examples/audio2.json5}
*/
interface AudioNormalizationOptions {
/**
* Enable audio normalization?
*
* @default false
* @see [Audio normalization]{@link https://github.com/mifi/editly#audio-normalization}
*/
enable?: boolean;
/**
* Audio normalization gauss size.
*
* @default 5
* @see [Audio normalization]{@link https://github.com/mifi/editly#audio-normalization}
*/
gaussSize?: number;
/**
* Audio normalization max gain.
*
* @default 30
* @see [Audio normalization]{@link https://github.com/mifi/editly#audio-normalization}
*/
maxGain?: number;
}
interface Config {
/**
* Output path (`.mp4` or `.mkv`, can also be a `.gif`).
*/
outPath: string;
/**
* List of clip objects that will be played in sequence.
* Each clip can have one or more layers.
*
* @default []
*/
clips: Clip[];
/**
* Width which all media will be converted to.
*
* @default 640
*/
width?: number;
/**
* Height which all media will be converted to.
* Decides height based on `width` and aspect ratio of the first video by default.
*/
height?: number;
/**
* FPS which all videos will be converted to.
* Defaults to first video's FPS or `25`.
*/
fps?: number;
/**
* Specify custom output codec/format arguments for ffmpeg.
* Automatically adds codec options (normally `h264`) by default.
*
* @see [Example]{@link https://github.com/mifi/editly/blob/master/examples/customOutputArgs.json5}
*/
customOutputArgs?: string[];
/**
* Allow remote URLs as paths.
*
* @default false
*/
allowRemoteRequests?: boolean;
/**
* Fast mode (low resolution and FPS, useful for getting a quick preview ⏩).
*
* @default false
*/
fast?: boolean;
/**
* An object describing default options for clips and layers.
*/
defaults?: DefaultOptions;
/**
* List of arbitrary audio tracks.
*
* @default []
* @see [Audio tracks]{@link https://github.com/mifi/editly#arbitrary-audio-tracks}
*/
audioTracks?: AudioTrack[];
/**
* Set an audio track for the whole video..
*
* @see [Audio tracks]{@link https://github.com/mifi/editly#arbitrary-audio-tracks}
*/
audioFilePath?: string;
/**
* Loop the audio track if it is shorter than video?
*
* @default false
*/
loopAudio?: boolean;
/**
* Keep source audio from `clips`?
*
* @default false
*/
keepSourceAudio?: boolean;
/**
* Volume of audio from `clips` relative to `audioTracks`.
*
* @default 1
* @see [Audio tracks]{@link https://github.com/mifi/editly#arbitrary-audio-tracks}
*/
clipsAudioVolume?: number | string;
/**
* Adjust output [volume]{@link http://ffmpeg.org/ffmpeg-filters.html#volume} (final stage).
*
* @default 1
* @see [Example]{@link https://github.com/mifi/editly/blob/master/examples/audio-volume.json5}
* @example
* 0.5
* @example
* '10db'
*/
outputVolume?: number | string;
/**
* Audio normalization.
*/
audioNorm?: AudioNormalizationOptions;
/**
* WARNING: Undocumented feature!
*/
ffmpegPath?: string;
/**
* WARNING: Undocumented feature!
*/
ffprobePath?: string;
/**
* WARNING: Undocumented feature!
*/
enableFfmpegLog?: boolean;
/**
* WARNING: Undocumented feature!
*/
verbose?: boolean;
/**
* WARNING: Undocumented feature!
*/
logTimes?: boolean;
/**
* WARNING: Undocumented feature!
*/
keepTmp?: boolean;
}
interface RenderSingleFrameConfig extends Omit<Config, 'outPath'> {
/**
* Output path (`.mp4` or `.mkv`, can also be a `.gif`).
*/
outPath?: string;
/**
* Timestamp to render.
*/
time?: number;
}
/**
* WARNING: Undocumented feature!
* Pure function to get a frame at a certain time.
*
* @param config - Config.
*/
function renderSingleFrame(config: RenderSingleFrameConfig): Promise<void>;
}
export = Editly; | the_stack |
import React, { ReactNode } from 'react';
/* eslint-enable */
import { compose, withState, withProps } from 'recompose';
import {
map, groupBy, reduce, filter, some,
} from 'lodash';
import { Row, Column } from '@ncigdc/uikit/Flex';
import Button from '@ncigdc/uikit/Button';
import { visualizingButton } from '@ncigdc/theme/mixins';
import ControlEditableRow from '@ncigdc/uikit/ControlEditableRow';
const styles = {
button: {
...visualizingButton,
minWidth: 100,
},
horizonalPadding: {
paddingLeft: 20,
paddingRight: 20,
},
};
const initialName = (arr: string[], prefix: string) => {
/* @arr is the list of names
@ prefix is the prefix for the name
This function is to generate initial name for new file/list/element name.
e.g: if the arr is["new name 1", "new name 3", "apple", "banana"], prefix is "new name ".
Then the return value will be "new name 2".
*/
const numberSet = new Set(arr);
for (let i = 1; i <= arr.length + 1; i += 1) {
if (!numberSet.has(prefix + i)) {
return prefix + i;
}
}
return prefix + arr.length + 1;
};
// type TOption = {
// name: string,
// };
interface IBinProps {
key: string,
/* eslint-disable */
doc_count: number,
/* eslint-enable */
groupName: string,
}
interface ISelectedBinsProps {
[x: string]: boolean
}
interface IBinsProps { [x: string]: IBinProps }
interface IGroupValuesModalProps {
binGrouping: () => void,
currentBins: IBinsProps,
dataBuckets: IBinProps[],
setCurrentBins: (currentBins: IBinsProps) => void,
onUpdate: (bins: IBinsProps) => void,
onClose: () => void,
fieldName: string,
selectedHidingBins: ISelectedBinsProps,
setSelectedHidingBins: (selectedHidingBins: ISelectedBinsProps) => void,
selectedGroupBins: ISelectedBinsProps,
setSelectedGroupBins: (selectedGroupBins: ISelectedBinsProps) => void,
editingGroupName: string,
setEditingGroupName: (editingGroupName: string) => void,
children?: ReactNode,
globalWarning: string,
setGlobalWarning: (globalWarning: string) => void,
setListWarning: (listWarning: { [x: string]: string }) => void,
listWarning: { [x: string]: string },
}
const blockStyle = {
height: '500px',
margin: '20px',
padding: '20px',
width: '40%',
};
const listStyle = {
borderRadius: '2px',
borderStyle: 'inset',
borderWidth: '2px',
height: '100%',
overflow: 'scroll',
};
const buttonStyle = {
float: 'right',
margin: '10px 2px 10px 3px',
};
export default compose(
withState('editingGroupName', 'setEditingGroupName', ''),
withState('currentBins', 'setCurrentBins', ({ bins }: { bins: IBinsProps }) => bins),
withState('selectedHidingBins', 'setSelectedHidingBins', {}),
withState('selectedGroupBins', 'setSelectedGroupBins', {}),
withState('globalWarning', 'setGlobalWarning', ''),
withState('listWarning', 'setListWarning', {}),
withProps(({
currentBins,
selectedGroupBins,
setCurrentBins,
setEditingGroupName,
setSelectedHidingBins,
}) => ({
binGrouping: () => {
const newGroupName = initialName(
Object.values(currentBins).map((bin: IBinProps) => bin.groupName), 'selected Value '
);
setEditingGroupName(newGroupName);
setCurrentBins({
...currentBins,
...reduce(selectedGroupBins, (acc, val, key) => {
if (val) {
return {
...acc,
[key]: {
...currentBins[key],
groupName: newGroupName,
},
};
}
return acc;
}, {}),
});
setSelectedHidingBins({});
},
}))
)(
({
binGrouping,
currentBins,
dataBuckets,
editingGroupName,
fieldName,
globalWarning,
listWarning,
onClose,
onUpdate,
selectedGroupBins,
selectedHidingBins,
setCurrentBins,
setGlobalWarning,
setListWarning,
setSelectedGroupBins,
setSelectedHidingBins,
}: IGroupValuesModalProps) => {
const groupNameMapping = groupBy(
Object.keys(currentBins)
.filter((bin: string) => currentBins[bin].groupName !== ''),
key => currentBins[key].groupName
);
return (
<Column>
<h1 style={{ margin: '20px' }}>
Create Custom Bins:
{' '}
{fieldName}
</h1>
<h3 style={{ margin: '20px' }}>
Organize values into groups of your choosing. Click Save Bins to udpate
the analysis plots.
</h3>
<Row style={{ justifyContent: 'center' }}>
<Column style={blockStyle}>
<Row style={{ justifyContent: 'space-between' }}>
<div style={{
alignItems: 'flex-end',
display: 'flex',
height: '54px',
}}
>
Hidden Values
</div>
</Row>
<Column style={listStyle}>
{Object.keys(currentBins)
.filter((binKey: string) => currentBins[binKey].groupName === '')
.map((binKey: string) => (
<Row
key={binKey}
onClick={() => {
if (Object.keys(selectedGroupBins).length > 0) {
setSelectedGroupBins({});
}
setSelectedHidingBins({
...selectedHidingBins,
[binKey]: !selectedHidingBins[binKey],
});
}}
style={{
backgroundColor: selectedHidingBins[binKey] ? '#d5f4e6' : '',
paddingLeft: '10px',
}}
>
{`${binKey} (${currentBins[binKey].doc_count})`}
</Row>
))}
</Column>
</Column>
<Column style={{ justifyContent: 'center' }} >
<Button
disabled={Object.values(selectedHidingBins).every(value => !value)}
onClick={() => {
setCurrentBins({
...currentBins,
...reduce(selectedHidingBins, (acc, val, key) => {
if (val) {
return {
...acc,
[key]: {
...currentBins[key],
groupName: key,
},
};
}
return acc;
}, {}),
});
setSelectedHidingBins({});
setGlobalWarning('');
setListWarning({});
}}
style={{ margin: '10px' }}
>
{'>>'}
</Button>
<Button
disabled={Object.values(selectedGroupBins).every(value => !value)}
onClick={() => {
if (filter(selectedGroupBins, Boolean).length ===
Object.keys(filter(currentBins, (bin: IBinProps) => !!bin.groupName)).length) {
setGlobalWarning('Leave at least one bin.');
return;
}
setCurrentBins({
...currentBins,
...reduce(selectedGroupBins, (acc, val, key) => {
if (val) {
return {
...acc,
[key]: {
...currentBins[key],
groupName: '',
},
};
}
return acc;
}, {}),
});
setSelectedGroupBins({});
setGlobalWarning('');
setListWarning({});
}}
style={{ margin: '10px' }}
>
{'<<'}
</Button>
</Column>
<Column style={blockStyle}>
<Row style={{ justifyContent: 'space-between' }}>
<span style={{
alignItems: 'flex-end',
display: 'flex',
}}
>
Displayed Values
</span>
<Row>
<Button
onClick={() => {
setCurrentBins({
...dataBuckets.reduce((acc, r) => ({
...acc,
[r.key]: {
...r,
groupName: r.key,
},
}), {}),
});
setSelectedGroupBins({});
setGlobalWarning('');
setListWarning({});
}}
style={buttonStyle}
>
{'Reset'}
</Button>
<Button
disabled={Object
.keys(selectedGroupBins)
.filter(key => selectedGroupBins[key])
.every(key => currentBins[key].groupName === key)}
onClick={() => {
setCurrentBins({
...currentBins,
...reduce(selectedGroupBins, (acc, val, key) => {
if (val) {
return {
...acc,
[key]: {
...currentBins[key],
groupName: key,
},
};
}
return acc;
}, {}),
});
setSelectedGroupBins({});
setGlobalWarning('');
setListWarning({});
}}
style={buttonStyle}
>
{'Ungroup'}
</Button>
<Button
disabled={Object.values(selectedGroupBins).filter(Boolean).length < 2}
onClick={() => {
binGrouping();
setSelectedGroupBins({});
setGlobalWarning('');
setListWarning({});
}}
style={buttonStyle}
>
{'Group'}
</Button>
</Row>
</Row>
<Column style={listStyle}>
{map(
groupNameMapping,
(group: string[], groupName: string) => (
<Column key={groupName}>
<Row
key={groupName}
onClick={() => {
if (Object.keys(selectedHidingBins).length > 0) {
setSelectedHidingBins({});
}
setSelectedGroupBins({
...selectedGroupBins,
...group.reduce((acc: ISelectedBinsProps, binKey: string) => ({
...acc,
[binKey]: !group.every(
(binsWithSameGroupNameKey: string) => selectedGroupBins[binsWithSameGroupNameKey]
),
}), {}),
});
}}
style={{
backgroundColor: group.every((binKey: string) => selectedGroupBins[binKey]) ? '#d5f4e6' : '',
}}
>
{group.length > 1 || group[0] !== groupName
? (
<ControlEditableRow
cleanWarning={() => setListWarning({})}
containerStyle={{
justifyContent: 'flex-start',
}}
disableOnKeyDown={listWarning[groupName]}
handleSave={(value: string) => {
if (listWarning[groupName]) {
return 'unsave';
}
setCurrentBins({
...currentBins,
...group.reduce((acc: ISelectedBinsProps, bin: string) => ({
...acc,
[bin]: {
...currentBins[bin],
groupName: value,
},
}), {}),
});
setGlobalWarning('');
setListWarning({});
setSelectedGroupBins({});
return null;
}
}
iconStyle={{
cursor: 'pointer',
fontSize: '1.8rem',
marginLeft: 10,
}}
isEditing={editingGroupName === groupName}
noEditingStyle={{ fontWeight: 'bold' }}
onEdit={(value: string) => {
if (value.trim() === '') {
setListWarning({
...listWarning,
[groupName]: 'Can not be empty.',
});
} else if (
some(currentBins,
(bin: IBinProps) => bin.groupName.trim() === value.trim()) &&
groupName.trim() !== value.trim()
) {
setListWarning({
...listWarning,
[groupName]: `"${value.trim()}" already exists.`,
});
} else if (group.includes(value)) {
setListWarning({
...listWarning,
[groupName]: 'Group name can\'t be the same as one of values.',
});
} else {
setListWarning({});
}
}}
text={groupName}
warning={listWarning[groupName]}
>
{groupName}
</ControlEditableRow>
) : (
<div style={{ fontWeight: 'bold' }}>
{`${currentBins[group[0]].key} (${currentBins[group[0]].doc_count})`}
</div>
)
}
</Row>
{
group.length > 1 || group[0] !== groupName
? group.map((bin: string) => (
<Row
key={bin}
onClick={() => {
setSelectedGroupBins({
...selectedGroupBins,
[bin]: !selectedGroupBins[bin],
});
}
}
style={{
backgroundColor: selectedGroupBins[bin] ? '#d5f4e6' : '',
display: 'list-item',
listStylePosition: 'inside',
listStyleType: 'disc',
paddingLeft: '5px',
}}
>
{`${bin} (${currentBins[bin].doc_count})`}
</Row>
))
: null
}
</Column>
)
)}
</Column>
</Column>
</Row>
<Row
spacing="1rem"
style={{
justifyContent: 'flex-end',
margin: '20px',
}}
>
{globalWarning.length > 0 ? (
<span style={{
color: 'red',
justifyContent: 'flex-start',
}}
>
{'Warning: '}
{globalWarning}
</span>
) : null}
<Button
onClick={onClose}
style={styles.button}
>
Cancel
</Button>
<Button
onClick={() => onUpdate(currentBins)}
style={styles.button}
>
Save Bins
</Button>
</Row>
</Column >
);
}
); | the_stack |
import {Debugger} from '../common/debugger';
import {Engine} from '../common/engine';
import {SemanticAttr, SemanticRole, SemanticType} from './semantic_attr';
import {SemanticNode} from './semantic_node';
import {SemanticNodeFactory} from './semantic_node_factory';
import * as SemanticPred from './semantic_pred';
import SemanticProcessor from './semantic_processor';
import * as SemanticUtil from './semantic_util';
declare type SemanticHeuristicTypes = SemanticNode | SemanticNode[];
export namespace SemanticHeuristics {
export let factory: SemanticNodeFactory = null;
export const heuristics: Map<string, SemanticHeuristic<SemanticHeuristicTypes>> =
new Map();
/**
* Heuristics that are run by default.
*/
export const flags: {[key: string]: boolean} = {
combine_juxtaposition: true,
convert_juxtaposition: true,
multioperator: true
};
/**
* Heuristics that are permanently switched off.
*/
export const blacklist: {[key: string]: boolean} = {};
/**
* Register a heuristic with the handler.
* @param name The name of the heuristic.
* @param heuristic The heuristic.
*/
export function add(name: string, heuristic:
SemanticHeuristic<SemanticHeuristicTypes>) {
heuristics.set(name, heuristic);
// Registered switched off, unless it is set by default.
if (!flags[name]) {
flags[name] = false;
}
}
/**
* Runs a heuristic if its predicate evaluates to true.
* @param name The name of the heuristic.
* @param root The root node of the subtree.
* @param opt_alternative An
* optional method to run if the heuristic is not applicable.
* @return The resulting subtree.
*/
export function run(
name: string, root: SemanticHeuristicTypes,
opt_alternative?: (p1: SemanticHeuristicTypes) => SemanticHeuristicTypes):
SemanticHeuristicTypes | void {
let heuristic = SemanticHeuristics.lookup(name);
return heuristic && !blacklist[name] &&
(flags[name] ||
heuristic.applicable(root)) ?
heuristic.apply(root) :
opt_alternative ? opt_alternative(root) : root;
}
// /**
// * Runs a multi heuristic if its predicate evaluates to true.
// * @param name The name of the heuristic.
// * @param root The list of root nodes.
// * @param opt_alternative An optional method to run if the heuristic is not
// * applicable.
// * @return The resulting subtree.
// */
// export function runMulti(
// name: string, root: SemanticNode[],
// opt_alternative?: (p1: SemanticNode[]) => SemanticNode[]):
// SemanticNode[] {
// let heuristic = SemanticHeuristics.lookup(name);
// return heuristic &&
// (flags[name] ||
// heuristic.applicable(root)) ?
// heuristic.apply(root) :
// opt_alternative ? opt_alternative(root) : root;
// }
/**
* Looks up the named heuristic.
* @param name The name of the heuristic.
* @return The heuristic.
*/
export function lookup(name: string): SemanticHeuristic<SemanticHeuristicTypes> {
return heuristics.get(name);
}
}
// TODO: Heuristic paths have to be included in the tests.
/**
* All heuristic methods get a method to manipulate nodes and have a predicate
* that either switches them on automatically (e.g., on selection of a domain),
* or they can be switched on manually via a flag. Currently these flags are
* hard coded.
*/
export interface SemanticHeuristic<T> {
name: string;
apply: (node: T) => void;
applicable: (node: T) => boolean;
}
export abstract class SemanticAbstractHeuristic<T extends SemanticHeuristicTypes> implements SemanticHeuristic<T> {
public apply: (node: T) => void;
public applicable: (_node: T) => boolean;
/**
* Abstract class of heuristics.
* @param {{predicate: ((function(T): boolean)|undefined),
* method: function(T): sre.SemanticNode} } heuristic The predicate and
* method of the heuristic
*/
constructor(public name: string, method: (node: T) => void,
predicate: (node: T) => boolean = (_x: T) => false) {
this.apply = method;
this.applicable = predicate;
SemanticHeuristics.add(name, this);
}
}
/**
* Heuristics work on the root of a subtree.
* @override
*/
export class SemanticTreeHeuristic extends SemanticAbstractHeuristic<SemanticNode> {}
/**
* Heuristics work on a list of nodes.
* @override
*/
export class SemanticMultiHeuristic extends SemanticAbstractHeuristic<SemanticNode[]> {}
/**
* Recursively combines implicit nodes as much as possible for the given root
* node of a subtree.
*/
new SemanticTreeHeuristic('combine_juxtaposition', combineJuxtaposition);
function combineJuxtaposition(root: SemanticNode) {
for (let i = root.childNodes.length - 1, child;
child = root.childNodes[i]; i--) {
if (!SemanticPred.isImplicitOp(child) || child.nobreaking) {
continue;
}
// TODO (TS): Cleanup those any types.
root.childNodes.splice.apply(
root.childNodes, [i, 1].concat(child.childNodes as any));
root.contentNodes.splice.apply(
root.contentNodes, [i, 0].concat(child.contentNodes as any));
child.childNodes.concat(child.contentNodes).forEach(function(x) {
x.parent = root;
});
root.addMathmlNodes(child.mathml);
}
return root;
}
/**
* Finds composed functions, i.e., simple functions that are either composed
* with an infix operation or fraction and rewrites their role accordingly.
* Currently restricted to Clearspeak!
*/
new SemanticTreeHeuristic(
'propagateSimpleFunction',
(node) => {
if ((node.type === SemanticType.INFIXOP ||
node.type === SemanticType.FRACTION) &&
node.childNodes.every(SemanticPred.isSimpleFunction)) {
node.role = SemanticRole.COMPFUNC;
}
return node;
},
(_node) => Engine.getInstance().domain === 'clearspeak'
);
/**
* Naive name based heuristic for identifying simple functions. This is used in
* clearspeak only.
*/
new SemanticTreeHeuristic(
'simpleNamedFunction',
(node) => {
let specialFunctions = ['f', 'g', 'h', 'F', 'G', 'H'];
if (node.role !== SemanticRole.UNIT &&
specialFunctions.indexOf(node.textContent) !== -1) {
node.role = SemanticRole.SIMPLEFUNC;
}
return node;
},
(_node) => Engine.getInstance().domain === 'clearspeak'
);
/**
* Propagates the role of composed function to surrounding fences.
* Currently restricted to Clearspeak!
*/
new SemanticTreeHeuristic(
'propagateComposedFunction',
(node) => {
if (node.type === SemanticType.FENCED &&
node.childNodes[0].role === SemanticRole.COMPFUNC) {
node.role = SemanticRole.COMPFUNC;
}
return node;
},
(_node) => Engine.getInstance().domain === 'clearspeak'
);
/**
* Heuristic to compute a meaningful role for multi character operators (e.g.,
* as in a++). If all operators have the same role (ignoring unknown) that role
* is used.
*/
new SemanticTreeHeuristic(
'multioperator',
(node) => {
if (node.role !== SemanticRole.UNKNOWN ||
node.textContent.length <= 1) {
return;
}
// TODO: Combine with lines in numberRole_/exprFont_?
let content = SemanticUtil.splitUnicode(node.textContent);
let meaning = content.map(SemanticAttr.lookupMeaning);
let singleRole = meaning.reduce(function(prev, curr) {
if (!prev || !curr.role || curr.role === SemanticRole.UNKNOWN ||
curr.role === prev) {
return prev;
}
if (prev === SemanticRole.UNKNOWN) {
return curr.role;
}
return null;
}, SemanticRole.UNKNOWN);
if (singleRole) {
node.role = singleRole;
}
}
);
/**
* Combines explicitly given juxtapositions.
*/
new SemanticMultiHeuristic(
'convert_juxtaposition',
(nodes) => {
let partition = SemanticUtil.partitionNodes(nodes, function(x) {
return x.textContent === SemanticAttr.invisibleTimes() &&
x.type === SemanticType.OPERATOR;
});
// Preprocessing pre and postfixes.
partition = partition.rel.length ?
juxtapositionPrePost(partition) :
partition;
// TODO: Move to Util
nodes = partition.comp[0];
for (let i = 1, c, r; c = partition.comp[i], r = partition.rel[i - 1];
i++) {
nodes.push(r);
nodes = nodes.concat(c);
}
partition = SemanticUtil.partitionNodes(nodes, function(x) {
return x.textContent === SemanticAttr.invisibleTimes() &&
(x.type === SemanticType.OPERATOR ||
x.type === SemanticType.INFIXOP);
});
if (!partition.rel.length) {
return nodes;
}
return recurseJuxtaposition(
partition.comp.shift(), partition.rel, partition.comp);
}
);
/**
* Rewrites a simple function to a prefix function if it consists of multiple
* letters. (Currently restricted to Braille!)
*/
new SemanticTreeHeuristic(
'simple2prefix',
(node) => {
if (node.textContent.length > 1 &&
// TODO: Discuss this line!
!node.textContent[0].match(/[A-Z]/)) {
node.role = SemanticRole.PREFIXFUNC;
}
return node;
},
(node) => Engine.getInstance().modality === 'braille' &&
node.type === SemanticType.IDENTIFIER
);
/**
* Rewrites space separated lists of numbers into of cycles.
* (Currently only used in Nemeth.)
*/
new SemanticTreeHeuristic(
'detect_cycle',
(node) => {
// TODO: Test for simple elements?
node.type = SemanticType.MATRIX;
node.role = SemanticRole.CYCLE;
let row = node.childNodes[0];
row.type = SemanticType.ROW;
row.role = SemanticRole.CYCLE;
row.contentNodes = [];
return node;
},
(node) => Engine.getInstance().modality === 'braille' &&
node.type === SemanticType.FENCED &&
node.childNodes[0].type === SemanticType.INFIXOP &&
node.childNodes[0].role === SemanticRole.IMPLICIT &&
node.childNodes[0].childNodes.every(function(x) {
return x.type === SemanticType.NUMBER;
}) &&
node.childNodes[0].contentNodes.every(function(x) {
return x.role === SemanticRole.SPACE;
})
);
/**
* Rewrites a partition with respect to explicit juxtapositions into one where
* all multiple operators are combined to post or prefix operators.
* @param partition The partition wrt. invisible
* times.
* @return The partition with collated pre/postfix
* operators.
*/
function juxtapositionPrePost(partition: SemanticUtil.Partition):
SemanticUtil.Partition {
let rels = [];
let comps = [];
let next = partition.comp.shift();
let rel = null;
let collect = [];
while (partition.comp.length) {
collect = [];
if (next.length) {
if (rel) {
rels.push(rel);
}
comps.push(next);
rel = partition.rel.shift();
next = partition.comp.shift();
continue;
}
if (rel) {
collect.push(rel);
}
while (!next.length && partition.comp.length) {
next = partition.comp.shift();
collect.push(partition.rel.shift());
}
rel = convertPrePost(collect, next, comps);
}
if (!collect.length && !next.length) {
// A trailing rest exists that needs to be rewritten.
collect.push(rel);
convertPrePost(collect, next, comps);
} else {
rels.push(rel);
comps.push(next);
}
return {rel: rels, comp: comps};
}
/**
* Converts lists of invisible times operators into pre/postfix operatiors.
* @param collect The collected list of invisible
* times.
* @param next The next component element.
* @param comps The previous components.
* @return The operator that needs to be taken care of.
*/
function convertPrePost(
collect: SemanticNode[], next: SemanticNode[],
comps: SemanticNode[][]): SemanticNode|null {
let rel = null;
if (!collect.length) {
return rel;
}
let prev = comps[comps.length - 1];
let prevExists = prev && prev.length;
let nextExists = next && next.length;
let processor = SemanticProcessor.getInstance();
if (prevExists && nextExists) {
if (next[0].type === SemanticType.INFIXOP &&
next[0].role === SemanticRole.IMPLICIT) {
rel = collect.pop();
prev.push(processor['postfixNode_'](prev.pop(), collect));
return rel;
}
rel = collect.shift();
let result = processor['prefixNode_'](next.shift(), collect);
next.unshift(result);
// next.unshift(processor['prefixNode_'](next.shift(), collect));
return rel;
}
if (prevExists) {
prev.push(processor['postfixNode_'](prev.pop(), collect));
return rel;
}
if (nextExists) {
next.unshift(processor['prefixNode_'](next.shift(), collect));
}
return rel;
}
/**
* Heuristic to recursively combines a list of juxtaposition elements
* expressions. Note that the heuristic assumes that all multiple occurrences
* of invisible times elements are processed. So all we have here are single
* operators or infix operators of role implicit.
*
* @param acc Elements to the left of the first
* implicit operation or application of an implicit operation. This serves
* as an accumulator during the recursion.
* @param ops The list of juxtaposition operators
* or applications. That is, subtrees that are infix operations with
* inivisible times.
* @param elements The list of elements
* between the operators in ops. These are lists of not yet combined
* elements.
* @return The resulting lists where implicit and
* explicitly given invisible times are combined as much as possible.
*/
function recurseJuxtaposition(
acc: SemanticNode[], ops: SemanticNode[],
elements: SemanticNode[][]): SemanticNode[] {
if (!ops.length) {
return acc;
}
let left = acc.pop();
let op = ops.shift();
let first = elements.shift();
if (SemanticPred.isImplicitOp(op)) {
Debugger.getInstance().output('Juxta Heuristic Case 2');
// In case we have a tree as operator, move on.
let right = (left ? [left, op] : [op]).concat(first);
return recurseJuxtaposition(
acc.concat(right), ops, elements);
}
if (!left) {
Debugger.getInstance().output('Juxta Heuristic Case 3');
return recurseJuxtaposition(
[op].concat(first), ops, elements);
}
let right = first.shift();
if (!right) {
Debugger.getInstance().output('Juxta Heuristic Case 9');
// Attach to the next operator, which must be an infix operation, As there
// are no more double operators. Left also exists. Cases that left is an
// implicit infix or simple.
let newOp = SemanticHeuristics.factory.makeBranchNode(
SemanticType.INFIXOP, [left, ops.shift()], [op], op.textContent);
newOp.role = SemanticRole.IMPLICIT;
SemanticHeuristics.run('combine_juxtaposition', newOp);
ops.unshift(newOp);
return recurseJuxtaposition(acc, ops, elements);
}
if (SemanticPred.isOperator(left) || SemanticPred.isOperator(right)) {
Debugger.getInstance().output('Juxta Heuristic Case 4');
return recurseJuxtaposition(
acc.concat([left, op, right]).concat(first), ops, elements);
}
let result = null;
if (SemanticPred.isImplicitOp(left) && SemanticPred.isImplicitOp(right)) {
// Merge both left and right.
Debugger.getInstance().output('Juxta Heuristic Case 5');
left.contentNodes.push(op);
left.contentNodes = left.contentNodes.concat(right.contentNodes);
left.childNodes.push(right);
left.childNodes = left.childNodes.concat(right.childNodes);
right.childNodes.forEach(x => x.parent = left);
op.parent = left;
left.addMathmlNodes(op.mathml);
left.addMathmlNodes(right.mathml);
result = left;
} else if (SemanticPred.isImplicitOp(left)) {
// Add to the left one.
Debugger.getInstance().output('Juxta Heuristic Case 6');
left.contentNodes.push(op);
left.childNodes.push(right);
right.parent = left;
op.parent = left;
left.addMathmlNodes(op.mathml);
left.addMathmlNodes(right.mathml);
result = left;
} else if (SemanticPred.isImplicitOp(right)) {
// Add to the right one.
Debugger.getInstance().output('Juxta Heuristic Case 7');
right.contentNodes.unshift(op);
right.childNodes.unshift(left);
left.parent = right;
op.parent = right;
right.addMathmlNodes(op.mathml);
right.addMathmlNodes(left.mathml);
result = right;
} else {
// Create new implicit node.
Debugger.getInstance().output('Juxta Heuristic Case 8');
result = SemanticHeuristics.factory.makeBranchNode(
SemanticType.INFIXOP, [left, right], [op], op.textContent);
result.role = SemanticRole.IMPLICIT;
}
acc.push(result);
return recurseJuxtaposition(
acc.concat(first), ops, elements);
} | the_stack |
import type * as types from "../types.ts";
const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
/**
* Split line breaks
*
* @param text
* @returns
*/
export const splitLines = (text: string): string[] => text.split("\n");
/**
* Format a block description line
*
* @param line
* @param indent
* @returns
*/
export const formatBlockCommentLine = (line: string, indent = 0) =>
`${" ".repeat(indent > 0 ? indent : 0)}* ${line}`;
/**
* Make a block description
*
* @param text
* @param indent
* @returns
*/
export const makeBlockComment = (text: string, indent = 0): string => {
return `${"".repeat(indent > 1 ? indent - 1 : 0)}/**\n${
splitLines(text).map((line) => formatBlockCommentLine(line, indent + 1))
.join("\n")
}\n${" ".repeat(indent + 1)}*/`;
};
export const formatKeywordComment = (
keyword: types.KeywordSchema,
): string | undefined => {
const comment: string[] = [];
const tags: string[] = [];
if (keyword.description !== undefined) {
comment.push(keyword.description);
}
// `default` is the only one out of alphabetical order since editors like
// VS Code display it differently.
if ("default" in keyword && keyword.default !== undefined) {
const { default: def } = keyword;
tags.push(
`@default ${typeof def === "string" ? `"${def}"` : def.toString()}`,
);
}
if ("const" in keyword && keyword.const !== undefined) {
const { const: value } = keyword;
tags.push(
`@const ${typeof value === "string" ? `"${value}"` : value.toString()}`,
);
}
if ("deprecated" in keyword && keyword.deprecated !== undefined) {
tags.push(
`@deprecated ${keyword.deprecated.toString()}`,
);
}
// `enum` is not needed -- the values will display as a TypeScript union
if ("exclusiveMinimum" in keyword && keyword.exclusiveMinimum !== undefined) {
tags.push(
`@exclusiveMinimum ${keyword.exclusiveMinimum.toString()}`,
);
}
if ("format" in keyword && keyword.format !== undefined) {
tags.push(
`@format "${keyword.format.toString()}"`,
);
}
if ("minimum" in keyword && keyword.minimum !== undefined) {
tags.push(
`@minimum ${keyword.minimum.toString()}`,
);
}
if (tags.length > 0) {
comment.push("\n\n", ...tags);
}
if (comment.length === 0) {
return;
}
return comment.join("\n");
};
export const stringifyKeyword = (keyword: types.KeywordSchema): string => {
if ("type" in keyword) {
switch (keyword.type) {
case "string": {
if (keyword.enum !== undefined) {
return stringifyArrayToUnion(keyword.enum);
}
return "string";
}
case "JSONSchema":
return "JSONSchema";
case "JSONSchema<Narrowable>":
return "JSONSchema<Value, SchemaType>";
case "Value":
return "Value";
case "array":
return `MaybeReadonlyArray<${
Array.isArray(keyword.items)
? keyword.items.map((item) => stringifyKeyword(item))
: stringifyKeyword(keyword.items)
}>`;
case "object": {
if (keyword.additionalProperties !== undefined) {
return `Record<string, ${
stringifyKeyword(keyword.additionalProperties)
}>`;
}
throw new TypeError("Unexpected object without `additionalProperties`");
}
case "boolean":
case "null":
return keyword.type;
case "integer":
case "number":
return "number";
default:
console.log(keyword);
throw new TypeError("Unexpected keyword schema");
}
}
if ("oneOf" in keyword) {
return keyword.oneOf.map(stringifyKeyword).join(" | ");
}
if ("anyOf" in keyword) {
return keyword.anyOf.map(stringifyKeyword).join(" | ");
}
throw new TypeError("Unexpected keyword schema");
};
export const stringifyArray = (
values: readonly string[],
): string => {
return `\n${values.map((value) => `"${value}",`).join("\n")}`;
};
export const stringifyArrayToUnion = (
values: readonly string[],
indent = 0,
): string => {
return `\n${
values.map((value) => `${" ".repeat(indent)}| "${value}"`).join("\n")
}`;
};
export const assertCodeDoesNotHavePlaceholder = (
filename: string,
sourceCode: string,
): void => {
if (sourceCode.includes("PLACEHOLDER") === false) {
return;
}
console.error(
`Placeholder is still present when generating "${filename}".`,
"Refusing to proceed.",
);
const placeHolderIndex = sourceCode.indexOf("PLACEHOLDER");
const indexStart = placeHolderIndex - 250;
console.log(
sourceCode.slice(indexStart > 0 ? indexStart : 0, indexStart + 500),
);
Deno.exit();
};
export const expandSourcePlaceholders = (
filename: string,
rawSourceCode: string,
draftSpec: types.ValidationSpecDefinition,
) => {
const sourceCode = rawSourceCode.includes("// __BEGIN__")
? rawSourceCode.split("// __BEGIN__")[1]
: rawSourceCode;
const draftIdNoLeadingZero = draftSpec.$draft.replace(/^0/, "");
const typeNames = Object.values(draftSpec.enums.typeName.values).map((
value,
) => value.value);
const newCode = splitLines(sourceCode.trim())
.filter((line) => {
const trimmedLine = line.trim();
return trimmedLine.includes("// @ts-expect-error") === false;
})
.map((line) => {
if (line.includes("* __PLACEHOLDER:KEYWORD_COMMENT:")) {
const indent = line.length - line.trimStart().length;
const keyword = line.split(`* __PLACEHOLDER:KEYWORD_COMMENT:`)[1]
.trim().slice(0, -2) as keyof typeof draftSpec.keywords;
if (keyword in draftSpec.keywords) {
const keywordSchema = draftSpec.keywords[keyword];
const keywordComment = formatKeywordComment(
keywordSchema as types.KeywordSchema,
);
if (keywordComment !== undefined) {
return splitLines(keywordComment).map((
descriptionLine,
) => formatBlockCommentLine(descriptionLine, indent)).join("\n");
}
// throw new TypeError("TODO")
return "";
}
}
return line;
})
.join("\n")
.replace(
"// __PLACEHOLDER:LICENSE__",
makeBlockComment(
draftSpec.$license,
).replace("/**", "/*"),
)
.replace(
`// __PLACEHOLDER:TYPES_IMPORT__`,
`import { type JSONSchema } from "./types.ts";`,
)
.replaceAll(/(__|\*\*)PLACEHOLDER\:DRAFT(__|\*\*)/g, draftSpec.$draft)
.replaceAll(
/(__|\*\*)PLACEHOLDER\:DRAFT(__|\*\*)/g,
draftIdNoLeadingZero,
)
.replaceAll(
/(__|\*\*)PLACEHOLDER\:DRAFT_LEFT_PADDED(__|\*\*)/g,
draftSpec.$draft.padStart(2, "0"),
)
.replaceAll("__PLACEHOLDER:SCHEMA_URL__", draftSpec.$schemaUrl)
.replaceAll("__PLACEHOLDER:DOCS_URL__", draftSpec.$docsUrl)
.replace(
`__PLACEHOLDER__: true; // KEYWORDS_INTERFACE`,
Object.entries(draftSpec.keywords).map(([keyword, keywordSchema]) => {
const entry: string[] = [];
const comment = formatKeywordComment(keywordSchema);
if (comment !== undefined) {
entry.push(makeBlockComment(comment));
}
entry.push(
` ${keyword}?: ${
keyword === "type"
? "SchemaType"
: stringifyKeyword(keywordSchema as types.KeywordSchema)
};`,
);
return entry.join("\n");
}).join("\n\n"),
)
.replace(`// __PLACEHOLDER:KEYWORD_TYPES__`, () => {
const code: string[] = [];
for (
const entry of Object.values(
draftSpec.keywordsByType,
) as types.KeywordKind<string, string>[]
) {
code.push(
` export type ${entry.title} = ${
stringifyArrayToUnion(entry.values)
}`,
);
}
return code.join("\n\n");
})
.replace(`// __PLACEHOLDER:TYPE_NAMES_TYPE__`, () => {
const typeEnum = draftSpec.enums.typeName;
return ` export type TypeName = ${
stringifyArrayToUnion(
Object.values(typeEnum.values).map((entry) => entry.value),
2,
)
}`;
})
.replace(`// __PLACEHOLDER:ENUMS__`, () => {
const code: string[] = [];
for (
const enumSchema of Object.values(
draftSpec.enums,
) as types.EnumSchema[]
) {
if (enumSchema.description !== undefined) {
code.push(
makeBlockComment(enumSchema.description, 0),
);
}
code.push(
`export enum ${enumSchema.title} {${
Object.entries(enumSchema.values).map(
([valueKey, valueSchema]) => {
const value: string[] = [];
if (valueSchema.description !== undefined) {
value.push(
"\n\n",
makeBlockComment(valueSchema.description, 2),
"\n",
);
}
value.push(
`${" ".repeat(4)}${
Number.isInteger(parseInt(valueKey.charAt(0), 10))
? `"${valueKey}"`
: valueKey
} = "${valueSchema.value}",`,
);
return value.join("");
},
).join("")
}}\n`,
);
}
return code.join("\n");
})
.replace(`// __PLACEHOLDER:KEYWORDS__`, () => {
return `export const keywords = [${
stringifyArray(Object.keys(draftSpec.keywords))
}] as const;`;
})
.replace(
`"__PLACEHOLDER:TYPE_UNION__"`,
stringifyArrayToUnion(typeNames, 2),
).replace("// __PLACEHOLDER:EXTRACT_ARRAY_ITEMS_TUPLE__", () => {
return [
"// deno-fmt-ignore-start",
...LETTERS.map((_letter, index) => {
const chars = LETTERS.slice(0, index + 1);
return `: Schema extends { items: readonly [${
chars.map((char) => `infer ${char}`).join(", ")
}] } | { items: [${
chars.map((char) => `infer ${char}`).join(", ")
}]} ? [${
chars.map((char) => `JSONSchemaToValueType<${char}, RootSchema>`)
.join(", ")
}]`;
}),
// ...LETTERS.map((_letter, index) => {
// const chars = LETTERS.slice(0, index + 1);
// return `: Schema extends { items: [${
// chars.map((char) => `infer ${char}`).join(", ")
// }] } ? [${
// chars.map((char) => `JSONSchemaToValueType<${char}, RootSchema>`)
// .join(", ")
// }]`;
// }),
"// deno-fmt-ignore-end",
,
].join("\n");
});
assertCodeDoesNotHavePlaceholder(filename, newCode);
return newCode;
}; | the_stack |
import * as PropTypes from 'prop-types';
const numberProp = PropTypes.oneOfType([PropTypes.string, PropTypes.number]);
const numberArrayProp = PropTypes.oneOfType([PropTypes.arrayOf(numberProp), numberProp]);
const fillProps = {
fill: PropTypes.string,
fillOpacity: numberProp,
fillRule: PropTypes.oneOf(['evenodd', 'nonzero']),
};
const clipProps = {
clipRule: PropTypes.oneOf(['evenodd', 'nonzero']),
clipPath: PropTypes.string,
};
const definationProps = {
name: PropTypes.string,
};
const strokeProps = {
stroke: PropTypes.string,
strokeWidth: numberProp,
strokeOpacity: numberProp,
strokeDasharray: numberArrayProp,
strokeDashoffset: numberProp,
strokeLinecap: PropTypes.oneOf(['butt', 'square', 'round']),
strokeLinejoin: PropTypes.oneOf(['miter', 'bevel', 'round']),
strokeAlignment: PropTypes.oneOf(['center', 'inner', 'outer']),
strokeMiterlimit: numberProp,
};
const transformProps = {
scale: numberProp,
scaleX: numberProp,
scaleY: numberProp,
rotate: numberProp,
rotation: numberProp,
translate: numberProp,
translateX: numberProp,
translateY: numberProp,
x: numberProp,
y: numberProp,
origin: numberProp,
originX: numberProp,
originY: numberProp,
skew: numberProp,
skewX: numberProp,
skewY: numberProp,
transform: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
};
const pathProps = {
...fillProps,
...strokeProps,
...clipProps,
...transformProps,
...definationProps,
};
// normal | italic | oblique | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-style
const fontStyle = PropTypes.oneOf(['normal', 'italic', 'oblique']);
// normal | small-caps | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-variant
const fontVariant = PropTypes.oneOf(['normal', 'small-caps']);
// normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-weight
const fontWeight = PropTypes.oneOf([
'normal',
'bold',
'bolder',
'lighter',
'100',
'200',
'300',
'400',
'500',
'600',
'700',
'800',
'900',
]);
// normal | wider | narrower | ultra-condensed | extra-condensed |
// condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-stretch
const fontStretch = PropTypes.oneOf([
'normal',
'wider',
'narrower',
'ultra-condensed',
'extra-condensed',
'condensed',
'semi-condensed',
'semi-expanded',
'expanded',
'extra-expanded',
'ultra-expanded',
]);
// <absolute-size> | <relative-size> | <length> | <percentage> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-size
const fontSize = numberProp;
// [[<family-name> | <generic-family>],]* [<family-name> | <generic-family>] | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/font-family
const fontFamily = PropTypes.string;
/*
font syntax [ [ <'font-style'> || <font-variant-css21> ||
<'font-weight'> || <'font-stretch'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ] |
caption | icon | menu | message-box | small-caption | status-bar
where <font-variant-css21> = [ normal | small-caps ]
Shorthand property for setting ‘font-style’, ‘font-variant’,
‘font-weight’, ‘font-size’, ‘line-height’ and ‘font-family’.
The ‘line-height’ property has no effect on text layout in SVG.
Note: for the purposes of processing the ‘font’ property in SVG,
'line-height' is assumed to be equal the value for property ‘font-size’
https://www.w3.org/TR/SVG11/text.html#FontProperty
https://developer.mozilla.org/en-US/docs/Web/CSS/font
https://drafts.csswg.org/css-fonts-3/#font-prop
https://www.w3.org/TR/CSS2/fonts.html#font-shorthand
https://www.w3.org/TR/CSS1/#font
*/
const font = PropTypes.object;
// start | middle | end | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor
const textAnchor = PropTypes.oneOf(['start', 'middle', 'end']);
// none | underline | overline | line-through | blink | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-decoration
const textDecoration = PropTypes.oneOf(['none', 'underline', 'overline', 'line-through', 'blink']);
// normal | <length> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing
const letterSpacing = numberProp;
// normal | <length> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/word-spacing
const wordSpacing = numberProp;
// auto | <length> | inherit
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/kerning
const kerning = numberProp;
/*
Name: font-variant-ligatures
Value: normal | none | [ <common-lig-values> || <discretionary-lig-values> ||
<historical-lig-values> || <contextual-alt-values> ]
Initial: normal
Applies to: all elements
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified
Animatable: no
Ligatures and contextual forms are ways of combining glyphs to produce more harmonized forms.
<common-lig-values> = [ common-ligatures | no-common-ligatures ]
<discretionary-lig-values> = [ discretionary-ligatures | no-discretionary-ligatures ]
<historical-lig-values> = [ historical-ligatures | no-historical-ligatures ]
<contextual-alt-values> = [ contextual | no-contextual ]
https://developer.mozilla.org/en/docs/Web/CSS/font-variant-ligatures
https://www.w3.org/TR/css-fonts-3/#font-variant-ligatures-prop
*/
const fontVariantLigatures = PropTypes.oneOf(['normal', 'none']);
const fontProps = {
fontStyle,
fontVariant,
fontWeight,
fontStretch,
fontSize,
fontFamily,
textAnchor,
textDecoration,
letterSpacing,
wordSpacing,
kerning,
fontVariantLigatures,
font,
};
/*
Name Value Initial value Animatable
lengthAdjust spacing | spacingAndGlyphs spacing yes
https://svgwg.org/svg2-draft/text.html#TextElementLengthAdjustAttribute
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/lengthAdjust
*/
const lengthAdjust = PropTypes.oneOf(['spacing', 'spacingAndGlyphs']);
/*
Name Value Initial value Animatable
textLength <length> | <percentage> | <number> See below yes
https://svgwg.org/svg2-draft/text.html#TextElementTextLengthAttribute
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/textLength
*/
const textLength = numberProp;
/*
2.2. Transverse Box Alignment: the vertical-align property
Name: vertical-align
Value: <‘baseline-shift’> || <‘alignment-baseline’>
Initial: baseline
Applies to: inline-level boxes
Inherited: no
Percentages: N/A
Media: visual
Computed value: as specified
Canonical order: per grammar
Animation type: discrete
This shorthand property specifies how an inline-level box is aligned within the line.
Values are the same as for its longhand properties, see below.
Authors should use this property (vertical-align) instead of its longhands.
https://www.w3.org/TR/css-inline-3/#transverse-alignment
https://drafts.csswg.org/css-inline/#propdef-vertical-align
*/
const verticalAlign = numberProp;
/*
Name: alignment-baseline
1.1 Value: auto | baseline | before-edge | text-before-edge | middle | central |
after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | inherit
2.0 Value: baseline | text-bottom | alphabetic | ideographic | middle | central |
mathematical | text-top | bottom | center | top
Initial: baseline
Applies to: inline-level boxes, flex items, grid items, table cells
Inherited: no
Percentages: N/A
Media: visual
Computed value: as specified
Canonical order: per grammar
Animation type: discrete
https://drafts.csswg.org/css-inline/#propdef-alignment-baseline
https://www.w3.org/TR/SVG11/text.html#AlignmentBaselineProperty
https://svgwg.org/svg2-draft/text.html#AlignmentBaselineProperty
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/alignment-baseline
*/
const alignmentBaseline = PropTypes.oneOf([
'baseline',
'text-bottom',
'alphabetic',
'ideographic',
'middle',
'central',
'mathematical',
'text-top',
'bottom',
'center',
'top',
'text-before-edge',
'text-after-edge',
'before-edge',
'after-edge',
'hanging',
]);
/*
2.2.2. Alignment Shift: baseline-shift longhand
Name: baseline-shift
Value: <length> | <percentage> | sub | super
Initial: 0
Applies to: inline-level boxes
Inherited: no
Percentages: refer to the used value of line-height
Media: visual
Computed value: absolute length, percentage, or keyword specified
Animation type: discrete
This property specifies by how much the box is shifted up from its alignment point.
It does not apply when alignment-baseline is top or bottom.
https://www.w3.org/TR/css-inline-3/#propdef-baseline-shift
*/
const baselineShift = PropTypes.oneOfType([
PropTypes.oneOf(['sub', 'super', 'baseline']),
PropTypes.arrayOf(numberProp),
numberProp,
]);
/*
6.12. Low-level font feature settings control: the font-feature-settings property
Name: font-feature-settings
Value: normal | <feature-tag-value> #
Initial: normal
Applies to: all elements
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified
Animatable: no
This property provides low-level control over OpenType font features.
It is intended as a way of providing access to font features
that are not widely used but are needed for a particular use case.
Authors should generally use ‘font-variant’ and its related subproperties
whenever possible and only use this property for special cases where its use
is the only way of accessing a particular infrequently used font feature.
enable small caps and use second swash alternate
font-feature-settings: "smcp", "swsh" 2;
A value of ‘normal’ means that no change in glyph selection or positioning
occurs due to this property.
Feature tag values have the following syntax:
<feature-tag-value> = <string> [ <integer> | on | off ]?
The <string> is a case-sensitive OpenType feature tag. As specified in the
OpenType specification, feature tags contain four ASCII characters.
Tag strings longer or shorter than four characters,
or containing characters outside the U+20–7E codepoint range are invalid.
Feature tags need only match a feature tag defined in the font,
so they are not limited to explicitly registered OpenType features.
Fonts defining custom feature tags should follow the tag name rules
defined in the OpenType specification [OPENTYPE-FEATURES].
Feature tags not present in the font are ignored;
a user agent must not attempt to synthesize fallback behavior based on these feature tags.
The one exception is that user agents may synthetically support the kern feature with fonts
that contain kerning data in the form of a ‘kern’ table but lack kern feature
support in the ‘GPOS’ table.
In general, authors should use the ‘font-kerning’ property to explicitly
enable or disable kerning
since this property always affects fonts with either type of kerning data.
If present, a value indicates an index used for glyph selection.
An <integer> value must be 0 or greater.
A value of 0 indicates that the feature is disabled.
For boolean features, a value of 1 enables the feature.
For non-boolean features, a value of 1 or greater enables the
feature and indicates the feature selection index.
A value of ‘on’ is synonymous with 1 and ‘off’ is synonymous with 0.
If the value is omitted, a value of 1 is assumed.
font-feature-settings: "dlig" 1; /* dlig=1 enable discretionary ligatures * /
font-feature-settings: "smcp" on; /* smcp=1 enable small caps * /
font-feature-settings: 'c2sc'; /* c2sc=1 enable caps to small caps * /
font-feature-settings: "liga" off; /* liga=0 no common ligatures * /
font-feature-settings: "tnum", 'hist'; /* tnum=1, hist=1 enable tabular numbers
and historical forms * /
font-feature-settings: "tnum" "hist"; /* invalid, need a comma-delimited list * /
font-feature-settings: "silly" off; /* invalid, tag too long * /
font-feature-settings: "PKRN"; /* PKRN=1 enable custom feature * /
font-feature-settings: dlig; /* invalid, tag must be a string * /
When values greater than the range supported by the font are specified,
the behavior is explicitly undefined.
For boolean features, in general these will enable the feature.
For non-boolean features, out of range values will in general be equivalent to a 0 value.
However, in both cases the exact behavior will depend upon the way the font is designed
(specifically, which type of lookup is used to define the feature).
Although specifically defined for OpenType feature tags,
feature tags for other modern font formats that support font features
may be added in the future.
Where possible, features defined for other font formats
should attempt to follow the pattern of registered OpenType tags.
The Japanese text below will be rendered with half-width kana characters:
body { font-feature-settings: "hwid"; /* Half-width OpenType feature * / }
<p>毎日カレー食べてるのに、飽きない</p>
https://drafts.csswg.org/css-fonts-3/#propdef-font-feature-settings
https://developer.mozilla.org/en/docs/Web/CSS/font-feature-settings
*/
const fontFeatureSettings = PropTypes.string;
const textSpecificProps = {
...pathProps,
...fontProps,
alignmentBaseline,
baselineShift,
verticalAlign,
lengthAdjust,
textLength,
fontData: PropTypes.object,
fontFeatureSettings,
};
// https://svgwg.org/svg2-draft/text.html#TSpanAttributes
const textProps = {
...textSpecificProps,
dx: numberArrayProp,
dy: numberArrayProp,
};
/*
Name
side
Value
left | right
initial value
left
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementSideAttribute
*/
const side = PropTypes.oneOf(['left', 'right']);
/*
Name
startOffset
Value
<length> | <percentage> | <number>
initial value
0
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementStartOffsetAttribute
https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
*/
const startOffset = numberProp;
/*
Name
method
Value
align | stretch
initial value
align
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementMethodAttribute
https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
*/
const method = PropTypes.oneOf(['align', 'stretch']);
/*
Name
spacing
Value
auto | exact
initial value
exact
Animatable
yes
https://svgwg.org/svg2-draft/text.html#TextPathElementSpacingAttribute
https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
*/
const spacing = PropTypes.oneOf(['auto', 'exact']);
/*
Name
mid-line
Value
sharp | smooth
initial value
smooth
Animatable
yes
*/
const midLine = PropTypes.oneOf(['sharp', 'smooth']);
// https://svgwg.org/svg2-draft/text.html#TextPathAttributes
// https://developer.mozilla.org/en/docs/Web/SVG/Element/textPath
const textPathProps = {
...textSpecificProps,
href: PropTypes.string.isRequired,
startOffset,
method,
spacing,
side,
midLine,
};
export {
numberProp,
fillProps,
strokeProps,
fontProps,
textProps,
textPathProps,
clipProps,
pathProps,
}; | the_stack |
import chalk from 'chalk';
import fs from 'fs';
import https, { Agent as HttpsAgent } from 'https';
import path from 'path';
import FormData from 'form-data';
import axios, { AxiosRequestConfig, AxiosError } from 'axios';
import { TLSSocket } from 'tls';
import { digest, hmac } from './digest';
import { ClientRequest, IncomingMessage } from 'http';
export interface PackageDeployOptions {
packagePath: string;
appName: string;
importServiceUrl: string;
secret: string;
debugSecurity?: boolean;
acceptCertificate?: string;
proxy?: string;
}
// Node does not use system level trusted CAs. This causes issues because SIF likes to install
// using a Windows trusted CA - so SSL connections to Sitecore will fail from Node.
// If the options.acceptCertificate is passed, we disable normal SSL validation and use this function
// to whitelist only a cert with the specific thumbprint - essentially certificate pinning.
/**
* @param {ClientRequest} req
* @param {PackageDeployOptions} options
*/
export function applyCertPinning(req: ClientRequest, options: PackageDeployOptions) {
req.on('socket', (socket) => {
socket.on('secureConnect', () => {
const fingerprint = (socket as TLSSocket).getPeerCertificate().fingerprint;
// Match the fingerprint with our saved fingerprint
if (
options.acceptCertificate &&
!doFingerprintsMatch(options.acceptCertificate, fingerprint)
) {
// Abort request, optionally emit an error event
req.emit(
'error',
new Error(
`Expected server SSL certificate to have thumbprint ${options.acceptCertificate} from acceptCertificate, but got ${fingerprint} from server. This may mean the certificate has changed, or that a malicious certificate is present.`
)
);
return req.abort();
}
});
});
}
/**
* @param {string} fp
*/
export function normalizeFingerprint(fp: string): string {
//
// The fingerprint for a certificate is a 20-byte value.
// Such values are typically expressed as strings, but
// there are many different formats that may be used.
//
// For example, the following values all represent
// the same fingerprint:
// * 5E:D1:5E:D4:D4:42:71:CC:30:A5:B6:A2:DA:A4:79:06:67:CB:F6:36
// * 5ED15ED4D44271CC30A5B6A2DAA4790667CBF636
// * 5e:d1:5e:d4:d4:42:71:cc:30:a5:b6:a2:da:a4:79:06:67:cb:f6:36
// * 5ed15ed4d44271cc30a5b6a2daa4790667cbf636
//
// Before two fingerprints can be properly compared,
// they must be converted into the same format. This
// function implements the logic for that conversion.
return fp.toLowerCase().replace(new RegExp(':', 'g'), '');
}
/**
* @param {string} fp1
* @param {string} fp2
*/
export function doFingerprintsMatch(fp1: string, fp2: string): boolean {
return normalizeFingerprint(fp1) === normalizeFingerprint(fp2);
}
/**
* @param {Object} params
* @param {string[]} params.warnings
* @param {string[]} params.errors
* @param {Function} params.resolve
* @param {Function} params.reject
*/
export function finishWatchJobStatusTask({
warnings,
errors,
resolve,
reject,
}: {
warnings: string[];
errors: string[];
resolve: (value?: unknown) => void;
reject: () => void;
}) {
console.log();
console.log('Import is complete.');
if (warnings.length) {
console.log();
console.warn(chalk.yellow('IMPORT WARNING(S) OCCURRED!'));
warnings.forEach((w) => console.error(chalk.yellow(w)));
}
if (errors.length) {
console.log();
console.error(chalk.red('IMPORT ERROR(S) OCCURRED!'));
errors.forEach((e) => console.error(chalk.red(e)));
reject();
} else {
resolve();
}
}
/**
* @param {Object} params
* @param {string} params.message
* @param {string} params.entryLevel
* @param {string[]} params.warnings
* @param {string[]} params.errors
*/
export function logJobStatus({
message,
entryLevel,
warnings,
errors,
}: {
message: string;
entryLevel: string;
warnings: string[];
errors: string[];
}) {
switch (entryLevel) {
case 'WARN':
console.warn(chalk.yellow(message));
warnings.push(message);
break;
case 'ERROR':
console.error(chalk.red(message));
errors.push(message);
break;
case 'DEBUG':
console.log(chalk.white(message));
break;
default:
console.log(chalk.green(message));
break;
}
}
/**
* @param {PackageDeployOptions} options
* @param {string} taskName
*/
async function watchJobStatus(options: PackageDeployOptions, taskName: string) {
let logOffset = 0;
const errors: string[] = [];
const warnings: string[] = [];
const factors = [options.appName, taskName, `${options.importServiceUrl}/status`];
const mac = hmac(factors, options.secret);
const isHttps = options.importServiceUrl.startsWith('https');
const requestBaseOptions = {
transport: isHttps ? getHttpsTransport(options) : undefined,
headers: {
'User-Agent': 'Sitecore/JSS-Import',
'Cache-Control': 'no-cache',
'X-JSS-Auth': mac,
},
proxy: extractProxy(options.proxy),
maxRedirects: 0,
httpsAgent: isHttps
? new HttpsAgent({
// we turn off normal CA cert validation when we are whitelisting a single cert thumbprint
rejectUnauthorized: options.acceptCertificate ? false : true,
// needed to allow whitelisting a cert thumbprint if a connection is reused
maxCachedSessions: options.acceptCertificate ? 0 : undefined,
})
: undefined,
};
if (options.debugSecurity) {
console.log(`Deployment status security factors: ${factors}`);
console.log(`Deployment status HMAC: ${mac}`);
}
return new Promise((resolve, reject) => {
/**
* Send job status request
*/
function sendJobStatusRequest() {
axios
.get(
`${options.importServiceUrl}/status?appName=${options.appName}&jobName=${taskName}&after=${logOffset}`,
requestBaseOptions
)
.then((response) => {
const body = response.data;
try {
const { state, messages }: { state: string; messages: string[] } = body;
messages.forEach((entry) => {
logOffset++;
const entryBits = /^(\[([A-Z]+)\] )?(.+)/.exec(entry);
let entryLevel = 'INFO';
let message = entry;
if (entryBits && entryBits[2]) {
entryLevel = entryBits[2];
// 3 = '[] ' in say [INFO] My log message
// we're not using the capture group as the message might be multi-line
message = entry.substring(entryLevel.length + 3);
}
if (message.startsWith('[JSS] - ')) {
message = message.substring(8);
}
logJobStatus({ message, entryLevel, warnings, errors });
});
if (state === 'Finished') {
finishWatchJobStatusTask({ warnings, errors, resolve, reject });
return;
}
setTimeout(sendJobStatusRequest, 1000);
} catch (error) {
console.error(
chalk.red(`Unexpected error processing reply from import status service: ${error}`)
);
console.error(chalk.red(`Response: ${body}`));
console.error(chalk.red('Consult the Sitecore logs for details.'));
reject(error);
}
})
.catch((error: AxiosError) => {
console.error(
chalk.red(
'Unexpected response from import status service. The import task is probably still running; check the Sitecore logs for details.'
)
);
if (error.response) {
console.error(chalk.red(`Status message: ${error.response.statusText}`));
console.error(chalk.red(`Status: ${error.response.status}`));
} else {
console.error(chalk.red(error.message));
}
reject();
});
}
setTimeout(sendJobStatusRequest, 1000);
});
}
/**
* @param {PackageDeployOptions} options
*/
export async function packageDeploy(options: PackageDeployOptions) {
if (!options.secret) {
throw new Error(
'Deployment secret was not passed. A shared secret must be configured on both the Sitecore app config and the JS app config'
);
}
if (options.secret.length < 32) {
throw new Error(
'Deployment secret was too short. Use a RANDOM (not words or phrases) secret at least 32 characters long.'
);
}
let packageFile = null;
fs.readdirSync(options.packagePath).forEach((file) => {
if (file.startsWith(options.appName) && file.endsWith('.manifest.zip')) {
packageFile = path.join(options.packagePath, file);
}
});
if (!packageFile) {
throw new Error('Package file not found, ensure you have generated the package first.');
}
const factors = [options.appName, options.importServiceUrl, await digest(packageFile)];
if (options.debugSecurity) {
console.log('Security debugging is enabled. Do not use this unless absolutely necessary.');
console.log(`Deployment secret: ${options.secret}`);
console.log(`Deployment security factors: ${factors}`);
console.log(`Deployment HMAC: ${hmac(factors, options.secret)}`);
}
const formData = new FormData();
formData.append('path', fs.createReadStream(packageFile));
formData.append('appName', options.appName);
const isHttps = options.importServiceUrl.startsWith('https');
const requestBaseOptions = {
transport: isHttps ? getHttpsTransport(options) : undefined,
headers: {
'User-Agent': 'Sitecore/JSS-Import',
'Cache-Control': 'no-cache',
'X-JSS-Auth': hmac(factors, options.secret),
...formData.getHeaders(),
},
proxy: extractProxy(options.proxy),
httpsAgent: isHttps
? new HttpsAgent({
// we turn off normal CA cert validation when we are whitelisting a single cert thumbprint
rejectUnauthorized: options.acceptCertificate ? false : true,
// needed to allow whitelisting a cert thumbprint if a connection is reused
maxCachedSessions: options.acceptCertificate ? 0 : undefined,
})
: undefined,
maxRedirects: 0,
} as AxiosRequestConfig;
console.log(`Sending package ${packageFile} to ${options.importServiceUrl}...`);
return new Promise<string>((resolve, reject) => {
axios
.post(options.importServiceUrl, formData, requestBaseOptions)
.then((response) => {
const body = response.data;
console.log(chalk.green(`Sitecore has accepted import task ${body}`));
resolve(body);
})
.catch((error: AxiosError) => {
console.error(chalk.red('Unexpected response from import service:'));
if (error.response) {
console.error(chalk.red(`Status message: ${error.response.statusText}`));
console.error(chalk.red(`Status: ${error.response.status}`));
} else {
console.error(chalk.red(error.message));
}
reject();
});
}).then((taskName) => watchJobStatus(options, taskName));
}
/**
* Creates valid proxy object which fit to axios configuration
* @param {string} [proxy] proxy url
*/
export function extractProxy(proxy?: string) {
if (!proxy) return undefined;
try {
const proxyUrl = new URL(proxy);
return {
protocol: proxyUrl.protocol.slice(0, -1),
host: proxyUrl.hostname,
port: +proxyUrl.port,
};
} catch (error) {
console.error(chalk.red(`Invalid proxy url provided ${proxy}`));
process.exit(1);
}
}
/**
* Provides way to customize axios request adapter
* in order to execute certificate pinning before request sent:
* {@link https://github.com/axios/axios/issues/2808}
* @param {PackageDeployOptions} options
*/
export function getHttpsTransport(options: PackageDeployOptions) {
return {
...https,
request: (reqOptions: https.RequestOptions, callback: (res: IncomingMessage) => void) => {
const req = https.request(
{
...reqOptions,
},
callback
);
applyCertPinning(req, options);
return req;
},
};
} | the_stack |
process.on('unhandledRejection', err => {
console.log("Caught unhandledRejection");
console.log(err);
});
'use strict';
// @ts-ignore
const mochaSteps = require('mocha-steps');
const step: Mocha.ITestDefinition = mochaSteps.step;
const Map: typeof MapPolyfill = (global as any).Map;
import * as request from 'request';
import { assert } from 'chai';
import * as path from 'path';
import * as fs from 'fs';
import { GlobalObject } from '../app/js/background/sharedTypes';
import { DeepPartial } from './imports';
function isDefaultKey(key: string): key is Extract<keyof Storage, string> {
return !(key !== 'getItem' &&
key !== 'setItem' &&
key !== 'length' &&
key !== 'clear' &&
key !== 'removeItem');
}
function createLocalStorageObject(): Storage {
var obj: Storage & {
[key: string]: any;
} = {
getItem(key: string) {
if (!isDefaultKey(key)) {
return obj[key];
}
return undefined;
},
setItem(key, value) {
if (!isDefaultKey(key)) {
obj[key] = value;
}
},
removeItem(key) {
if (!isDefaultKey(key)) {
delete obj[key];
}
},
get length() {
var keys = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key) && !isDefaultKey(key)) {
keys++;
}
}
return keys;
},
key(index) {
var keyIndex = 0;
var lastKey = null;
for (var key in obj) {
if (keyIndex === index) {
return key;
}
keyIndex++;
lastKey = key;
}
return lastKey;
},
clear() {
for (var key in obj) {
if (obj.hasOwnProperty(key) && !isDefaultKey(key)) {
obj.removeItem(key);
}
}
}
}
return obj;
}
function toOldCrmNode(node: CRM.Node) {
var oldNodes: string[] = [];
var dataArr = [node.name, node.type[0].toUpperCase() + node.type.slice(1)];
switch (node.type) {
case 'link':
dataArr.push(node.value.map((link) => {
return link.url;
}).join(','));
oldNodes[0] = dataArr.join('%123');
break;
case 'menu':
var children = node.children;
dataArr.push(children.length + '');
oldNodes[0] = dataArr.join('%123');
children.forEach((child) => {
oldNodes = oldNodes.concat(toOldCrmNode(child));
});
break;
case 'divider':
dataArr.push('');
oldNodes[0] = dataArr.join('%123');
break;
case 'script':
var toPush;
switch (~~node.value.launchMode) {
case 0: // Always
toPush = ['0', node.value.script].join('%124');
break;
case 1: // On clicking
toPush = node.value.script;
break;
case 2: // On selected sites
toPush = [['1'].concat(node.triggers.map((trigger) => {
return trigger.url;
})).join(', '), node.value.script].join('%124');
break;
default:
throw new Error('Script launchmode not supported on old CRM');
}
dataArr.push(toPush);
oldNodes[0] = dataArr.join('%123');
break;
default:
throw new Error('Node to simulate has no matching type for old CRM');
}
return oldNodes;
}
function createCrmLocalStorage(nodes: DeepPartial<CRM.Node>[], newTab: boolean = false): Storage {
var obj = createLocalStorageObject();
obj.whatpage = !!newTab;
obj.noBetaAnnouncement = true;
obj.firsttime = 'no';
obj.scriptOptions = '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,';
var oldNodes: string[] = [];
nodes.forEach((node) => {
oldNodes = oldNodes.concat(toOldCrmNode(node as CRM.Node));
});
obj.numberofrows = oldNodes.length;
oldNodes.forEach((oldNode, index) => {
obj[index + 1] = oldNode;
});
return obj;
}
var backgroundPageWindowResolve: (val?: any) => void;
var backgroundPageWindowDone = new Promise((resolve) => {
backgroundPageWindowResolve = resolve;
});
function mergeObjects<T1, T2>(obj1: T1, obj2: T2): T1 & T2 {
const joined: Partial<T1 & T2> = {};
for (let key in obj1) {
(joined as any)[key as any] = obj1[key];
}
for (let key in obj2) {
(joined as any)[key as any] = obj2[key];
}
return joined as T1 & T2;
}
function generateRandomString(noDot: boolean = false) {
var length = 25 + Math.floor(Math.random() * 25);
var str = [];
for (var i = 0; i < length; i++) {
if (Math.floor(Math.random() * 5) === 0 && str[str.length - 1] !== '.' && str.length > 0 && (i - 1) !== length && !noDot) {
str.push('.');
} else {
str.push(String.fromCharCode(48 + Math.floor(Math.random() * 74)));
}
}
str.push('a');
return str.join('');
}
//Takes a function and catches any errors, generating stack traces
// from the point of view of the actual error instead of the
// assert error, which makes debugging waaaay easier
// var run = (fn: Function) => {
// return () => {
// try {
// return fn();
// } catch (e) {
// console.log('Error', e);
// throw e;
// }
// };
// };
function createCopyFunction(obj: {
[key: string]: any;
}, target: {
[key: string]: any;
}) {
return (props: string[]) => {
props.forEach((prop) => {
if (prop in obj) {
if (typeof obj[prop] === 'object') {
target[prop] = JSON.parse(JSON.stringify(obj[prop]));
} else {
target[prop] = obj[prop];
}
}
});
}
}
function makeNodeSafe(node: CRM.Node): CRM.SafeNode {
const newNode: Partial<CRM.SafeNode> = {};
if (node.children) {
newNode.children = [];
for (var i = 0; i < node.children.length; i++) {
newNode.children[i] = makeNodeSafe(node.children[i]);
}
}
const copy = createCopyFunction(node, newNode);
copy(['id','path', 'type', 'name', 'value', 'linkVal',
'menuVal', 'scriptVal', 'stylesheetVal', 'nodeInfo',
'triggers', 'onContentTypes', 'showOnSpecified']);
safeNodes.push(newNode as CRM.SafeNode);
return newNode as CRM.SafeNode;
}
function makeTreeSafe(tree: CRM.Node[]) {
var safe = [];
for (var i = 0; i < tree.length; i++) {
safe.push(makeNodeSafe(tree[i]));
}
return safe;
}
const safeNodes: CRM.SafeNode[] = [];
const testCRMTree = [{
"name": "menu",
"onContentTypes": [true, true, true, true, true, true],
"type": "menu",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": null,
"id": 0,
"path": [0],
"index": 0,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"children": [],
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: [],
nodeInfo: {
permissions: []
}
} as CRM.MenuNode, {
"name": "link",
"onContentTypes": [true, true, true, false, false, false],
"type": "link",
"showOnSpecified": true,
"triggers": [{
"url": "*://*.example.com/*",
"not": true
}, {
"url": "www.google.com",
"not": false
}],
"isLocal": true,
"value": [{
"url": "https://www.google.com",
"newTab": true
}, {
"url": "www.youtube.com",
"newTab": false
}],
"id": 1,
"path": [1],
"index": 1,
children: null,
linkVal: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: [],
nodeInfo: {
permissions: []
}
} as CRM.LinkNode, {
"name": "script",
"onContentTypes": [true, true, true, false, false, false],
"type": "script",
"showOnSpecified": false,
"isLocal": true,
"value": {
"launchMode": 0,
"backgroundLibraries": [],
"libraries": [],
"script": "// ==UserScript==\n// @name\tscript\n// @CRM_contentTypes\t[true, true, true, false, false, false]\n// @CRM_launchMode\t2\n// @grant\tnone\n// @match\t*://*.google.com/*\n// @exclude\t*://*.example.com/*\n// ==/UserScript==\nconsole.log('Hello');",
"backgroundScript": "",
"metaTags": {
"name": ["script"],
"CRM_contentTypes": ["[true, true, true, false, false, false]"],
"CRM_launchMode": ["2"],
"grant": ["none"],
"match": ["*://*.google.com/*"],
"exclude": ["*://*.example.com/*"]
},
"options": {},
ts: {
enabled: false,
script: { },
backgroundScript: {}
}
},
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": false
}, {
"url": "*://*.google.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": true
}],
"id": 2 as CRM.GenericNodeId,
"path": [2],
"index": 2,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"nodeInfo": {
"permissions": []
},
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
} as CRM.ScriptNode, {
"name": "stylesheet",
"onContentTypes": [true, true, true, false, false, false],
"type": "stylesheet",
"showOnSpecified": false,
"isLocal": true,
"value": {
"stylesheet": "/* ==UserScript==\n// @name\tstylesheet\n// @CRM_contentTypes\t[true, true, true, false, false, false]\n// @CRM_launchMode\t3\n// @CRM_stylesheet\ttrue\n// @grant\tnone\n// @match\t*://*.example.com/*\n// ==/UserScript== */\nbody {\n\tbackground-color: red;\n}",
"launchMode": 0,
"toggle": true,
"defaultOn": true,
"options": {},
convertedStylesheet: {
options: '',
stylesheet: ''
}
},
"id": 3,
"path": [3],
"index": 3,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"nodeInfo": {
permissions: []
},
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
} as CRM.StylesheetNode, {
"name": "divider",
"onContentTypes": [true, true, true, false, false, false],
"type": "divider",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": null,
"id": 4,
"path": [4],
"index": 4,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
nodeInfo: {
permissions: []
},
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
} as CRM.DividerNode, {
"name": "menu",
"onContentTypes": [true, true, true, false, false, false],
"type": "menu",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": null,
"id": 5,
"path": [5],
"index": 5,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"children": [{
"name": "lots of links",
"onContentTypes": [true, true, true, false, false, false],
"type": "link",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": [{
"url": "https://www.example.com",
"newTab": true
}, {
"url": "www.example.com",
"newTab": true
}, {
"url": "www.example.com",
"newTab": false
}, {
"url": "www.example.com",
"newTab": true
}, {
"url": "www.example.com",
"newTab": true
}],
"id": 6,
"path": [5, 0],
"index": 0,
nodeInfo: {
permissions: []
},
linkVal: null,
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
}],
nodeInfo: {
permissions: []
},
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
} as CRM.MenuNode];
const testCRMTreeBase = JSON.parse(JSON.stringify(testCRMTree));
const safeTestCRMTree = makeTreeSafe(testCRMTree) as [
CRM.SafeMenuNode, CRM.SafeLinkNode,
CRM.SafeScriptNode, CRM.SafeStylesheetNode,
CRM.SafeDividerNode, CRM.SafeMenuNode
];
function resetTree() {
return new Promise((resolve) => {
bgPageOnMessageListener({
type: 'updateStorage',
data: {
type: 'optionsPage',
localChanges: false,
settingsChanges: [{
key: 'crm',
oldValue: testCRMTree,
newValue: JSON.parse(JSON.stringify(testCRMTreeBase))
}]
}
}, {}, (response: any) => {
resolve(response);
});
});
}
class xhr {
public readyState: number;
public status: number;
public responseText: string;
private _config: {
method: string;
filePath: string;
}
constructor() {
this.readyState = 0;
this.status = xhr.UNSENT;
this.responseText = '';
this._config;
}
open(method: string, filePath: string) {
//Strip chrome-extension://
filePath = filePath.split('://something/')[1];
this.readyState = xhr.UNSENT;
this._config = {
method: method,
filePath: filePath
}
}
onreadystatechange() {
console.log('This should not be called, onreadystatechange is not overridden');
}
send() {
fs.readFile(path.join(__dirname, '..', 'build/', this._config.filePath), {
encoding: 'utf8',
}, (err, data) => {
this.readyState = xhr.DONE;
if (err) {
if (err.code === 'ENOENT') {
this.status = 404;
} else {
this.status = 500;
}
} else {
this.status = 200;
}
this.responseText = data;
this.onreadystatechange();
});
if (this.readyState === xhr.UNSENT) {
this.readyState = xhr.LOADING;
}
}
static get UNSENT() {
return 0;
}
static get OPENED() {
return 1;
}
static get HEADERS_RECEIVED() {
return 2;
}
static get LOADING() {
return 3;
}
static get DONE() {
return 4;
}
}
// Simulate user-agent chrome on windows for codemirror
//@ts-ignore
const navigator = {
userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'
};
const document: Partial<Document> = {
documentMode: true,
createElement: function () {
return {
getAttribute: function() {},
setAttribute: function () { },
appendChild: function () { },
classList: {
add: function () { }
},
animate: function () {
return {
onfinish: function () { }
};
},
addEventListener: function () { },
style: {},
src: ''
};
},
nodeType: 9,
get documentElement() {
return document;
},
createComment: function() {},
body: {
appendChild(el: {
src: string;
}) {
if (el.src.indexOf('chrome-extension') > -1) {
el.src = el.src.split('something')[1].slice(1);
}
fs.readFile(path.join(__dirname, '..', 'build/', el.src), {
encoding: 'utf8',
}, (err, data) => {
if (err) {
throw err;
} else {
eval(data);
}
});
}
}
} as any;
const storageLocal: {
[key: string]: any;
} = {};
const storageSync: {
[key: string]: any;
} = {};
var bgPageConnectListener: (port: _browser.runtime.Port) => void;
var idChangeListener: (change: {
[key: string]: {
oldValue?: any;
newValue?: any;
}
}) => void;
//Type checking
function getOriginalFunctionName(err: Error) {
var fns = err.stack.split('\n').slice(1);
for (var i = 0; i < fns.length; i++) {
if (fns[i].indexOf('typeCheck') > -1) {
var offset = 1;
if (fns[i + 1].indexOf('checkOnlyCallback') > -1) {
offset = 2;
}
return ' - at' + fns[i + offset].split('at')[1];
}
}
return '';
}
function getDotValue<T extends {
[key: string]: T|any;
}>(source: T, index: string) {
var indexes = index.split('.');
var currentValue = source;
for (var i = 0; i < indexes.length; i++) {
if (indexes[i] in currentValue) {
currentValue = currentValue[indexes[i]];
}
else {
return undefined;
}
}
return currentValue;
};
type TypeCheckTypes = 'string' | 'function' |
'number' | 'object' | 'array' | 'boolean' | 'enum';
interface TypeCheckConfig {
val: string;
type: TypeCheckTypes | TypeCheckTypes[];
optional?: boolean;
forChildren?: {
val: string;
type: TypeCheckTypes | TypeCheckTypes[];
optional?: boolean;
}[];
dependency?: string;
min?: number;
max?: number;
enum?: any[];
}
function dependencyMet(data: TypeCheckConfig, optionals: {
[key: string]: any;
[key: number]: any;
}): boolean {
if (data.dependency && !optionals[data.dependency]) {
optionals[data.val] = false;
return false;
}
return true;
}
function isDefined(data: TypeCheckConfig, value: any, optionals: {
[key: string]: any;
[key: number]: any;
}): boolean | 'continue' {
//Check if it's defined
if (value === undefined || value === null) {
if (data.optional) {
optionals[data.val] = false;
return 'continue';
} else {
throw new Error("Value for " + data.val + " is not set" + getOriginalFunctionName(new Error()));
}
}
return true;
};
function typesMatch(data: TypeCheckConfig, value: any): string {
const types = Array.isArray(data.type) ? data.type : [data.type];
for (let i = 0; i < types.length; i++) {
const type = types[i];
if (type === 'array') {
if (typeof value === 'object' && Array.isArray(value)) {
return type;
}
} else if (type === 'enum') {
if (data.enum.indexOf(value) > -1) {
return type;
}
}
if (typeof value === type) {
return type;
}
}
throw new Error("Value for " + data.val + " is not of type " + types.join(' or ') +
getOriginalFunctionName(new Error()));
};
function checkNumberConstraints(data: TypeCheckConfig, value: number): boolean {
if (data.min !== undefined) {
if (data.min > value) {
throw new Error("Value for " + data.val + " is smaller than " + data.min +
getOriginalFunctionName(new Error()));
}
}
if (data.max !== undefined) {
if (data.max < value) {
throw new Error("Value for " + data.val + " is bigger than " + data.max +
getOriginalFunctionName(new Error()));
}
}
return true;
};
function checkArrayChildType(data: TypeCheckConfig, value: any, forChild: {
val: string;
type: TypeCheckTypes | TypeCheckTypes[];
optional?: boolean;
}): boolean {
var types = Array.isArray(forChild.type) ? forChild.type : [forChild.type];
for (var i = 0; i < types.length; i++) {
var type = types[i];
if (type === 'array') {
if (Array.isArray(value)) {
return true;
}
}
else if (typeof value === type) {
return true;
}
}
throw new Error("For not all values in the array " + data.val +
" is the property " + forChild.val + " of type " + types.join(' or ') +
getOriginalFunctionName(new Error()));
};
function checkArrayChildrenConstraints<T extends {
[key: string]: any;
}>(data: TypeCheckConfig, values: T[]): boolean {
for (const value of values) {
for (const forChild of data.forChildren) {
const childValue = value[forChild.val];
if (childValue === undefined || childValue === null) {
if (!forChild.optional) {
throw new Error("For not all values in the array " + data.val +
" is the property " + forChild.val + " defined" +
getOriginalFunctionName(new Error()));
}
}
else if (!checkArrayChildType(data, childValue, forChild)) {
return false;
}
}
}
return true;
};
function checkConstraints(data: TypeCheckConfig, value: any): boolean {
if (typeof value === 'number') {
return checkNumberConstraints(data, value);
}
if (Array.isArray(value) && data.forChildren) {
return checkArrayChildrenConstraints(data, value);
}
return true;
};
function typeCheck(args: {
[key: string]: any;
}, toCheck: TypeCheckConfig[]) {
const optionals: {
[key: string]: any;
[key: number]: any;
} = {};
for (var i = 0; i < toCheck.length; i++) {
var data = toCheck[i];
if (!dependencyMet(data, optionals)) {
continue;
}
var value = getDotValue(args, data.val);
var isDef = isDefined(data, value, optionals);
if (isDef === true) {
var matchedType = typesMatch(data, value);
if (matchedType) {
optionals[data.val] = true;
checkConstraints(data, value);
continue;
}
}
else if (isDef === 'continue') {
continue;
}
return false;
}
return true;
};
function checkOnlyCallback(callback: Function, optional: boolean) {
typeCheck({
callback: callback
}, [{
val: 'callback',
type: 'function',
optional: optional
}]);
}
function asyncThrows(fn: () => Promise<any>, regexp: RegExp, message?: string) {
return new Promise((resolve) => {
fn().then(() => {
assert.throws(() => {}, regexp, message);
resolve(null);
}).catch((err) => {
assert.throws(() => {
throw err;
}, regexp, message)
resolve(null);
});
});
}
function asyncDoesNotThrow(fn: () => Promise<any>, message?: string) {
return new Promise((resolve) => {
fn().then(() => {
assert.doesNotThrow(() => {}, message);
resolve(null);
}).catch((err) => {
assert.doesNotThrow(() => {
throw err;
}, message)
resolve(null);
});
});
}
/**
* Asserts that actual contains expected
*
* @type T Type of the objects.
* @param actual Actual value.
* @param expected Potential expected value.
* @param message Message to display on error.
*/
function assertDeepContains<T>(actual: T, expected: Partial<T>, message?: string): void {
//Strip actual of keys that expected does not contain
const actualCopy = JSON.parse(JSON.stringify(actual));
for (const key in actualCopy) {
if (!(key in expected)) {
delete actualCopy[key];
}
}
assert.deepEqual(actualCopy, expected, message);
}
const bgPagePortMessageListeners: ((message: any) => void)[] = [];
const crmAPIPortMessageListeners: ((message: any) => void)[] = [];
const chrome = ({
app: {
getDetails: function() {
return {
version: 2.0
}
}
},
runtime: {
getURL: function (url: string) {
if (url) {
if (url.indexOf('/') === 0) {
url = url.slice(1);
}
return 'chrome-extension://something/' + url;
}
return 'chrome-extension://something/';
},
onConnect: {
addListener: function (fn: (port: _browser.runtime.Port) => void) {
checkOnlyCallback(fn, false);
bgPageConnectListener = fn;
}
},
onMessage: {
addListener: function (fn: (message: any) => void) {
checkOnlyCallback(fn, false);
bgPageOnMessageListener = fn;
}
},
connect: function(extensionId?: string|{
name?: string;
includeTlsChannelId?: boolean;
}, connectInfo?: {
name?: string;
includeTlsChannelId?: boolean;
}) {
if (connectInfo === void 0 && typeof extensionId !== 'string') {
connectInfo = extensionId;
extensionId = void 0;
}
typeCheck({
extensionId: extensionId,
connectInfo: connectInfo
}, [{
val: 'extensionId',
type: 'string',
optional: true
}, {
val: 'connectInfo',
type: 'object',
optional: true
}, {
val: 'connectInfo.name',
type: 'string',
optional: true,
dependency: 'connectInfo'
}, {
val: 'connectInfo.includeTlsChannelId',
type: 'boolean',
optional: true,
dependency: 'connectInfo'
}]);
var idx = bgPagePortMessageListeners.length;
bgPageConnectListener({ //Port for bg page
onMessage: {
addListener: function(fn: (message: any) => void) {
bgPagePortMessageListeners[idx] = fn;
}
},
postMessage: function(message: any) {
crmAPIPortMessageListeners[idx](message);
}
} as any);
return { //Port for crmAPI
onMessage: {
addListener: function(fn: (message: any) => void) {
crmAPIPortMessageListeners[idx] = fn;
}
},
postMessage: function (message: any) {
bgPagePortMessageListeners[idx](message);
}
}
},
getManifest: function() {
return JSON.parse(fs
.readFileSync(path.join(__dirname, '../', './build/manifest.json'), {
encoding: 'utf8'
})
.replace(/\/\*.+\*\//g, ''))
},
openOptionsPage: function() { },
lastError: null,
sendMessage: function(extensionId: string|any, message: any|{
includeTlsChannelId?: boolean;
}, options: {
includeTlsChannelId?: boolean;
}|((value: any) => void), responseCallback: (value: any) => void) {
if (typeof extensionId !== 'string') {
responseCallback = options as (value: any) => void;
options = message;
message = extensionId;
extensionId = void 0;
}
if (typeof options === 'function') {
responseCallback = options;
options = void 0;
}
typeCheck({
extensionId: extensionId,
message: message,
options: options,
responseCallback: responseCallback
}, [{
val: 'extensionId',
type: 'string',
optional: true
}, {
val: 'options',
type: 'object',
optional: true
}, {
val: 'options.includeTlsChannelId',
type: 'boolean',
optional: true,
dependency: 'options'
}, {
val: 'responseCallback',
type: 'function',
optional: true
}]);
},
},
contextMenus: {
create: function(data: _chrome.contextMenus.CreateProperties, callback?: () => void) {
typeCheck({
data: data,
callback: callback
}, [{
val: 'data',
type: 'object'
}, {
val: 'data.type',
type: 'enum',
enum: ['normal', 'checkbox', 'radio', 'separator'],
optional: true
}, {
val: 'data.id',
type: 'string',
optional: true
}, {
val: 'data.title',
type: 'string',
optional: data.type === 'separator'
}, {
val: 'data.checked',
type: 'boolean',
optional: true
}, {
val: 'data.contexts',
type: 'array',
optional: true
}, {
val: 'data.onclick',
type: 'function',
optional: true
}, {
val: 'data.parentId',
type: ['number', 'string'],
optional: true
}, {
val: 'data.documentUrlPatterns',
type: 'array',
optional: true
}, {
val: 'data.targetUrlPatterns',
type: 'array',
optional: true
}, {
val: 'data.enabled',
type: 'boolean',
optional: true
}, {
val: 'callback',
type: 'function',
optional: true
}]);
return 0;
},
update: function(id: number|string, data: _chrome.tabs.UpdateProperties, callback?: () => void) {
typeCheck({
id: id,
data: data,
callback: callback
}, [{
val: 'id',
type: ['number', 'string']
}, {
val: 'data',
type: 'object'
}, {
val: 'data.type',
type: 'enum',
enum: ['normal', 'checkbox', 'radio', 'separator'],
optional: true
}, {
val: 'data.title',
type: 'string',
optional: true
}, {
val: 'data.checked',
type: 'boolean',
optional: true
}, {
val: 'data.contexts',
type: 'array',
optional: true
}, {
val: 'data.onclick',
type: 'function',
optional: true
}, {
val: 'data.parentId',
type: ['number', 'string'],
optional: true
}, {
val: 'data.documentUrlPatterns',
type: 'array',
optional: true
}, {
val: 'data.targetUrlPatterns',
type: 'array',
optional: true
}, {
val: 'data.enabled',
type: 'boolean',
optional: true
}, {
val: 'callback',
type: 'function',
optional: true
}]);
callback && callback();
},
remove: function(id: number|string, callback?: () => void) {
typeCheck({
id: id,
callback: callback
}, [{
val: 'id',
type: ['number', 'string']
}, {
val: 'callback',
type: 'function',
optional: true
}]);
callback();
},
removeAll: function(callback?: () => void) {
checkOnlyCallback(callback, true);
callback();
}
},
commands: {
onCommand: {
addListener: function(listener: () => void) {
checkOnlyCallback(listener, false);
}
},
getAll: function(callback: (commands: any[]) => void) {
checkOnlyCallback(callback, false);
callback([]);
}
},
i18n: {
getAcceptLanguages(callback: (languages: string[]) => void) {
callback(['en', 'en-US']);
},
getMessage(messageName: string, _substitutions?: any): string {
return messageName;
},
getUILanguage(): string {
return 'en';
}
},
tabs: {
onHighlighted: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
onUpdated: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
onRemoved: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
query: function(options: _chrome.tabs.QueryInfo, callback?: (tabs: _chrome.tabs.Tab[]) => void) {
typeCheck({
options: options,
callback: callback
}, [{
val: 'options',
type: 'object'
}, {
val: 'options.tabId',
type: ['number', 'array'],
optional: true
}, {
val: 'options.status',
type: 'enum',
enum: ['loading', 'complete'],
optional: true
}, {
val: 'options.lastFocusedWindow',
type: 'boolean',
optional: true
}, {
val: 'options.windowId',
type: 'number',
optional: true
}, {
val: 'options.windowType',
type: 'enum',
enum: ['normal', 'popup', 'panel', 'app', 'devtools'],
optional: true
}, {
val: 'options.active',
type: 'boolean',
optional: true
}, {
val: 'options.index',
type: 'number',
optional: true
}, {
val: 'options.title',
type: 'string',
optional: true
}, {
val: 'options.url',
type: ['string', 'array'],
optional: true
}, {
val: 'options.currentWindow',
type: 'boolean',
optional: true
}, {
val: 'options.highlighted',
type: 'boolean',
optional: true
}, {
val: 'options.pinned',
type: 'boolean',
optional: true
}, {
val: 'options.audible',
type: 'boolean',
optional: true
}, {
val: 'options.muted',
type: 'boolean',
optional: true
}, {
val: 'options.tabId',
type: ['number', 'array'],
optional: true
}, {
val: 'callback',
type: 'function',
optional: true
}]);
callback([]);
}
},
webRequest: {
onBeforeRequest: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
}
},
management: {
getAll: function(listener: (extensions: any[]) => void) {
listener([]);
},
onInstalled: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
onEnabled: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
onUninstalled: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
onDisabled: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
}
},
notifications: {
onClosed: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
onClicked: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
}
},
permissions: {
getAll: function (callback: (permissions: {
permissions: string[];
}) => void) {
checkOnlyCallback(callback, false);
callback({
permissions: []
});
},
onAdded: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
onRemoved: {
addListener: function (listener: () => void) {
checkOnlyCallback(listener, false);
}
},
},
storage: {
sync: {
get: function (key: string|((value: any) => void), cb?: (value: any) => void) {
if (typeof key === 'function') {
key(storageSync);
} else {
var result: {
[key: string]: any;
} = {};
result[key] = storageSync[key];
cb(result);
}
},
set: function (data: {
[key: string]: any;
}|any, cb?: (data: any) => void) {
for (var objKey in data) {
if (data.hasOwnProperty(objKey)) {
storageSync[objKey] = data[objKey];
}
}
cb && cb(storageSync);
},
clear: function(callback?: () => void) {
for (let key in storageSync) {
delete storageSync[key];
}
callback && callback();
}
},
local: {
get: function (key: string|((value: any) => void), cb?: (value: any) => void) {
if (typeof key === 'function') {
key(storageLocal);
} else {
var result: {
[key: string]: any;
} = {};
result[key] = storageSync[key];
cb(result);
}
},
set: function (data: {
[key: string]: any;
}|any, cb?: (data: any) => void) {
for (var objKey in data) {
if (objKey === 'latestId') {
idChangeListener && idChangeListener({
latestId: {
newValue: data[objKey]
}
});
}
storageLocal[objKey] = data[objKey];
}
cb && cb(storageLocal);
},
clear: function(callback?: () => void) {
for (let key in storageLocal) {
delete storageLocal[key];
}
callback && callback();
}
},
onChanged: {
addListener: function (fn: (change: {
[key: string]: {
oldValue?: any;
newValue?: any;
}
}) => void) {
checkOnlyCallback(fn, false);
idChangeListener = fn;
}
}
}
} as DeepPartial<typeof _chrome>) as typeof _chrome;
let window: GlobalObject & {
XMLHttpRequest: any;
crmAPI: CRM.CRMAPI.Instance;
changelogLog: {
[key: string]: Array<string>;
}
} & {
chrome: typeof chrome,
browser: typeof _browser
};
class GenericNode {
getAttribute() {
return '';
}
cloneNode() {
return new GenericNode()
}
setAttribute () { }
appendChild () {
this.childNodes.push(new GenericNode());
return this;
}
classList = {
add() { }
}
set innerHTML(_val: any) {
this.childNodes.push(new GenericNode());
}
animate() {
return {
onfinish: function () { }
};
}
addEventListener() { }
style = {}
childNodes: GenericNode[] = []
compareDocumentPosition() {}
get firstChild() {
return new GenericNode();
}
get lastChild() {
return new GenericNode();
}
getElementsByTagName() { return [] as any[] }
}
const backgroundPageWindow: GlobalObject & {
XMLHttpRequest: any;
crmAPI: CRM.CRMAPI.Instance;
changelogLog: {
[key: string]: Array<string>;
}
} & {
chrome: typeof chrome,
browser: typeof _browser
} = window = {
HTMLElement: function HTMLElement() {
return {};
},
console: {
log: console.log,
group: function() {},
groupEnd: function() {},
groupCollapsed: function() {}
},
JSON: JSON,
Map: Map,
setTimeout: setTimeout,
setInterval: setInterval,
clearInterval: clearInterval,
md5: function() {
return generateRandomString();
},
addEventListener: function() {},
XMLHttpRequest: xhr,
location: {
href: '',
protocol: 'http://'
},
document: {
querySelector: function() {
return {
classList: {
remove: function() {
}
}
}
},
createElement: function () {
return new GenericNode();
},
createDocumentFragment: function () {
return new GenericNode();
},
addEventListener: function() {},
nodeType: 9,
implementation: {
createHTMLDocument: function() {
return {
body: new GenericNode()
}
}
},
documentElement: new GenericNode(),
childNodes: [new GenericNode()],
createComment: function() {}
},
chrome: chrome
} as any;
console.log('Please make sure you have an internet connection as some tests use XHRs');
describe('Meta', () => {
let changelog: {
[version: string]: string[];
}
step('changelog should be defined', () => {
changelog = require('../app/elements/util/change-log/changelog');
assert.isDefined(changelog, 'changelogLog is defined');
});
step('current manifest version should have a changelog entry', () => {
assert.isDefined(changelog[chrome.runtime.getManifest().version],
'Current manifest version has a changelog entry');
});
});
describe('Conversion', () => {
//@ts-ignore
var Worker = function() {
return {
postMessage: function() {
},
addEventListener: function(){}
}
}
//@ts-ignore
var localStorage = {
getItem: function () { return 'yes'; }
};
describe('Setup', function() {
this.slow(1000);
var backgroundCode: string;
step('should be able to read background.js and its dependencies', () => {
// @ts-ignore
window.localStorage = {
setItem: () => { },
getItem: (key: string) => {
if (key === 'transferToVersion2') {
return false;
}
if (key === 'numberofrows') {
return 0;
}
return undefined;
}
};
assert.doesNotThrow(() => {
backgroundCode = fs.readFileSync(
path.join(__dirname, '../', './build/html/background.js'), {
encoding: 'utf8'
});
}, 'File background.js is readable');
});
//@ts-ignore
var location = {
href: 'test.com'
}
step('background.js should be runnable', () => {
assert.doesNotThrow(() => {
eval(backgroundCode);
}, 'File background.js is executable');
});
step('should be defined', () => {
assert.isDefined(backgroundPageWindow, 'backgroundPage is defined');
});
step('should finish loading', function(done) {
this.timeout(5000);
backgroundPageWindow.backgroundPageLoaded.then(() => {
done();
backgroundPageWindowResolve();
});
});
step('should have a transferCRMFromOld property that is a function', () => {
assert.isDefined(backgroundPageWindow.TransferFromOld.transferCRMFromOld, 'Function is defined');
assert.isFunction(backgroundPageWindow.TransferFromOld.transferCRMFromOld, 'Function is a function');
});
step('should have a generateScriptUpgradeErrorHandler property that is a function', () => {
assert.isDefined(backgroundPageWindow.TransferFromOld.transferCRMFromOld, 'Function is defined');
assert.isFunction(backgroundPageWindow.TransferFromOld.transferCRMFromOld, 'Function is a function');
});
step('generateScriptUpgradeErrorHandler should be overwritable', () => {
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.LegacyScriptReplace.generateScriptUpgradeErrorHandler = () => {
return ((oldScriptErrs: Error[], newScriptErrs: Error[], parseErrors: Error[], errors: Error[][]) => {
if (Array.isArray(errors)) {
if (Array.isArray(errors[0])) {
throw errors[0][0];
}
throw errors[0];
} else if (errors) {
throw errors;
}
if (oldScriptErrs) {
throw oldScriptErrs;
}
if (newScriptErrs) {
throw newScriptErrs;
}
if (parseErrors) {
throw new Error('Error parsing script');
}
}) as any;
};
}, 'generateScriptUpgradeErrorHandler is overwritable');
});
});
describe('Converting CRM', () => {
before((done) => {
backgroundPageWindowDone.then(done);
});
it('should convert an empty crm', (done) => {
var openInNewTab = false;
var oldStorage = createCrmLocalStorage([], false);
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(openInNewTab, oldStorage).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.isArray(result, 'Resulting CRM is an array');
assert.lengthOf(result, 0, 'Resulting CRM is empty');
done();
});
}, 'Converting does not throw an error');
});
const singleLinkBaseCase = [{
name: 'linkname',
type: 'link',
value: [{
url: 'http://www.youtube.com'
}, {
url: 'google.com'
}, {
url: 'badurl'
}]
}] as CRM.LinkNode[];
it('should convert a CRM with one link with openInNewTab false', (done) => {
var openInNewTab = false;
var oldStorage = createCrmLocalStorage(singleLinkBaseCase, false);
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(openInNewTab, oldStorage).then((result) => {
var expectedLinks = singleLinkBaseCase[0].value.map((url) => {
return {
url: url.url,
newTab: openInNewTab
};
});
assert.isDefined(result, 'Result is defined');
assert.isArray(result, 'Resulting CRM is an array');
assert.lengthOf(result, 1, 'Resulting CRM has one child');
assert.isObject(result[0], "Resulting CRM's first (and only) child is an object");
assert.strictEqual(result[0].type, 'link', 'Link has type link');
assert.strictEqual(result[0].name, 'linkname', 'Link has name linkname');
assert.isArray(result[0].value, "Link's value is an array");
// @ts-ignore
assert.lengthOf(result[0].value, 3, "Link's value array has a length of 3");
assert.deepEqual(result[0].value, expectedLinks, "Link's value array should match the expected values");
done();
});
}, 'Converting does not throw an error');
});
it('should convert a CRM with one link with openInNewTab true', (done) => {
var openInNewTab = true;
var oldStorage = createCrmLocalStorage(singleLinkBaseCase, true);
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(openInNewTab, oldStorage).then((result) => {
var expectedLinks = singleLinkBaseCase[0].value.map((url) => {
return {
url: url.url,
newTab: openInNewTab
};
});
assert.isDefined(result, 'Result is defined');
assert.isArray(result, 'Resulting CRM is an array');
assert.lengthOf(result, 1, 'Resulting CRM has one child');
assert.isObject(result[0], "Resulting CRM's first (and only) child is an object");
assert.strictEqual(result[0].type, 'link', 'Link has type link');
assert.strictEqual(result[0].name, 'linkname', 'Link has name linkname');
assert.isArray(result[0].value, "Link's value is an array");
// @ts-ignore
assert.lengthOf(result[0].value, 3, "Link's value array has a length of 3");
assert.deepEqual(result[0].value, expectedLinks, "Link's value array should match the expected values");
done();
});
}, 'Converting does not throw an error');
});
it('should be able to handle spaces in the name', (done) => {
var testName = 'a b c d e f g';
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage(
[mergeObjects(singleLinkBaseCase[0], {
name: testName
})]
)).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.strictEqual(result[0].name, testName, 'Names should match');
done();
});
}, 'Converting does not throw an error');
});
it('should be able to handle newlines in the name', (done) => {
var testName = 'a\nb\nc\nd\ne\nf\ng';
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage(
[mergeObjects(singleLinkBaseCase[0], {
name: testName
})]
)).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.strictEqual(result[0].name, testName, 'Names should match');
done();
});
}, 'Converting does not throw an error');
});
it('should be able to handle quotes in the name', (done) => {
var testName = 'a\'b"c\'\'d""e`f`g';
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage(
[mergeObjects(singleLinkBaseCase[0], {
name: testName
})]
)).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.strictEqual(result[0].name, testName, 'Names should match');
done();
});
}, 'Converting does not throw an error');
});
it('should be able to handle an empty name', (done) => {
var testName = '';
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage(
[mergeObjects(singleLinkBaseCase[0], {
name: testName
})]
)).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.strictEqual(result[0].name, testName, 'Names should match');
done();
});
}, 'Converting does not throw an error');
});
it('should be able to convert an empty menu', (done) => {
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage([{
type: 'menu',
name: 'test-menu',
children: []
}])).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.isArray(result, 'Resulting CRM is an array');
assert.lengthOf(result, 1, 'Resulting CRM has one child');
assert.isObject(result[0], 'Resulting node is an object');
assert.strictEqual(result[0].type, 'menu', 'Resulting node is of type menu');
assert.strictEqual(result[0].name, 'test-menu', "Resulting node's name should match given name");
assert.property(result[0], 'children', 'Resulting node has a children property');
assert.isArray(result[0].children, "Resulting node's children property is an array");
// @ts-ignore
assert.lengthOf(result[0].children, 0, "Resulting node's children array has length 0");
done();
});
}, 'Converting does not throw an error');
});
it('should be able to convert a script with triggers', function(done) {
this.slow(300);
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage([{
type: 'script',
name: 'testscript',
triggers: [{
url: 'google.com'
}, {
url: 'example.com'
}, {
url: 'youtube.com'
}],
value: {
launchMode: 2
}
}])).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.isArray(result, 'Resulting CRM is an array');
assert.lengthOf(result, 1, 'Resulting CRM has one child');
assert.isObject(result[0], 'Resulting node is an object');
assert.strictEqual(result[0].type, 'script', 'Resulting node is of type script');
assert.strictEqual(result[0].name, 'testscript', "Resulting node's name should match given name");
assert.property(result[0], 'triggers', 'Resulting node has a triggers property');
assert.property(result[0].value, 'launchMode', 'Resulting node has a launchMode property');
// @ts-ignore
assert.strictEqual(result[0].value.launchMode, 2, 'Resulting launch mode matches expected');
assert.deepEqual(result[0].triggers, [{
not: false,
url: 'google.com'
}, {
not: false,
url: 'example.com'
}, {
not: false,
url: 'youtube.com'
}], 'Triggers match expected');
done();
});
}, 'Converting does not throw an error');
});
it('should be able to convert a menu with some children with various types', (done) => {
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage([{
type: 'menu',
name: 'test-menu',
children: [{
type: 'divider',
name: 'test-divider'
},
singleLinkBaseCase[0],
singleLinkBaseCase[0],
singleLinkBaseCase[0]
]
}])).then((result: CRM.MenuNode[]) => {
assert.isDefined(result, 'Result is defined');
assert.isArray(result, 'Resulting CRM is an array');
assert.lengthOf(result, 1, 'Resulting CRM has one child');
assert.isObject(result[0], 'Resulting node is an object');
assert.strictEqual(result[0].type, 'menu', 'Resulting node is of type menu');
assert.property(result[0], 'children', 'Resulting node has a children property');
assert.isArray(result[0].children, "Resulting node's children property is an array");
// @ts-ignore
assert.lengthOf(result[0].children, 4, "Resulting node's children array has length 4");
assert.strictEqual(result[0].children[0].type, 'divider', 'First child is a divider');
assert.strictEqual(result[0].children[1].type, 'link', 'second child is a divider');
assert.strictEqual(result[0].children[2].type, 'link', 'Third child is a divider');
assert.strictEqual(result[0].children[3].type, 'link', 'Fourth child is a divider');
done();
});
}, 'Converting does not throw an error');
});
it('should be able to convert a menu which contains menus itself', (done) => {
var nameIndex = 0;
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage([{
type: 'menu',
name: `test-menu${nameIndex++}`,
children: [{
type: 'menu',
name: `test-menu${nameIndex++}`,
children: [{
type: 'menu',
name: `test-menu${nameIndex++}`,
children: [{
type: 'menu',
name: `test-menu${nameIndex++}`,
children: []
}, {
type: 'menu',
name: `test-menu${nameIndex++}`,
children: []
}, {
type: 'menu',
name: `test-menu${nameIndex++}`,
children: []
}, {
type: 'menu',
name: `test-menu${nameIndex++}`,
children: []
}]
}, {
type: 'menu',
name: `test-menu${nameIndex++}`,
children: [{
type: 'menu',
name: `test-menu${nameIndex++}`,
children: []
}, {
type: 'menu',
name: `test-menu${nameIndex++}`,
children: []
}, {
type: 'menu',
name: `test-menu${nameIndex++}`,
children: []
}]
}]
}]
}])).then((result: CRM.MenuNode[]) => {
assert.isDefined(result, 'Result is defined');
assert.isArray(result, 'Result is an array');
assert.lengthOf(result, 1, 'Result only has one child');
assert.isArray(result[0].children, 'First node has a children array');
const firstChild = result[0].children[0] as CRM.MenuNode;
// @ts-ignore
assert.lengthOf(result[0].children, 1, 'First node has only one child');
assert.isArray(firstChild.children, "First node's child has children");
assert.lengthOf(firstChild.children, 2, 'First node\s child has 2 children');
assert.isArray(firstChild.children[0].children, "First node's first child has children");
assert.lengthOf(firstChild.children[0].children as CRM.Node[], 4, "First node's first child has 4 children");
(firstChild.children[0].children as CRM.Node[]).forEach((child: CRM.MenuNode, index) => {
assert.isArray(child.children, `First node's first child's child at index ${index} has children array`);
assert.lengthOf(child.children, 0, `First node's first child's child at index ${index} has 0 children`);
});
assert.isArray(firstChild.children[1].children, "First node's second child has children");
assert.lengthOf(firstChild.children[1].children as CRM.Node[], 3, "First node's second child has 3 children");
(firstChild.children[1].children as CRM.Node[]).forEach((child: CRM.MenuNode, index) => {
assert.isArray(child.children, `First node's first child's child at index ${index} has children array`);
assert.lengthOf(child.children, 0, `First node's first child's child at index ${index} has 0 children`);
});
done();
});
}, 'Converting does not throw an error');
});
});
describe('Converting Scripts', function() {
this.slow(1000);
before((done) => {
backgroundPageWindowDone.then(done);
});
var singleScriptBaseCase = {
type: 'script',
name: 'script',
value: {
launchMode: 0,
script: ''
}
};
var SCRIPT_CONVERSION_TYPE = {
CHROME: 0,
LOCAL_STORAGE: 1,
BOTH: 2
}
function testScript(script: string, expected: string|number, testType: number|(() => void), doneFn?: () => void) {
if (typeof expected === 'number') {
doneFn = testType as () => void;
testType = expected;
expected = script;
}
assert.doesNotThrow(() => {
backgroundPageWindow.TransferFromOld.transferCRMFromOld(true,
createCrmLocalStorage(
[mergeObjects(singleScriptBaseCase, {
value: {
script: script
}
} as any)]), testType as number).then((result) => {
assert.isDefined(result, 'Result is defined');
assert.property(result[0], 'value', 'Script has property value');
assert.property(result[0].value, 'script', "Script's value property has a script property");
// @ts-ignore
assert.strictEqual(result[0].value.script, expected);
doneFn();
}).catch((e) => {
throw e;
});
}, 'Converting does not throw an error');
}
describe('Converting LocalStorage', function() {
it('should be able to convert a multiline script with indentation with no localStorage-calls', (done) => {
testScript(`
console.log('hi')
var x
if (true) {
x = (true ? 1 : 2)
} else {
x = 5
}
console.log(x);`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should not convert a script when it doesn\'t have execute locally', (done) => {
var msg = `var x = localStorage;`;
testScript(msg, msg, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with a simple reference to localStorage', (done) => {
testScript(
`/*execute locally*/
var x = localStorage;`,
`var x = localStorageProxy;`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with a simple reference to window.localStorage', (done) => {
testScript(
`/*execute locally*/
var x = window.localStorage;`,
`var x = window.localStorageProxy;`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with a call to getItem', (done) => {
testScript(
`/*execute locally*/
var x = localStorage.getItem('a');`,
`var x = localStorageProxy.getItem('a');`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with a call to setItem', (done) => {
testScript(`/*execute locally*/
var x = localStorage.getItem('a', 'b');`,
`var x = localStorageProxy.getItem('a', 'b');`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with a call to clear', (done) => {
testScript(
`/*execute locally*/
var x = localStorage.clear();`,
`var x = localStorageProxy.clear();`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with a proxied call to a getItem', (done) => {
testScript(
`/*execute locally*/
var x = localStorage;
var y = x.getItem('b');`,
`var x = localStorageProxy;
var y = x.getItem('b');`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with nested chrome calls', (done) => {
testScript(
`/*execute locally*/
var x = localStorage.setItem(localStorage.getItem('a'), localStorage.getItem('b'));`,
`var x = localStorageProxy.setItem(localStorageProxy.getItem('a'), localStorageProxy.getItem('b'));`,
SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
it('should be able to convert a script with a dot-access', (done) => {
testScript(
`/*execute locally*/
var x = localStorage.a;`,
`var x = localStorageProxy.a;`, SCRIPT_CONVERSION_TYPE.LOCAL_STORAGE, done);
});
});
describe('Converting Chrome', function() {
it('should be able to convert a oneline no-chrome-calls script', (done) => {
testScript('console.log("hi");', SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it('should be able to convert a multiline script with indentation with no chrome-calls', (done) => {
testScript(`
console.log('hi')
var x
if (true) {
x = (true ? 1 : 2)
} else {
x = 5
}
console.log(x);`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it('should be able to convert a single-line script with a callback chrome-call', (done) => {
testScript(`
chrome.runtime.getPlatformInfo(function(platformInfo) {
console.log(platformInfo);
});`, `
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
console.log(platformInfo);
}).send();`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it('should be able to convert nested chrome-calls', (done) => {
testScript(`
chrome.runtime.getPlatformInfo(function(platformInfo) {
console.log(platformInfo);
chrome.runtime.getPlatformInfo(function(platformInfo) {
console.log(platformInfo);
chrome.runtime.getBackgroundPage(function(bgPage) {
console.log(bgPage);
});
});
});`, `
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
console.log(platformInfo);
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
console.log(platformInfo);
window.crmAPI.chrome('runtime.getBackgroundPage')(function(bgPage) {
console.log(bgPage);
}).send();
}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it('should be able to convert chrome functions returning to a variable', (done) => {
testScript(`
var url = chrome.runtime.getURL();
console.log(url);`, `
window.crmAPI.chrome('runtime.getURL').return(function(url) {
console.log(url);
}).send();`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it('should be able to convert multiple chrome functions returning to variables', (done) => {
testScript(`
var url = chrome.runtime.getURL();
var manifest = chrome.runtime.getManifest();
var url2 = chrome.runtime.getURL('/options.html');`, `
window.crmAPI.chrome('runtime.getURL').return(function(url) {
window.crmAPI.chrome('runtime.getManifest').return(function(manifest) {
window.crmAPI.chrome('runtime.getURL')('/options.html').return(function(url2) {
}).send();
}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it('should be able to convert mixed chrome function calls', (done) => {
testScript(`
var url = chrome.runtime.getURL();
var manifest = chrome.runtime.getManifest();
var somethingURL = chrome.runtime.getURL(manifest.something);
chrome.runtime.getPlatformInfo(function(platformInfo) {
var platformURL = chrome.runtime.getURL(platformInfo.os);
});`, `
window.crmAPI.chrome('runtime.getURL').return(function(url) {
window.crmAPI.chrome('runtime.getManifest').return(function(manifest) {
window.crmAPI.chrome('runtime.getURL')(manifest.something).return(function(somethingURL) {
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
window.crmAPI.chrome('runtime.getURL')(platformInfo.os).return(function(platformURL) {
}).send();
}).send();
}).send();
}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it('should be able to convert chrome calls in if statements', (done) => {
testScript(`
if (true) {
var url = chrome.runtime.getURL('something');
console.log(url);
} else {
var url2 = chrome.runtime.getURL('somethingelse');
console.log(url2);
}`, `
if (true) {
window.crmAPI.chrome('runtime.getURL')('something').return(function(url) {
console.log(url);
}).send();
} else {
window.crmAPI.chrome('runtime.getURL')('somethingelse').return(function(url2) {
console.log(url2);
}).send();
}`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
it("should be able to convert chrome calls that aren't formatted nicely", (done) => {
testScript(`
var x = chrome.runtime.getURL('something');x = x + 'foo';chrome.runtime.getBackgroundPage(function(bgPage){console.log(x + bgPage);});`, `
window.crmAPI.chrome('runtime.getURL')('something').return(function(x) {x = x + 'foo';window.crmAPI.chrome('runtime.getBackgroundPage')(function(bgPage){console.log(x + bgPage);}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.CHROME, done);
});
});
describe('Converting LocalStorage and Chrome', function() {
it('should be able to convert a oneline normal script', (done) => {
var scr = 'console.log("hi");';
testScript(scr, scr, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it('should be able to convert a multiline script with indentation with no chrome-calls', (done) => {
testScript(`
/*execute locally*/
console.log('hi')
var x
if (true) {
x = (true ? localStorage.getItem('1') : localStorage.getItem('2'))
} else {
x = 5
}
console.log(x);`, `
console.log('hi')
var x
if (true) {
x = (true ? localStorageProxy.getItem('1') : localStorageProxy.getItem('2'))
} else {
x = 5
}
console.log(x);`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it('should be able to convert a single-line script with a callback chrome-call', (done) => {
testScript(`
/*execute locally*/
chrome.runtime.getPlatformInfo(function(platformInfo) {
console.log(platformInfo, localStorage.getItem('x'));
});`, `
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
console.log(platformInfo, localStorageProxy.getItem('x'));
}).send();`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it('should be able to convert nested chrome-calls', (done) => {
testScript(`
/*execute locally*/
chrome.runtime.getPlatformInfo(function(platformInfo) {
console.log(platformInfo);
localStorage.clear();
chrome.runtime.getPlatformInfo(function(platformInfo) {
console.log(platformInfo);
localStorage.setItem('x', platformInfo);
chrome.runtime.getBackgroundPage(function(bgPage) {
localStorage.clear();
console.log(bgPage);
});
});
});`, `
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
console.log(platformInfo);
localStorageProxy.clear();
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
console.log(platformInfo);
localStorageProxy.setItem('x', platformInfo);
window.crmAPI.chrome('runtime.getBackgroundPage')(function(bgPage) {
localStorageProxy.clear();
console.log(bgPage);
}).send();
}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it('should be able to convert chrome functions returning to a variable', (done) => {
testScript(`
/*execute locally*/
var url = chrome.runtime.getURL();
localStorage.setItem('a', url);`, `
window.crmAPI.chrome('runtime.getURL').return(function(url) {
localStorageProxy.setItem('a', url);
}).send();`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it('should be able to convert multiple chrome functions returning to variables', (done) => {
testScript(`
/*execute locally*/
var url = chrome.runtime.getURL();
var manifest = chrome.runtime.getManifest();
var url2 = chrome.runtime.getURL('/options.html');
localStorage.setItem('a', url);`, `
window.crmAPI.chrome('runtime.getURL').return(function(url) {
window.crmAPI.chrome('runtime.getManifest').return(function(manifest) {
window.crmAPI.chrome('runtime.getURL')('/options.html').return(function(url2) {
localStorageProxy.setItem('a', url);
}).send();
}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it('should be able to convert mixed chrome function calls', (done) => {
testScript(`
/*execute locally*/
var url = chrome.runtime.getURL();
var manifest = chrome.runtime.getManifest();
localStorage.setItem('a', 'b');
var somethingURL = chrome.runtime.getURL(manifest.something);
chrome.runtime.getPlatformInfo(function(platformInfo) {
var platformURL = chrome.runtime.getURL(platformInfo.os);
localStorage.clear();
});`, `
window.crmAPI.chrome('runtime.getURL').return(function(url) {
window.crmAPI.chrome('runtime.getManifest').return(function(manifest) {
localStorageProxy.setItem('a', 'b');
window.crmAPI.chrome('runtime.getURL')(manifest.something).return(function(somethingURL) {
window.crmAPI.chrome('runtime.getPlatformInfo')(function(platformInfo) {
window.crmAPI.chrome('runtime.getURL')(platformInfo.os).return(function(platformURL) {
localStorageProxy.clear();
}).send();
}).send();
}).send();
}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it('should be able to convert chrome calls in if statements', (done) => {
testScript(`
/*execute locally*/
if (true) {
var url = chrome.runtime.getURL('something');
console.log(localStorage.getItem(url));
} else {
var url2 = chrome.runtime.getURL('somethingelse');
console.log(localStorage.getItem(url2));
}`, `
if (true) {
window.crmAPI.chrome('runtime.getURL')('something').return(function(url) {
console.log(localStorageProxy.getItem(url));
}).send();
} else {
window.crmAPI.chrome('runtime.getURL')('somethingelse').return(function(url2) {
console.log(localStorageProxy.getItem(url2));
}).send();
}`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
it("should be able to convert chrome calls that aren't formatted nicely", (done) => {
testScript(`
/*execute locally*/
var x = chrome.runtime.getURL('something');x = x + localStorage.getItem('foo');chrome.runtime.getBackgroundPage(function(bgPage){console.log(x + bgPage);});`, `
window.crmAPI.chrome('runtime.getURL')('something').return(function(x) {x = x + localStorageProxy.getItem('foo');window.crmAPI.chrome('runtime.getBackgroundPage')(function(bgPage){console.log(x + bgPage);}).send();
}).send();`, SCRIPT_CONVERSION_TYPE.BOTH, done);
});
});
});
});
var bgPageOnMessageListener: (message: any, sender: any, respond: (response: any) => void) => void;
describe('CRMAPI', () => {
step('default settings should be set', () => {
assert.deepEqual(storageLocal, {
CRMOnPage: false,
editCRMInRM: true,
nodeStorage: {},
resourceKeys: [],
resources: {},
updatedScripts: [],
settings: null,
urlDataPairs: {},
useStorageSync: true,
requestPermissions: [],
editing: null,
selectedCrmType: [true, true, true, true, true, true],
hideToolsRibbon: false,
isTransfer: true,
shrinkTitleRibbon: false,
useAsUserscriptInstaller: true,
useAsUserstylesInstaller: true,
jsLintGlobals: ['window', '$', 'jQuery', 'crmAPI'],
globalExcludes: [''],
lang: 'en',
lastUpdatedAt: JSON.parse(fs.readFileSync(
path.join(__dirname, '../', './build/manifest.json'), {
encoding: 'utf8'
}).replace(/\/\*.+\*\//g, '')).version,
catchErrors: true,
notFirstTime: true,
authorName: 'anonymous',
showOptions: true,
recoverUnsavedData: false,
libraries: [],
settingsVersionData: {
current: storageLocal.settingsVersionData.current,
latest: storageLocal.settingsVersionData.latest,
wasUpdated: false
}
}, 'default settings are set');
});
step('should be able to set a new CRM', () => {
return new Promise((resolve) => {
assert.doesNotThrow(() => {
bgPageOnMessageListener({
type: 'updateStorage',
data: {
type: 'optionsPage',
localChanges: false,
settingsChanges: [{
key: 'crm',
oldValue: (JSON.parse(storageSync['section0']) as CRM.SettingsStorage).crm,
newValue: testCRMTree
}]
}
}, {}, () => {
resolve(null);
});
}, 'CRM is changable through runtime messaging');
});
});
step('should be able to keep a CRM in persistent storage', () => {
assert.deepEqual({
section0: JSON.parse(storageSync.section0),
indexes: storageSync.indexes
}, {
section0: {
"editor": {
"cssUnderlineDisabled": false,
"disabledMetaDataHighlight": false,
"keyBindings": {
"goToDef": "Alt-.",
"rename": "Ctrl-Q",
},
"theme": "dark",
"zoom": "100"
},
"crm": [{
"name": "menu",
"onContentTypes": [true, true, true, true, true, true],
"type": "menu",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": null,
"id": 0,
"path": [0],
"index": 0,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"children": [],
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: [],
nodeInfo: {
permissions: []
}
}, {
"name": "link",
"onContentTypes": [true, true, true, false, false, false],
"type": "link",
"showOnSpecified": true,
"triggers": [{
"url": "*://*.example.com/*",
"not": true
}, {
"url": "www.google.com",
"not": false
}],
"isLocal": true,
"value": [{
"url": "https://www.google.com",
"newTab": true
}, {
"url": "www.youtube.com",
"newTab": false
}],
"id": 1,
"path": [1],
"index": 1,
children: null,
linkVal: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: [],
nodeInfo: {
permissions: []
}
}, {
"name": "script",
"onContentTypes": [true, true, true, false, false, false],
"type": "script",
"showOnSpecified": false,
"isLocal": true,
"value": {
"launchMode": 0,
"backgroundLibraries": [],
"libraries": [],
"script": "// ==UserScript==\n// @name\tscript\n// @CRM_contentTypes\t[true, true, true, false, false, false]\n// @CRM_launchMode\t2\n// @grant\tnone\n// @match\t*://*.google.com/*\n// @exclude\t*://*.example.com/*\n// ==/UserScript==\nconsole.log('Hello');",
"backgroundScript": "",
"metaTags": {
"name": ["script"],
"CRM_contentTypes": ["[true, true, true, false, false, false]"],
"CRM_launchMode": ["2"],
"grant": ["none"],
"match": ["*://*.google.com/*"],
"exclude": ["*://*.example.com/*"]
},
"options": {},
ts: {
enabled: false,
script: { },
backgroundScript: {}
}
},
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": false
}, {
"url": "*://*.google.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": true
}],
"id": 2,
"path": [2],
"index": 2,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"nodeInfo": {
"permissions": []
},
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
}, {
"name": "stylesheet",
"onContentTypes": [true, true, true, false, false, false],
"type": "stylesheet",
"showOnSpecified": false,
"isLocal": true,
"value": {
"stylesheet": "/* ==UserScript==\n// @name\tstylesheet\n// @CRM_contentTypes\t[true, true, true, false, false, false]\n// @CRM_launchMode\t3\n// @CRM_stylesheet\ttrue\n// @grant\tnone\n// @match\t*://*.example.com/*\n// ==/UserScript== */\nbody {\n\tbackground-color: red;\n}",
"launchMode": 0,
"toggle": true,
"defaultOn": true,
"options": {},
convertedStylesheet: {
options: '',
stylesheet: ''
}
},
"id": 3,
"path": [3],
"index": 3,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"nodeInfo": {
permissions: []
},
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
}, {
"name": "divider",
"onContentTypes": [true, true, true, false, false, false],
"type": "divider",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": null,
"id": 4,
"path": [4],
"index": 4,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
nodeInfo: {
permissions: []
},
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
}, {
"name": "menu",
"onContentTypes": [true, true, true, false, false, false],
"type": "menu",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": null,
"id": 5,
"path": [5],
"index": 5,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"children": [{
"name": "lots of links",
"onContentTypes": [true, true, true, false, false, false],
"type": "link",
"showOnSpecified": false,
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}],
"isLocal": true,
"value": [{
"url": "https://www.example.com",
"newTab": true
}, {
"url": "www.example.com",
"newTab": true
}, {
"url": "www.example.com",
"newTab": false
}, {
"url": "www.example.com",
"newTab": true
}, {
"url": "www.example.com",
"newTab": true
}],
"id": 6,
"path": [5, 0],
"index": 0,
nodeInfo: {
permissions: []
},
linkVal: null,
children: null,
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
}],
nodeInfo: {
permissions: []
},
scriptVal: null,
stylesheetVal: null,
menuVal: null,
permissions: []
}],
nodeStorageSync: {},
"latestId": (JSON.parse(storageSync.section0) as CRM.SettingsStorage).latestId,
"settingsLastUpdatedAt": (JSON.parse(storageSync.section0) as CRM.SettingsStorage).settingsLastUpdatedAt,
"rootName": "Custom Menu"
},
indexes: 1
});
});
var crmAPICode: string;
step('should be able to read crmapi.js', () => {
assert.doesNotThrow(() => {
crmAPICode = fs.readFileSync(
path.join(__dirname, '../', './build/js/crmapi.js'), {
encoding: 'utf8'
});
}, 'File crmapi.js is readable');
});
step('crmapi.js should be runnable', () => {
assert.doesNotThrow(() => {
eval(crmAPICode);
}, 'File crmapi.js is executable');
});
var crmAPI: CRMAPI;
var nodeStorage: any;
var usedKeys: {
[usedKey: string]: boolean;
} = {};
var crmAPIs: CRMAPI[] = [];
var createSecretKey = (): number[] => {
var key = [];
var i;
for (i = 0; i < 25; i++) {
key[i] = Math.round(Math.random() * 100);
}
var joined = key.join(',');
if (!usedKeys[joined]) {
usedKeys[joined] = true;
return key;
} else {
return createSecretKey();
}
}
var greaseMonkeyData: CRM.CRMAPI.GreaseMonkeyData = {
info: {
testKey: createSecretKey()
},
resources: {
[generateRandomString()]: {
crmUrl: generateRandomString(),
dataString: generateRandomString()
},
[generateRandomString()]: {
crmUrl: generateRandomString(),
dataString: generateRandomString()
},
[generateRandomString()]: {
crmUrl: generateRandomString(),
dataString: generateRandomString()
}
},
[Math.round(Math.random() * 100)]: Math.round(Math.random() * 100),
[Math.round(Math.random() * 100)]: Math.round(Math.random() * 100),
[Math.round(Math.random() * 100)]: Math.round(Math.random() * 100),
[Math.round(Math.random() * 100)]: Math.round(Math.random() * 100),
[Math.round(Math.random() * 100)]: Math.round(Math.random() * 100)
} as any;
const TAB_ID = 0;
const NODE_ID = 2 as CRM.GenericNodeId;
const NODE_NAME = "script";
describe('setup', function() {
var node = {
"name": NODE_NAME,
"onContentTypes": [true, true, true, false, false, false],
"type": "script",
"showOnSpecified": false,
"isLocal": true,
"children": null,
"menuVal": null,
"stylesheetVal": null,
"scriptVal": null,
"permissions": [],
"value": {
"launchMode": 0,
"backgroundLibraries": [],
"libraries": [],
"script": "// ==UserScript==\n// @name\tscript\n// @CRM_contentTypes\t[true, true, true, false, false, false]\n// @CRM_launchMode\t2\n// @grant\tnone\n// @match\t*://*.google.com/*\n// @exclude\t*://*.example.com/*\n// ==/UserScript==\nconsole.log('Hello');",
"backgroundScript": "",
"metaTags": {
"name": ["script"],
"CRM_contentTypes": ["[true, true, true, false, false, false]"],
"CRM_launchMode": ["2"],
"grant": ["none"],
"match": ["*://*.google.com/*"],
"exclude": ["*://*.example.com/*"]
},
"options": {},
"ts": {
"enabled": false,
"script": {},
"backgroundScript": {}
}
},
"id": NODE_ID as CRM.GenericNodeId,
"path": [2],
"index": 2,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"nodeInfo": {
"permissions": []
},
"triggers": [{
"url": "*://*.google.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": true
}, {
"url": "*://*.google.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": true
}]
} as CRM.ScriptNode;
var tabData: CRM.CRMAPI.TabData = {id: TAB_ID, testKey: createSecretKey()} as any;
var clickData = {selection: 'some text', testKey: createSecretKey()};
nodeStorage = {testKey: createSecretKey()};
var secretKey = createSecretKey();
step('CrmAPIInit class can be created', () => {
let result;
assert.doesNotThrow(() => {
window.globals.crmValues.tabData.get(0).nodes.set(node.id, [{
secretKey: secretKey,
usesLocalStorage: false
}]);
window.globals.availablePermissions = ['sessions'];
window.globals.crm.crmById.set(2 as CRM.GenericNodeId, node);
//Actual code
var code = 'new (window._crmAPIRegistry.pop())(' +
[node, node.id, tabData, clickData, secretKey, nodeStorage,
{}, greaseMonkeyData, false, {}, true, 0, 'abcdefg', 'chrome,browser']
.map(function(param) {
if (param === void 0) {
return JSON.stringify(null);
}
return JSON.stringify(param);
}).join(', ') + ');';
result = eval(code);
}, 'CrmAPIInit class can be initialized');
assert.isDefined(result);
crmAPI = result;
});
step('crmapi should finish loading', function (done) {
this.timeout(5000);
// @ts-ignore
crmAPI.onReady(() => {
done();
});
});
step('stackTraces can be turned off', () => {
assert.doesNotThrow(() => {
crmAPI.stackTraces = false;
}, 'setting stacktraces to false does not throw');
});
step('should correctly return its arguments on certain calls', () => {
assert.deepEqual(crmAPI.getNode(), node, 'crmAPI.getNode works');
assert.deepEqual(crmAPI.getNode().id, node.id, 'crmAPI.getNode id matches');
assert.deepEqual(crmAPI.tabId, tabData.id, 'tab ids match');
assert.deepEqual(crmAPI.getTabInfo(), tabData, 'tabData matches');
// @ts-ignore
assert.deepEqual(crmAPI.getClickInfo(), clickData, 'clickData matches');
assert.deepEqual(crmAPI.GM.GM_info(), greaseMonkeyData.info, 'greaseMonkey info matches');
assert.deepEqual(window.GM_info(), greaseMonkeyData.info, 'greaseMonkey API\'s are executable through GM_...');
});
});
describe('Comm', () => {
var tabIds: number[] = [];
step('exists', () => {
assert.isObject(crmAPI.comm, 'comm API is an object');
});
step('should be able to set up other instances', async function () {
this.timeout(1500);
this.slow(1000);
function setupInstance(tabId: number): Promise<CRMAPI> {
return new Promise((resolve) => {
//First run crmapi.js
assert.doesNotThrow(() => {
eval(crmAPICode);
}, 'File crmapi.js is executable');
var node = {
"name": "script",
"onContentTypes": [true, true, true, false, false, false],
"type": "script",
"showOnSpecified": false,
"isLocal": true,
"value": {
"launchMode": 0,
"backgroundLibraries": [],
"libraries": [],
"script": "// ==UserScript==\n// @name\tscript\n// @CRM_contentTypes\t[true, true, true, false, false, false]\n// @CRM_launchMode\t2\n// @grant\tnone\n// @match\t*://*.google.com/*\n// @exclude\t*://*.example.com/*\n// ==/UserScript==\nconsole.log('Hello');",
"backgroundScript": "",
"triggers": [{
"url": "*://*.example.com/*",
"not": false
}, {
"url": ["*://*.example.com/*"],
"not": false
}, {
"url": ["*://*.google.com/*"],
"not": false
}, {
"url": ["*://*.example.com/*"],
"not": true
}],
"metaTags": {
"name": ["script"],
"CRM_contentTypes": ["[true, true, true, false, false, false]"],
"CRM_launchMode": ["2"],
"grant": ["none"],
"match": ["*://*.google.com/*"],
"exclude": ["*://*.example.com/*"]
},
options: {},
ts: {
script: {},
backgroundScript: {},
enabled: false
}
},
"id": 2 as CRM.GenericNodeId,
"expanded": false,
"path": [2],
"index": 2,
"linkVal": [{
"newTab": true,
"url": "https://www.example.com"
}],
"nodeInfo": {
"permissions": []
},
"triggers": [{
"url": "*://*.google.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": true
}, {
"url": "*://*.google.com/*",
"not": false
}, {
"url": "*://*.example.com/*",
"not": true
}],
children: null,
menuVal: null,
stylesheetVal: null,
scriptVal: null,
permissions: [],
} as CRM.ScriptNode;
var createSecretKey = (): number[] => {
var key = [];
var i;
for (i = 0; i < 25; i++) {
key[i] = Math.round(Math.random() * 100);
}
const joined = key.join(',')
if (!usedKeys[joined]) {
usedKeys[joined] = true;
return key;
} else {
return createSecretKey();
}
}
var tabData = {id: tabId, testKey: createSecretKey()};
var clickData = {selection: 'some text', testKey: createSecretKey()};
var greaseMonkeyData = {
info: {
testKey: createSecretKey()
}
};
var secretKey = createSecretKey();
assert.doesNotThrow(() => {
window.globals.crmValues.tabData.set(tabId, {
nodes: new Map(),
libraries: new Map()
});
window.globals.crmValues.tabData.get(tabId).nodes.set(node.id,
window.globals.crmValues.tabData.get(tabId).nodes.get(node.id) || []);
window.globals.crmValues.tabData.get(tabId).nodes.get(node.id).push({
secretKey: secretKey,
usesLocalStorage: false
});
//Actual code
var code = 'new (window._crmAPIRegistry.pop())(' +
[node, node.id, tabData, clickData, secretKey, {
testKey: createSecretKey() }, {}, greaseMonkeyData, false, {}, false,
window.globals.crmValues.tabData.get(tabId).nodes.get(node.id).length - 1,
'abcdefg', 'browser,chrome']
.map(function(param) {
if (param === void 0) {
return JSON.stringify(null);
}
return JSON.stringify(param);
}).join(', ') +
');';
const instance = eval(code);
instance.onReady(() => {
resolve(instance);
});
}, 'CrmAPIInit class can be initialized');
});
}
for (var i = 0; i < 5; i++) {
var num;
while (tabIds.indexOf((num = (Math.floor(Math.random() * 500)) + 1)) > -1) { }
tabIds.push(num);
}
for (const tabId of tabIds) {
crmAPIs.push(await setupInstance(tabId));
}
});
step('getInstances()', async () => {
const instances = await crmAPI.comm.getInstances();
assert.isArray(instances, 'comm.getInstances in an array');
for (const { id } of instances) {
assert.isNumber(id, 'instance ID is a number');
assert.include(tabIds, id, 'instance ID matches expected');
};
});
var listeners: ((message: any) => void)[] = [];
var listenerRemovals: number[] = [];
var listenersCalled: number[] = [];
var expectedMessageValue = generateRandomString();
function setupListener(i: number) {
var idx = i;
var fn = function(message: any) {
if (expectedMessageValue !== message.key) {
throw new Error(`Received value ${message.key} did not match ${expectedMessageValue}`);
}
listenersCalled[idx]++;
}
listenersCalled[idx] = 0;
listeners.push(fn);
assert.doesNotThrow(() => {
var num = crmAPIs[idx].comm.addListener(fn);
listenerRemovals.push(num);
}, 'adding listeners does not throw');
}
step('#addListener() setup', () => {
assert.isAtLeast(crmAPIs.length, 1, 'at least one API was registered');
for (var i = 0; i < crmAPIs.length; i++) {
setupListener(i);
}
});
step('#sendMessage()', async () => {
//Send a message from the main CRM API used for testingRunning
const instances = await crmAPI.comm.getInstances();
for (const instance of instances) {
crmAPI.comm.sendMessage(instance, {
key: expectedMessageValue
});
}
});
step('#getInstances[].sendMessage()', async () => {
const instances = await crmAPI.comm.getInstances();
for (const instance of instances) {
instance.sendMessage({
key: expectedMessageValue
});
}
});
step('#addListener()', () => {
for (var i = 0; i < listenersCalled.length; i++) {
assert.strictEqual(listenersCalled[i], 2, 'instances got called twice');
}
});
step('#removeListener()', (done) => {
assert.doesNotThrow(() => {
for (var i = 0 ; i < listeners.length; i++) {
if (Math.floor(Math.random() * 2) === 0) {
crmAPIs[i].comm.removeListener(listeners[i]);
} else {
crmAPIs[i].comm.removeListener(listenerRemovals[i]);
}
}
}, 'calling removeListener works');
//Send another message to test
crmAPI.comm.getInstances(function(instances) {
for (var i = 0; i < instances.length; i++) {
instances[i].sendMessage({
key: expectedMessageValue
});
}
for (var i = 0; i < listenersCalled.length; i++) {
assert.strictEqual(listenersCalled[i], 2, 'instances got called while removed');
}
done();
});
});
});
describe('CRM', () => {
describe('#getRootContextMenuId()', () => {
it('should return the root context menu id', async () => {
const rootId = await crmAPI.crm.getRootContextMenuId();
assert.strictEqual(rootId, window.globals.crmValues.rootId,
'root id matches expected');
});
});
describe('#getTree()', () => {
it('should return the crm subtree', async () => {
const tree = await crmAPI.crm.getTree();
assert.isDefined(tree, 'result is defined');
assert.isArray(tree, 'tree has the form of an array');
assert.deepEqual(tree, safeTestCRMTree, 'tree matches the expected CRM tree');
});
});
describe('#getSubTree()', () => {
it('should return a subtree when given a correct id', async () => {
const subTree = await crmAPI.crm.getSubTree(testCRMTree[5].id);
assert.isDefined(subTree, 'resulting subtree is defined');
assert.isArray(subTree, 'subTree is an array');
assert.deepEqual(subTree, [safeTestCRMTree[5]], 'tree matches expected subtree');
});
it('should throw an error when given a non-existing id', async () => {
crmAPI.stackTraces = false;
await asyncThrows(() => {
return crmAPI.crm.getSubTree(999);
}, /There is no node with id ([0-9]+)/);
});
it('should throw an error when given a non-number parameter', async () => {
crmAPI.stackTraces = false;
await asyncThrows(() => {
// @ts-ignore
return crmAPI.crm.getSubTree('string');
}, /No nodeId supplied/);
})
});
describe('#getNode()', () => {
it('should return a node when given a correct id', async () => {
for (const testNode of safeTestCRMTree) {
const node = await crmAPI.crm.getNode(testNode.id);
assert.isDefined(node, 'resulting node is defined');
assert.isObject(node, 'resulting node is an object');
assert.deepEqual(node, testNode, 'node is equal to expected node');
}
});
it('should throw an error when giving a non-existing node id', async () => {
await asyncThrows(() => {
return crmAPI.crm.getNode(999);
}, /There is no node with id ([0-9]+)/);
});
});
describe('#getNodeIdFromPath()', () => {
it('should return the correct path when given a correct id', async () => {
for (const safeNode of safeNodes) {
const nodeId = await crmAPI.crm.getNodeIdFromPath(safeNode.path);
assert.isDefined(nodeId, 'resulting nodeId is defined');
assert.isNumber(nodeId, 'resulting nodeId is an object');
assert.strictEqual(nodeId, safeNode.id, 'nodeId matches expected nodeId');
}
});
it('should return an error when given a non-existing path', async () => {
await asyncThrows(() => {
return crmAPI.crm.getNodeIdFromPath([999,999,999]);
}, /Path does not return a valid value/);
});
});
describe('#queryCrm()', () => {
it('should return everything when query is empty', async () => {
const results = await crmAPI.crm.queryCrm({});
assert.isDefined(results, 'results is defined');
assert.isArray(results, 'query result is an array');
assert.sameDeepMembers(results, safeNodes, 'both arrays have the same members');
});
it('should return all nodes matching queried name', async () => {
for (const safeNode of safeNodes) {
const results = await crmAPI.crm.queryCrm({
name: safeNode.name
});
assert.isDefined(results, 'results are defined');
assert.isArray(results, 'results are in an array');
var found = false;
for (var i = 0; i < results.length; i++) {
var errorred = false;
try {
assert.deepEqual(results[i], safeNode);
} catch(e) {
errorred = true;
}
if (!errorred) {
found = true;
}
}
assert.isTrue(found, 'expected node is in the results array');
}
});
it('should return all nodes matching type', async () => {
var types: CRM.NodeType[] = ['link','script','menu','stylesheet','divider'];
for (const type of types) {
const results = await crmAPI.crm.queryCrm({
type: type
});
assert.isDefined(results, 'results are defined');
assert.isArray(results, 'results are in an array');
assert.deepEqual(results, safeNodes.filter((node) => {
return node.type === type;
}), 'results match results of given type');
};
});
it('should return all nodes in given subtree', async () => {
const results = await crmAPI.crm.queryCrm({
inSubTree: safeTestCRMTree[5].id
});
assert.isDefined(results, 'results are defined');
assert.isArray(results, 'results are in an array');
var expected: CRM.SafeNode[] = [];
function flattenCrm(obj: CRM.SafeNode) {
expected.push(obj);
if ((obj as CRM.SafeMenuNode).children) {
(obj as CRM.SafeMenuNode).children.forEach(function(child) {
flattenCrm(child);
});
}
}
safeTestCRMTree[5].children.forEach(flattenCrm);
assert.deepEqual(results, expected, 'results match results of given type');
});
});
describe('#getParentNode()', () => {
it('should return the parent when given a valid node', async () => {
const parent = await crmAPI.crm.getParentNode(safeTestCRMTree[5].children[0].id);
assert.isDefined(parent, 'parent is defined');
assert.isObject(parent, 'parent is an object');
assert.deepEqual(parent, safeTestCRMTree[5], 'parent result matches expected parent');
});
it('should return the root when given a top-level node', async () => {
const parent = await crmAPI.crm.getParentNode(safeTestCRMTree[5].id);
assert.isDefined(parent, 'parent is defined');
assert.isArray(parent, 'parent is an array');
assert.deepEqual(parent, safeTestCRMTree, 'parent result matches full tree');
});
it('should throw an error when given a node that doesn\'t exist', async () => {
await asyncThrows(() => {
return crmAPI.crm.getParentNode(999);
}, /There is no node with the id you supplied \(([0-9]+)\)/);
});
});
describe('#getNodeType()', () => {
it('should return the type of all nodes correctly', async () => {
for (const safeNode of safeNodes) {
const type = await crmAPI.crm.getNodeType(safeNode.id);
assert.isDefined(type, 'type is defined');
assert.isString(type, 'type is a string');
assert.strictEqual(type, safeNode.type, 'type matches expected type');
}
});
});
describe('#getNodeValue()', () => {
it('should return the value of all nodes correctly', async () => {
for (const safeNode of safeNodes) {
const value = await crmAPI.crm.getNodeValue(safeNode.id);
assert.isDefined(value, 'value is defined');
assert.strictEqual(typeof value, typeof safeNode.value, 'value types match');
if (typeof value === 'object') {
assert.deepEqual(value, safeNode.value, 'value matches expected value');
} else {
assert.strictEqual(value, safeNode.value, 'value matches expected value');
}
}
});
});
describe('#createNode()', () => {
it('should correctly return the to-create node', async () => {
window.globals.latestId = 6;
var nodeSettings = {
name: 'testName',
type: 'link',
value: [{
newTab: true,
url: 'http://www.somesite.com'
}],
someBadSettings: {
illegalStuf: 123
}
}
var expected: Partial<CRM.LinkNode> = JSON.parse(JSON.stringify(nodeSettings)) as any;
expected.id = 7 as CRM.NodeId<CRM.LinkNode>;
expected.onContentTypes = [true, true, true, false, false, false];
expected.showOnSpecified = false;
expected.triggers = [{
url: '*://*.example.com/*',
not: false
}];
expected.nodeInfo = {
isRoot: false,
version: '1.0',
permissions: [],
source: 'local'
};
expected.isLocal = true;
expected.path = [6];
delete (expected as any).someBadSettings;
delete expected.isLocal;
const node = await crmAPI.crm.createNode({
name: 'testName',
type: 'link',
value: [{
newTab: true,
url: 'http://www.somesite.com'
}],
//@ts-ignore
someBadSettings: {
illegalStuf: 123
}
});
expected.nodeInfo.installDate = node.nodeInfo.installDate;
expected.nodeInfo.lastUpdatedAt = node.nodeInfo.lastUpdatedAt;
assert.isDefined(node, 'created node is defined');
assert.isObject(node, 'created node is an object');
assert.deepEqual(node, expected as any, 'created node matches expected node');
});
it('should correctly place the node and store it', async () => {
const node = await crmAPI.crm.createNode({
name: 'testName',
type: 'link',
value: [{
newTab: true,
url: 'http://www.somesite.com'
}]
});
assert.isDefined(window.globals.crm.crmById.get(node.id as CRM.GenericNodeId), 'node exists in crmById');
assert.isDefined(window.globals.crm.crmByIdSafe.get(node.id), 'node exists in crmByIdSafe');
assert.isDefined(window.globals.crm.crmTree[node.path[0]], 'node is in the crm tree');
assert.isDefined(window.globals.crm.safeTree[node.path[0]], 'node is in the safe crm tree');
});
});
describe('#copyNode()', () => {
it('should match the copied node', async () => {
var expected = JSON.parse(JSON.stringify(safeTestCRMTree[0]));
expected.id = 9 as CRM.NodeId<CRM.SafeMenuNode>;
expected.path = [8];
expected.nodeInfo = {
permissions: []
}
const copiedNode = await crmAPI.crm.copyNode(safeTestCRMTree[0].id, {});
assert.isDefined(copiedNode, 'copied node is defined');
assert.isObject(copiedNode, 'copied node is an object');
assert.deepEqual(copiedNode, expected, 'copied node matches original');
});
it('should make the changes correctly', async () => {
const copiedNode = await crmAPI.crm.copyNode(safeTestCRMTree[0].id, {
name: 'otherName'
});
assert.isDefined(copiedNode, 'copied node is defined');
assert.isObject(copiedNode, 'copied node is an object');
assert.strictEqual(copiedNode.name, 'otherName', 'name matches changed name');
});
});
describe('#moveNode()', () => {
function assertMovedNode(newNode: CRM.SafeNode,
originalPosition: number,
expectedIndex: number|number[]) {
if (!Array.isArray(expectedIndex)) {
expectedIndex = [expectedIndex];
}
var expectedTreeSize = safeTestCRMTree.length;
if (expectedIndex.length > 1) {
expectedTreeSize--;
}
assert.isDefined(newNode, 'new node is defined');
assert.strictEqual(window.globals.crm.crmTree.length, expectedTreeSize, 'tree size is the same as expected');
assert.deepEqual(newNode.path, expectedIndex, 'node has the wanted position');
assert.deepEqual(newNode,
eval(`window.globals.crm.safeTree[${expectedIndex.join('].children[')}]`),
`newNode is node at path ${expectedIndex}`);
//Set path to expected node as to "exclude" that property
newNode.path = safeTestCRMTree[originalPosition].path;
assert.deepEqual(newNode, safeTestCRMTree[originalPosition], 'node is the same node as before');
}
describe('No Parameters', () => {
it('should move the node to the end if no relation is given', async () => {
await resetTree();
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[0].id, {});
assertMovedNode(newNode, 0, window.globals.crm.safeTree.length - 1);
});
});
describe('firstChild', () => {
beforeEach(async () => {
await resetTree();
});
it('should use root when given no other node', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'firstChild'
});
assertMovedNode(newNode, 2, 0);
});
it('should use passed node when passed a different node', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'firstChild',
node: safeTestCRMTree[0].id
});
assertMovedNode(newNode, 2, [0, 0]);
});
it('should throw an error when passed a non-menu node', async () => {
await asyncThrows(() => {
return crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'firstChild',
node: safeTestCRMTree[2].id
});
}, /Supplied node is not of type "menu"/);
});
});
describe('firstSibling', () => {
beforeEach(async () => {
await resetTree();
});
it('should position it as root\'s first child when given no relative', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'firstSibling',
});
assertMovedNode(newNode, 2, 0);
});
it('should position it as given node\'s first sibling (root)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'firstSibling',
node: safeTestCRMTree[3].id
});
assertMovedNode(newNode, 2, 0);
});
it('should position it as given node\'s first sibling (menu)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'firstSibling',
node: safeTestCRMTree[5].children[0].id
});
assertMovedNode(newNode, 2, [4, 0]);
});
});
describe('lastChild', () => {
beforeEach(async () => {
await resetTree();
});
it('should position it as the root\'s last child when given no relative', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'lastChild'
});
assertMovedNode(newNode, 2, safeTestCRMTree.length - 1);
});
it('should position it as given node\'s last child', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'lastChild',
node: safeTestCRMTree[5].id
});
assertMovedNode(newNode, 2, [4, 1]);
});
it('should thrown an error when given a non-menu node', async () => {
await asyncThrows(() => {
return crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'lastChild',
node: safeTestCRMTree[2].id
});
}, /Supplied node is not of type "menu"/);
});
});
describe('lastSibling', () => {
beforeEach(async () => {
await resetTree();
});
it('should position it as the root\'s last child when given no relative', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'lastSibling'
});
assertMovedNode(newNode, 2, safeTestCRMTree.length - 1);
});
it('should position it as given node\'s last sibling (root)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'lastSibling',
node: safeTestCRMTree[3].id
});
assertMovedNode(newNode, 2, safeTestCRMTree.length - 1);
});
it('should position it as given node\'s last sibling (menu)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'lastSibling',
node: safeTestCRMTree[5].children[0].id
});
assertMovedNode(newNode, 2, [4, 1]);
});
});
describe('before', () => {
beforeEach(async () => {
await resetTree();
});
it('should position it as the root\'s first child when given no relative', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'before'
});
assertMovedNode(newNode, 2, 0);
});
it('should position it before given node (root)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'before',
node: safeTestCRMTree[4].id
});
assertMovedNode(newNode, 2, 3);
});
it('should position it before given node (menu)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'before',
node: safeTestCRMTree[5].children[0].id
});
assertMovedNode(newNode, 2, [4, 0]);
});
});
describe('after', () => {
beforeEach(async () => {
await resetTree();
});
it('should position it as the root\'s last child when given no relative', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'after'
});
assertMovedNode(newNode, 2, safeTestCRMTree.length - 1);
});
it('should position it after given node (root)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'after',
node: safeTestCRMTree[4].id
});
assertMovedNode(newNode, 2, 4);
});
it('should position it before given node (menu)', async () => {
const newNode = await crmAPI.crm.moveNode(safeTestCRMTree[2].id, {
relation: 'after',
node: safeTestCRMTree[5].children[0].id
});
assertMovedNode(newNode, 2, [4, 1]);
});
});
});
describe('#deleteNode()', () => {
beforeEach(async () => {
await resetTree();
});
it('should remove passed node when it\'s a valid node id (root)', async () => {
await Promise.all(safeTestCRMTree.map((node, i) => {
return new Promise((resolve, reject) => {
//Don't remove the current script
if (i !== 2) {
crmAPI.crm.deleteNode(node.id).then(() => {
resolve(null);
}).catch((err) => {
reject(err);
});
} else {
resolve(null);
}
});
}));
assert.lengthOf(window.globals.crm.crmTree, 1, 'crmTree is almost empty');
var crmByIdEntries = 0;
window.globals.crm.crmById.forEach(() => {
crmByIdEntries++;
});
assert.strictEqual(crmByIdEntries, 1, 'crmById is almost empty');
assert.isDefined(window.globals.crm.crmById.get(2 as CRM.GenericNodeId), 'current node is still defined');
assert.isObject(window.globals.crm.crmById.get(2 as CRM.GenericNodeId), 'current node is object');
var comparisonCopy = JSON.parse(JSON.stringify(safeTestCRMTree[2]));
comparisonCopy.path = [0];
assert.deepEqual(window.globals.crm.crmByIdSafe.get(2 as CRM.GenericNodeId), comparisonCopy,
'remaining node matches expected');
});
it('should remove passed node when it\'s a valid node id (menu)', async () => {
await crmAPI.crm.deleteNode(safeTestCRMTree[5].children[0].id);
assert.isUndefined(window.globals.crm.crmById.get(safeTestCRMTree[5].children[0].id as CRM.GenericNodeId),
'removed node is removed from crmById');
assert.isUndefined((window.globals.crm.crmTree[5] as CRM.MenuNode).children[0],
'removed node is removed from crmTree');
// @ts-ignore
assert.lengthOf(window.globals.crm.crmTree[5].children, 0,
'previous container has no more children');
});
it('should throw an error when an invalid node id was passed', async () => {
await asyncThrows(() => {
return crmAPI.crm.deleteNode(999);
}, /There is no node with the id you supplied \(([0-9]+)\)/);
});
});
describe('#editNode()', () => {
beforeEach(async () => {
await resetTree();
});
it('should edit nothing when passed an empty objects argument', async () => {
const newNode = await crmAPI.crm.editNode(safeTestCRMTree[0].id, {});
assert.isDefined(newNode, 'new node is defined');
assert.deepEqual(newNode, safeTestCRMTree[0], 'node matches old node');
});
it('should edit the name when given just the name change option', async () => {
const newNode = await crmAPI.crm.editNode(safeTestCRMTree[0].id, {
name: 'someNewName'
});
assert.isDefined(newNode, 'new node is defined');
var localCopy = JSON.parse(JSON.stringify(safeTestCRMTree[0]));
localCopy.name = 'someNewName';
assert.deepEqual(newNode, localCopy, 'node matches old node');
});
it('should edit the type when given just the type change option (no-menu)', async () => {
const newNode: CRM.SafeLinkNode = await crmAPI.crm.editNode(safeTestCRMTree[0].id, {
type: 'link'
}) as any;
assert.isDefined(newNode, 'new node is defined');
var localCopy: CRM.SafeLinkNode = JSON.parse(JSON.stringify(safeTestCRMTree[0])) as any;
localCopy.type = 'link';
localCopy.menuVal = [];
localCopy.value = [{
"newTab": true,
"url": "https://www.example.com"
}];
assert.deepEqual(newNode, localCopy, 'node matches expected node');
});
it('should edit the type when given just the type change option (menu)', async () => {
const newNode: CRM.SafeMenuNode = await crmAPI.crm.editNode(safeTestCRMTree[3].id, {
type: 'menu'
}) as any;
assert.isDefined(newNode, 'new node is defined');
var localCopy: CRM.SafeMenuNode = JSON.parse(JSON.stringify(safeTestCRMTree[3])) as any;
localCopy.type = 'menu';
localCopy.stylesheetVal = {
"stylesheet": "/* ==UserScript==\n// @name\tstylesheet\n// @CRM_contentTypes\t[true, true, true, false, false, false]\n// @CRM_launchMode\t3\n// @CRM_stylesheet\ttrue\n// @grant\tnone\n// @match\t*://*.example.com/*\n// ==/UserScript== */\nbody {\n\tbackground-color: red;\n}",
"launchMode": 0,
"toggle": true,
"defaultOn": true,
"convertedStylesheet": {
"options": "",
"stylesheet": ""
},
"options": {}
};
localCopy.value = null;
localCopy.children = [];
assert.deepEqual(newNode, localCopy, 'node matches expected node');
});
it('should be able to change both at the same time', async () => {
const newNode: CRM.LinkNode = await crmAPI.crm.editNode(safeTestCRMTree[0].id, {
type: 'link',
name: 'someNewName'
}) as any;
assert.isDefined(newNode, 'new node is defined');
var localCopy: CRM.LinkNode = JSON.parse(JSON.stringify(safeTestCRMTree[0])) as any;
localCopy.type = 'link';
localCopy.name = 'someNewName';
localCopy.menuVal = [];
localCopy.value = [{
"newTab": true,
"url": "https://www.example.com"
}];
assert.deepEqual(newNode, localCopy, 'node matches expected node');
});
it('should throw an error when given an invalid node id', async () => {
await asyncThrows(() => {
return crmAPI.crm.editNode(999, {
type: 'link',
name: 'someNewName'
});
}, /There is no node with the id you supplied \(([0-9]+)\)/);
});
it('should throw an error when given an type', async () => {
await asyncThrows(() => {
// @ts-ignore
return crmAPI.crm.editNode(safeTestCRMTree[0].id, {
type: 'someInvalidType' as any,
name: 'someNewName'
});
}, /Given type is not a possible type to switch to, use either script, stylesheet, link, menu or divider/);
});
});
describe('#getTriggers()', () => {
before(async () => {
await resetTree();
});
it('should correctly get the triggers for all nodes', async () => {
const pairs: [number, CRM.SafeNode][] = [];
window.globals.crm.crmByIdSafe.forEach((node, nodeId) => {
pairs.push([nodeId, node]);
});
for (const [ nodeId, node] of pairs) {
const { triggers } = node;
const callTriggers = await crmAPI.crm.getTriggers(nodeId);
assert.deepEqual(callTriggers, triggers,
'triggers match expected');
}
});
it('should throw an error when passed an invalid node id', async () => {
await asyncThrows(() => {
return crmAPI.crm.getTriggers(999);
}, /There is no node with the id you supplied \(([0-9]+)\)/);
});
});
describe('#setTriggers()', () => {
before(async () => {
await resetTree();
});
it('should set the triggers to passed triggers (empty)', async () => {
var triggers: CRM.Triggers = [];
const newNode = await crmAPI.crm.setTriggers(safeTestCRMTree[1].id, triggers);
assert.deepEqual(newNode.triggers, triggers, 'triggers match expected');
assert.isTrue(newNode.showOnSpecified, 'triggers are turned on');
});
it('should set the triggers to passed triggers (non-empty)', async () => {
var triggers = [{
url: '<all_urls>',
not: true
}];
const newNode = await crmAPI.crm.setTriggers(safeTestCRMTree[1].id, triggers);
assert.deepEqual(newNode.triggers, triggers, 'triggers match expected');
assert.isTrue(newNode.showOnSpecified, 'triggers are turned on');
});
it('should set the triggers and showOnSpecified to true', async () => {
var triggers = [{
url: 'http://somesite.com',
not: true
}];
const newNode = await crmAPI.crm.setTriggers(safeTestCRMTree[0].id, triggers);
assert.deepEqual(newNode.triggers, triggers, 'triggers match expected');
assert.isTrue(newNode.showOnSpecified, 'triggers are turned on');
});
it('should work on all valid urls', async function () {
this.timeout(500);
this.slow(300);
var triggerUrls = ['<all_urls>', 'http://google.com', '*://*/*', '*://google.com/*',
'http://*/*', 'https://*/*', 'file://*', 'ftp://*'];
for (const triggerUrl of triggerUrls) {
var trigger = [{
url: triggerUrl,
not: false
}];
const newNode = await crmAPI.crm.setTriggers(safeTestCRMTree[0].id, trigger);
assert.deepEqual(newNode.triggers, trigger, 'triggers match expected');
assert.isTrue(newNode.showOnSpecified, 'triggers are turned on');
};
});
it('should throw an error when given an invalid url', async () => {
var triggers = [{
url: 'somesite.com',
not: true
}];
await asyncThrows(async () => {
const newNode = await crmAPI.crm.setTriggers(safeTestCRMTree[0].id, triggers);
assert.deepEqual(newNode.triggers, triggers, 'triggers match expected');
assert.isTrue(newNode.showOnSpecified, 'triggers are turned on');
}, /Triggers don't match URL scheme/);
});
});
describe('#getTriggersUsage()', () => {
before(async () => {
await resetTree();
});
it('should return the triggers usage for given node', async () => {
for (const node of safeTestCRMTree) {
if (node.type === 'link' || node.type === 'menu' || node.type === 'divider') {
const usage = await crmAPI.crm.getTriggerUsage(node.id);
assert.strictEqual(usage, node.showOnSpecified, 'usage matches expected');
}
};
});
it('should throw an error when node is not of correct type', async () => {
for (const node of safeTestCRMTree) {
if (!(node.type === 'link' || node.type === 'menu' || node.type === 'divider')) {
await asyncThrows(() => {
return crmAPI.crm.getTriggerUsage(node.id);
}, /Node is not of right type, can only be menu, link or divider/);
}
};
});
});
describe('#setTriggerUsage()', () => {
beforeEach(async () => {
await resetTree();
});
it('should correctly set the triggers usage on a node of the right type', async () => {
await crmAPI.crm.setTriggerUsage(safeTestCRMTree[0].id, true);
assert.isTrue(window.globals.crm.crmTree[0].showOnSpecified, 'correctly set to true');
await crmAPI.crm.setTriggerUsage(safeTestCRMTree[0].id, false);
assert.isFalse(window.globals.crm.crmTree[0].showOnSpecified, 'correctly set to false');
await crmAPI.crm.setTriggerUsage(safeTestCRMTree[0].id, true);
assert.isTrue(window.globals.crm.crmTree[0].showOnSpecified, 'correctly set to true');
});
it('should throw an error when the type of the node is not right', async () => {
await asyncThrows(() => {
return crmAPI.crm.setTriggerUsage(safeTestCRMTree[2].id, true);
}, /Node is not of right type, can only be menu, link or divider/);
});
});
describe('#getContentTypes()', () => {
it('should get the content types when given a valid node', async () => {
const actual = await crmAPI.crm.getContentTypes(safeTestCRMTree[0].id);
const expected = safeTestCRMTree[0].onContentTypes;
assert.deepEqual(actual, expected,
'context type arrays match');
});
});
describe('#setContentType()', () => {
beforeEach(async () => {
await resetTree();
});
it('should set a single content type by index when given valid input', async function() {
this.timeout(250);
this.slow(150);
const currentContentTypes = JSON.parse(JSON.stringify(
safeTestCRMTree[0].onContentTypes));
for (let i = 0; i < currentContentTypes.length; i++) {
if (Math.random() > 0.5 || i === 5) {
const result = await crmAPI.crm.setContentType(safeTestCRMTree[0].id, i,
!currentContentTypes[i]);
assert.deepEqual(result,
await crmAPI.crm.getContentTypes(safeTestCRMTree[0].id),
'array resulting from setContentType is the same as ' +
'the one from getContentType');
currentContentTypes[i] = !currentContentTypes[i];
}
}
const current = window.globals.crm.crmTree[0].onContentTypes;
assert.deepEqual(current, currentContentTypes,
'correct content types were flipped');
});
it('should set a single content type by name when given valid input', async () => {
const arr = ['page','link','selection','image','video','audio'] as CRM.ContentTypeString[];
const currentContentTypes = JSON.parse(JSON.stringify(
safeTestCRMTree[0].onContentTypes));
for (let i = 0; i < currentContentTypes.length; i++) {
if (Math.random() > 0.5 || i === 5) {
const result = await crmAPI.crm.setContentType(safeTestCRMTree[0].id, arr[i],
!currentContentTypes[i]);
assert.deepEqual(result,
await crmAPI.crm.getContentTypes(safeTestCRMTree[0].id),
'array resulting from setContentType is the same as ' +
'the one from getContentType');
currentContentTypes[i] = !currentContentTypes[i];
}
}
const current = window.globals.crm.crmTree[0].onContentTypes;
assert.deepEqual(current, currentContentTypes,
'correct content types were flipped');
});
it('should throw an error when a non-existent name is used', async () => {
await asyncThrows(() => {
//@ts-ignore
return crmAPI.crm.setContentType(safeTestCRMTree[0].id, 'x', true);
}, /Index is not in index array/, 'should throw an error when given index -1');
});
it('should throw an error when a non-existent index is used', async () => {
await asyncThrows(() => {
return crmAPI.crm.setContentType(safeTestCRMTree[0].id, -1, true);
}, /Value for index is smaller than 0/, 'should throw an error when given index -1');
await asyncThrows(() => {
return crmAPI.crm.setContentType(safeTestCRMTree[0].id, 8, true);
}, /Value for index is bigger than 5/, 'should throw an error when given index 8');
});
it('should throw an error when given a non-boolean value to set', async () => {
await asyncThrows(() => {
//@ts-ignore
return crmAPI.crm.setContentType(safeTestCRMTree[0].id, 0, 'x');
}, /Value for value is not of type boolean/, 'should throw an error when given a non-boolean value');
});
});
describe('#setContentTypes()', () => {
it('should set the entire array when passed a correct one', async () => {
const testArr = [false, false, false, false, false, false].map(() => {
return Math.random() > 0.5;
});
const { onContentTypes } = await crmAPI.crm.setContentTypes(safeTestCRMTree[0].id, testArr);
assert.deepEqual(onContentTypes, window.globals.crm.crmTree[0].onContentTypes,
'returned value matches actual tree value');
assert.deepEqual(onContentTypes, testArr,
'returned value matches set value');
});
it('should throw an error when passed an array with incorrect length', async () => {
await asyncThrows(() => {
return crmAPI.crm.setContentTypes(safeTestCRMTree[0].id, []);
}, /Content type array is not of length 6/, 'should throw an error when given an array that is too short');
await asyncThrows(() => {
return crmAPI.crm.setContentTypes(safeTestCRMTree[0].id,
[false, false, false, false, false, false, false]);
}, /Content type array is not of length 6/, 'should throw an error when given an array that is too long');
});
it('should throw an error when passed an array with non-boolean values', async () => {
await asyncThrows(() => {
//@ts-ignore
return crmAPI.crm.setContentTypes(safeTestCRMTree[0].id, [1, 2, 3, 4, 5, 6]);
}, /Not all values in array contentTypes are of type string/, 'should throw an error when given an array with incorrect values');
});
});
describe('#setLaunchMode()', () => {
before(async () => {
await resetTree();
});
it('should correctly set it when given a valid node and value', async () => {
const newNode = await crmAPI.crm.setLaunchMode(safeTestCRMTree[3].id, 1);
// @ts-ignore
assert.strictEqual(newNode.value.launchMode, 1, 'launch modes match');
});
it('should throw an error when given a non-script or non-stylesheet node', async () => {
await asyncThrows(() => {
return crmAPI.crm.setLaunchMode(safeTestCRMTree[0].id, 1);
}, /Node is not of type script or stylesheet/);
});
it('should throw an error when given an invalid launch mode', async () => {
await asyncThrows(() => {
return crmAPI.crm.setLaunchMode(safeTestCRMTree[3].id, -5);
}, /Value for launchMode is smaller than 0/);
});
it('should throw an error when given an invalid launch mode', async () => {
await asyncThrows(() => {
return crmAPI.crm.setLaunchMode(safeTestCRMTree[3].id, 5);
}, /Value for launchMode is bigger than 4/);
});
});
describe('#getLaunchMode()', () => {
beforeEach(async () => {
await resetTree();
});
it('should correctly get the launchMode for scripts or stylesheets', async () => {
const launchMode = await crmAPI.crm.getLaunchMode(safeTestCRMTree[3].id);
assert.strictEqual(launchMode, safeTestCRMTree[3].value.launchMode,
'launchMode matches expected');
});
it('should throw an error when given an invalid node type', async () => {
await asyncThrows(() => {
return crmAPI.crm.getLaunchMode(safeTestCRMTree[0].id);
}, /Node is not of type script or stylesheet/);
});
});
describe('Stylesheet', () => {
describe('#setStylesheet()', () => {
beforeEach(async () => {
await resetTree();
});
it('should correctly set the stylesheet on stylesheet nodes', async () => {
const newNode = await crmAPI.crm.stylesheet.setStylesheet(safeTestCRMTree[3].id, 'testValue');
assert.isDefined(newNode, 'node has been passed along');
// @ts-ignore
assert.strictEqual(newNode.value.stylesheet, 'testValue', 'stylesheet has been set');
// @ts-ignore
assert.strictEqual(window.globals.crm.crmTree[3].value.stylesheet, 'testValue',
'stylesheet has been correctly updated in tree');
});
it('should correctly set the stylesheet on non-stylesheet nodes', async () => {
const newNode = await crmAPI.crm.stylesheet.setStylesheet(safeTestCRMTree[2].id, 'testValue');
assert.isDefined(newNode, 'node has been passed along');
// @ts-ignore
assert.strictEqual(newNode.stylesheetVal.stylesheet, 'testValue',
'stylesheet has been set');
// @ts-ignore
assert.strictEqual(window.globals.crm.crmTree[2].stylesheetVal.stylesheet,
'testValue', 'stylesheet has been correctly updated in tree');
});
});
describe('#getStylesheet()', () => {
before(async () => {
await resetTree();
});
it('should correctly get the value of stylesheet type nodes', async () => {
const stylesheet = await crmAPI.crm.stylesheet.getStylesheet(safeTestCRMTree[3].id);
assert.isDefined(stylesheet, 'stylesheet has been passed along');
assert.strictEqual(stylesheet, safeTestCRMTree[3].value.stylesheet,
'stylesheets match');
});
it('should correctly get the value of non-stylesheet type nodes', async () => {
const stylesheet = await crmAPI.crm.stylesheet.getStylesheet(safeTestCRMTree[2].id);
assert.strictEqual(stylesheet, (
safeTestCRMTree[2].stylesheetVal ?
// @ts-ignore
safeTestCRMTree[2].stylesheetVal.stylesheet :
undefined
), 'stylesheets match');
});
});
});
describe('Link', () => {
describe('#getLinks()', () => {
it('should correctly get the links of a link-type node', async () => {
const linkValue = await crmAPI.crm.link.getLinks(safeTestCRMTree[5].children[0].id);
assert.deepEqual(linkValue, safeTestCRMTree[5].children[0].value, 'link values match');
});
it('should correctly get the links of a non-link-type node', async () => {
const linkValue = await crmAPI.crm.link.getLinks(safeTestCRMTree[3].id);
if (linkValue) {
assert.deepEqual(linkValue, safeTestCRMTree[3].linkVal, 'link values match');
} else {
assert.strictEqual(linkValue, safeTestCRMTree[3].linkVal, 'link values match');
}
});
});
describe('#setLinks()', () => {
it('should correctly set it when passed an array of links', async () => {
const newValue = await crmAPI.crm.link.setLinks(safeTestCRMTree[5].children[0].id, [{
url: 'firstlink.com',
newTab: true
}, {
url: 'secondlink.com',
newTab: false
}, {
url: 'thirdlink.com',
newTab: true
}]);
assert.sameDeepMembers(newValue, [{
url: 'firstlink.com',
newTab: true
}, {
url: 'secondlink.com',
newTab: false
}, {
url: 'thirdlink.com',
newTab: true
}], 'link value matches expected');
});
it('should correctly set it when passed a link object', async () => {
const newValue = await crmAPI.crm.link.setLinks(safeTestCRMTree[5].children[0].id, {
url: 'firstlink.com',
newTab: true
});
assert.sameDeepMembers(newValue, [{
url: 'firstlink.com',
newTab: true
}], 'link value matches expected');
});
it('should throw an error when the link is missing (array)', async () => {
await asyncThrows(() => {
// @ts-ignore
return crmAPI.crm.link.setLinks(safeTestCRMTree[5].children[0].id, [{}, {
newTab: false
}, {
newTab: true
} as any]);
}, /For not all values in the array items is the property url defined/)
});
it('should throw an error when the link is missing (objec)', async () => {
await asyncThrows(() => {
// @ts-ignore
return crmAPI.crm.link.setLinks(safeTestCRMTree[5].children[0].id, { });
}, /For not all values in the array items is the property url defined/);
})
});
describe('#push()', () => {
beforeEach(async () => {
await resetTree();
});
it('should correctly set it when passed an array of links', async () => {
const newValue = await crmAPI.crm.link.push(safeTestCRMTree[5].children[0].id, [{
url: 'firstlink.com',
newTab: true
}, {
url: 'secondlink.com',
newTab: false
}, {
url: 'thirdlink.com',
newTab: true
}]);
// @ts-ignore
assert.sameDeepMembers(newValue, safeTestCRMTree[5].children[0].value.concat([{
url: 'firstlink.com',
newTab: true
}, {
url: 'secondlink.com',
newTab: false
}, {
url: 'thirdlink.com',
newTab: true
}]), 'link value matches expected');
});
it('should correctly set it when passed a link object', async () => {
const newValue = await crmAPI.crm.link.push(safeTestCRMTree[5].children[0].id, {
url: 'firstlink.com',
newTab: true
});
// @ts-ignore
assert.sameDeepMembers(newValue, safeTestCRMTree[5].children[0].value.concat([{
url: 'firstlink.com',
newTab: true
}]), 'link value matches expected');
});
it('should throw an error when the link is missing (array)', async () => {
await asyncThrows(() => {
// @ts-ignore
return crmAPI.crm.link.push(safeTestCRMTree[5].children[0].id, [{}, {
newTab: false
}, {
newTab: true
} as any]);
}, /For not all values in the array items is the property url defined/)
});
it('should throw an error when the link is missing (objec)', async () => {
await asyncThrows(() => {
// @ts-ignore
return crmAPI.crm.link.push(safeTestCRMTree[5].children[0].id, { });
}, /For not all values in the array items is the property url defined/);
})
});
describe('#splice()', () => {
beforeEach(async () => {
await resetTree();
});
it('should correctly splice at index 0 and amount 1', async () => {
const { spliced } = await crmAPI.crm.link.splice(safeTestCRMTree[5].children[0].id, 0, 1);
var linkCopy = JSON.parse(JSON.stringify(safeTestCRMTree[5].children[0].value)) as CRM.LinkNodeLink[];
var splicedExpected = linkCopy.splice(0, 1);
assert.deepEqual((window.globals.crm.crmTree[5] as CRM.MenuNode).children[0].value, linkCopy,
'new value matches expected');
assert.deepEqual(spliced, splicedExpected, 'spliced node matches expected node');
});
it('should correctly splice at index not-0 and amount 1', async () => {
const { spliced } = await crmAPI.crm.link.splice(safeTestCRMTree[5].children[0].id, 2, 1);
var linkCopy = JSON.parse(JSON.stringify(safeTestCRMTree[5].children[0].value)) as CRM.LinkNodeLink[];
var splicedExpected = linkCopy.splice(2, 1);
assert.deepEqual((window.globals.crm.crmTree[5] as CRM.MenuNode).children[0].value, linkCopy,
'new value matches expected');
assert.deepEqual(spliced, splicedExpected, 'spliced node matches expected node');
});
it('should correctly splice at index 0 and amount 2', async () => {
const { spliced } = await crmAPI.crm.link.splice(safeTestCRMTree[5].children[0].id, 0, 2);
var linkCopy = JSON.parse(JSON.stringify(safeTestCRMTree[5].children[0].value)) as CRM.LinkNodeLink[];
var splicedExpected = linkCopy.splice(0, 2);
assert.deepEqual((window.globals.crm.crmTree[5] as CRM.MenuNode).children[0].value, linkCopy,
'new value matches expected');
assert.deepEqual(spliced, splicedExpected, 'spliced node matches expected node');
});
it('should correctly splice at index non-0 and amount 2', async () => {
const { spliced } = await crmAPI.crm.link.splice(safeTestCRMTree[5].children[0].id, 1, 2);
var linkCopy = JSON.parse(JSON.stringify(safeTestCRMTree[5].children[0].value)) as CRM.LinkNodeLink[];
var splicedExpected = linkCopy.splice(1, 2);
assert.deepEqual((window.globals.crm.crmTree[5] as CRM.MenuNode).children[0].value, linkCopy,
'new value matches expected');
assert.deepEqual(spliced, splicedExpected, 'spliced node matches expected node');
});
});
});
describe('Script', () => {
describe('#setScript()', () => {
beforeEach(async () => {
await resetTree();
});
it('should correctly set the script on script nodes', async () => {
const newNode = await crmAPI.crm.script.setScript(safeTestCRMTree[2].id, 'testValue');
assert.isDefined(newNode, 'node has been passed along');
// @ts-ignore
assert.strictEqual(newNode.value.script, 'testValue', 'script has been set');
// @ts-ignore
assert.strictEqual(window.globals.crm.crmTree[2].value.script, 'testValue',
'script has been correctly updated in tree');
});
it('should correctly set the script on non-script nodes', async () => {
const newNode = await crmAPI.crm.script.setScript(safeTestCRMTree[3].id, 'testValue');
assert.isDefined(newNode, 'node has been passed along');
// @ts-ignore
assert.strictEqual(newNode.scriptVal.script, 'testValue',
'script has been set');
// @ts-ignore
assert.strictEqual(window.globals.crm.crmTree[3].scriptVal.script,
'testValue', 'script has been correctly updated in tree');
});
});
describe('#getScript()', () => {
before(async () => {
await resetTree();
});
it('should correctly get the value of script type nodes', async () => {
const script = await crmAPI.crm.script.getScript(safeTestCRMTree[2].id);
assert.isDefined(script, 'script has been passed along');
assert.strictEqual(script, safeTestCRMTree[2].value.script,
'scripts match');
});
it('should correctly get the value of non-script type nodes', async () => {
const script = await crmAPI.crm.script.getScript(safeTestCRMTree[3].id);
assert.strictEqual(script, (
safeTestCRMTree[2].scriptVal as any ?
// @ts-ignore
safeTestCRMTree[2].scriptVal.script : undefined
), 'scripts match');
});
});
describe('#setBackgroundScript()', () => {
//This has the exact same implementation as other script setting but
//testing this is kinda hard because it starts the background script and a
//lot of stuff happens as a result of that (web workers etc) that i can't
//really emulate
});
describe('#getBackgroundScript()', () => {
before(async () => {
await resetTree();
});
it('should correctly get the value of backgroundScript type nodes', async () => {
const backgroundScript = await crmAPI.crm.script.getBackgroundScript(safeTestCRMTree[2].id);
assert.isDefined(backgroundScript, 'backgroundScript has been passed along');
assert.strictEqual(backgroundScript, safeTestCRMTree[2].value.backgroundScript,
'backgroundScripts match');
});
it('should correctly get the value of non-script type nodes', async () => {
const backgroundScript = await crmAPI.crm.script.getScript(safeTestCRMTree[3].id);
assert.strictEqual(backgroundScript, (
safeTestCRMTree[2].scriptVal as any ?
// @ts-ignore
safeTestCRMTree[2].scriptVal.backgroundScript :
undefined
), 'backgroundScripts match');
});
});
describe('Libraries', () => {
describe('#push()', () => {
beforeEach(async () => {
await resetTree();
//Add some test libraries
await crmAPI.libraries.register('jquery', {
url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js'
});
await crmAPI.libraries.register('lib2', {
code: 'some code 2'
});
await crmAPI.libraries.register('lib3', {
code: 'some code 3'
});
await crmAPI.libraries.register('lib4', {
code: 'some code 4'
});
});
it('should be possible to add a library by name', async () => {
const libraries = await crmAPI.crm.script.libraries.push(safeTestCRMTree[2].id, {
name: 'jquery'
});
//@ts-ignore
assert.deepEqual(libraries, window.globals.crm.crmTree[2].value.libraries,
'returned value is the same as in the tree');
//@ts-ignore
assert.includeDeepMembers(libraries, [{
name: 'jquery'
}], 'libraries array contains the registered library');
});
it('should be possible to add multiple libraries by name', async () => {
const registered = [{
name: 'jquery'
}, {
name: 'lib2'
}];
const libraries = await crmAPI.crm.script.libraries.push(safeTestCRMTree[2].id, registered);
//@ts-ignore
assert.deepEqual(libraries, window.globals.crm.crmTree[2].value.libraries,
'returned value is the same as in the tree');
//@ts-ignore
assert.includeDeepMembers(libraries, registered,
'libraries array contains the registered library');
});
it('should throw an error when the node is not a script', async () => {
await asyncThrows(() => {
return crmAPI.crm.script.libraries.push(safeTestCRMTree[0].id, {
name: 'lib2'
});
}, /Node is not of type script/, 'non-existent library can\'t be added');
});
it('should throw an error when a non-existent library is added', async () => {
await asyncThrows(() => {
return crmAPI.crm.script.libraries.push(safeTestCRMTree[2].id, {
name: 'lib5'
});
}, /Library lib5 is not registered/, 'non-existent library can\'t be added');
});
});
describe('#splice()', () => {
beforeEach(async () => {
await resetTree();
//Add some test libraries
await crmAPI.libraries.register('jquery', {
url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js'
});
await crmAPI.libraries.register('lib2', {
code: 'some code 2'
});
await crmAPI.libraries.register('lib3', {
code: 'some code 3'
});
await crmAPI.libraries.register('lib4', {
code: 'some code 4'
});
//@ts-ignore
window.globals.crm.crmTree[2].value.libraries = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}]
});
it('should correctly splice at index 0 and amount 1', async () => {
const { spliced } = await crmAPI.crm.script.libraries.splice(safeTestCRMTree[2].id, 0, 1);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(0, 1);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.libraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced library matches expected library');
});
it('should correctly splice at index not-0 and amount 1', async () => {
const { spliced } = await crmAPI.crm.script.libraries.splice(safeTestCRMTree[2].id, 2, 1);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(2, 1);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.libraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced library matches expected library');
});
it('should correctly splice at index 0 and amount 2', async () => {
const { spliced } = await crmAPI.crm.script.libraries.splice(safeTestCRMTree[2].id, 0, 2);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(0, 2);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.libraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced libraries matches expected libraries');
});
it('should correctly splice at index non-0 and amount 2', async () => {
const { spliced } = await crmAPI.crm.script.libraries.splice(safeTestCRMTree[2].id, 1, 2);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(1, 2);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.libraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced libraries matches expected libraries');
});
});
});
describe('BackgroundLibraries', () => {
describe('Libraries', () => {
describe('#push()', () => {
beforeEach(async () => {
await resetTree();
//Add some test libraries
await crmAPI.libraries.register('jquery', {
url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js'
});
await crmAPI.libraries.register('lib2', {
code: 'some code 2'
});
await crmAPI.libraries.register('lib3', {
code: 'some code 3'
});
await crmAPI.libraries.register('lib4', {
code: 'some code 4'
});
});
it('should be possible to add a library by name', async () => {
const libraries = await crmAPI.crm.script.backgroundLibraries.push(safeTestCRMTree[2].id, {
name: 'jquery'
});
//@ts-ignore
assert.deepEqual(libraries, window.globals.crm.crmTree[2].value.backgroundLibraries,
'returned value is the same as in the tree');
//@ts-ignore
assert.includeDeepMembers(libraries, [{
name: 'jquery'
}], 'libraries array contains the registered library');
});
it('should be possible to add multiple libraries by name', async () => {
const registered = [{
name: 'jquery'
}, {
name: 'lib2'
}];
const libraries = await crmAPI.crm.script.backgroundLibraries.push(safeTestCRMTree[2].id, registered);
//@ts-ignore
assert.deepEqual(libraries, window.globals.crm.crmTree[2].value.backgroundLibraries,
'returned value is the same as in the tree');
//@ts-ignore
assert.includeDeepMembers(libraries, registered,
'libraries array contains the registered library');
});
it('should throw an error when the node is not a script', async () => {
await asyncThrows(() => {
return crmAPI.crm.script.backgroundLibraries.push(safeTestCRMTree[0].id, {
name: 'lib2'
});
}, /Node is not of type script/, 'non-existent library can\'t be added');
});
it('should throw an error when a non-existent library is added', async () => {
await asyncThrows(() => {
return crmAPI.crm.script.backgroundLibraries.push(safeTestCRMTree[2].id, {
name: 'lib5'
});
}, /Library lib5 is not registered/, 'non-existent library can\'t be added');
});
});
describe('#splice()', () => {
beforeEach(async () => {
await resetTree();
//Add some test libraries
await crmAPI.libraries.register('jquery', {
url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js'
});
await crmAPI.libraries.register('lib2', {
code: 'some code 2'
});
await crmAPI.libraries.register('lib3', {
code: 'some code 3'
});
await crmAPI.libraries.register('lib4', {
code: 'some code 4'
});
//@ts-ignore
window.globals.crm.crmTree[2].value.backgroundLibraries = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}]
});
it('should correctly splice at index 0 and amount 1', async () => {
const { spliced } = await crmAPI.crm.script.backgroundLibraries.splice(safeTestCRMTree[2].id, 0, 1);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(0, 1);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.backgroundLibraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced library matches expected library');
});
it('should correctly splice at index not-0 and amount 1', async () => {
const { spliced } = await crmAPI.crm.script.backgroundLibraries.splice(safeTestCRMTree[2].id, 2, 1);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(2, 1);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.backgroundLibraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced library matches expected library');
});
it('should correctly splice at index 0 and amount 2', async () => {
const { spliced } = await crmAPI.crm.script.backgroundLibraries.splice(safeTestCRMTree[2].id, 0, 2);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(0, 2);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.backgroundLibraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced libraries matches expected libraries');
});
it('should correctly splice at index non-0 and amount 2', async () => {
const { spliced } = await crmAPI.crm.script.backgroundLibraries.splice(safeTestCRMTree[2].id, 1, 2);
const expectedArray = [{
name: 'jquery'
}, {
name: 'lib2y'
}, {
name: 'lib3'
}, {
name: 'lib4'
}];
var splicedExpected = expectedArray.splice(1, 2);
//@ts-ignore
assert.deepEqual(window.globals.crm.crmTree[2].value.backgroundLibraries, expectedArray,
'new value matches expected');
//@ts-ignore
assert.deepEqual(spliced, splicedExpected, 'spliced libraries matches expected libraries');
});
});
});
});
});
describe('Menu', () => {
describe('#getChildren()', () => {
beforeEach(async () => {
await resetTree();
});
it('should return the node\'s children when passed a correct id', async () => {
const children = await crmAPI.crm.menu.getChildren(safeTestCRMTree[5].id);
assert.isDefined(children, 'children are defined');
assert.isArray(children, 'children is an array');
assert.deepEqual(children, safeTestCRMTree[5].children, 'children match expected children');
});
it('should throw an error when given a non-menu node', async () => {
await asyncThrows(async () => {
const children = await crmAPI.crm.menu.getChildren(safeTestCRMTree[1].id);
assert.isDefined(children, 'children are defined');
assert.isArray(children, 'children is an array');
assert.lengthOf(children, 0, 'children is an empty array');
}, /Node is not of type menu/);
});
});
describe('#setChildren()', () => {
beforeEach(async () => {
await resetTree();
});
it('should set the children and remove the old ones', async () => {
const newNode = await crmAPI.crm.menu.setChildren(safeTestCRMTree[5].id, [
safeTestCRMTree[1].id,
safeTestCRMTree[2].id
]);
var firstNodeCopy = {...JSON.parse(JSON.stringify(safeTestCRMTree[1])),
path: newNode.children[0].path,
children: null,
index: 1,
isLocal: true,
permissions: []
} as CRM.SafeLinkNode;
assert.deepEqual(newNode.children[0], firstNodeCopy, 'first node was moved correctly');
var secondNodeCopy = {...JSON.parse(JSON.stringify(safeTestCRMTree[2])),
path: newNode.children[1].path,
children: null,
index: 2,
isLocal: true,
permissions: []
} as CRM.ScriptNode;
assert.deepEqual(newNode.children[1], secondNodeCopy, 'second node was moved correctly');
assert.notDeepEqual(newNode.children[0], window.globals.crm.crmTree[1],
'original node has been removed');
assert.notDeepEqual(newNode.children[1], window.globals.crm.crmTree[2],
'original node has been removed');
// @ts-ignore
assert.lengthOf(newNode.children, 2, 'new node has correct size children array');
});
it('should throw an error when trying to run this on a non-menu node', async () => {
await asyncThrows(() => {
return crmAPI.crm.menu.setChildren(safeTestCRMTree[1].id, []);
}, /Node is not of type menu/);
});
});
describe('#push()', () => {
beforeEach(resetTree);
it('should set the children', async () => {
const { children } = await crmAPI.crm.menu.push(safeTestCRMTree[5].id, [
safeTestCRMTree[1].id,
safeTestCRMTree[2].id
]);
var firstNodeCopy = JSON.parse(JSON.stringify(safeTestCRMTree[1]));
firstNodeCopy.path = children[1].path;
assert.deepEqual(children[1], firstNodeCopy, 'first node was moved correctly');
var secondNodeCopy = JSON.parse(JSON.stringify(safeTestCRMTree[2]));
secondNodeCopy.path = children[2].path;
assert.deepEqual(children[2], secondNodeCopy, 'second node was moved correctly');
assert.notDeepEqual(children[1], window.globals.crm.crmTree[1],
'original node has been removed');
assert.notDeepEqual(children[2], window.globals.crm.crmTree[2],
'original node has been removed');
// @ts-ignore
assert.lengthOf(children, 3, 'new node has correct size children array');
});
it('should throw an error when trying to run this on a non-menu node', async () => {
await asyncThrows(() => {
return crmAPI.crm.menu.push(safeTestCRMTree[1].id, []);
}, /Node is not of type menu/);
});
});
describe('#splice()', () => {
beforeEach(resetTree);
it('should correctly splice at index 0 and amount 1', async () => {
const { spliced } = await crmAPI.crm.menu.splice(safeTestCRMTree[5].id, 0, 1);
// @ts-ignore
assert.lengthOf(window.globals.crm.crmTree[5].children, 0, 'new node has 0 children');
assert.deepEqual(spliced[0], safeTestCRMTree[5].children[0],
'spliced child matches expected child');
});
});
});
});
describe('Storage', function() {
this.slow(200);
step('API exists', () => {
assert.isObject(crmAPI.storage, 'storage API is an object');
});
var usedStrings: {
[str: string]: boolean;
} = {};
function generateUniqueRandomString() {
var str;
while (usedStrings[(str = generateRandomString())]) {}
usedStrings[str] = true;
return str;
}
var storageTestData: {
key: string;
value: string;
}[] = [];
for (var i = 0; i < 50; i++) {
storageTestData.push({
key: generateUniqueRandomString(),
value: generateUniqueRandomString()
});
}
step('API works', () => {
var isClearing = false;
var listeners: ((key: string, oldVal: any, newVal: any) => void)[] = [];
var listenerActivations: number[] = [];
for (var i = 0; i < storageTestData.length; i++) {
listenerActivations[i] = 0;
}
function createStorageOnChangeListener(index: number) {
var fn = function(key: string, _oldVal: any, newVal: any) {
if (storageTestData[index].key.indexOf(key) !== 0) {
throw new Error(`Storage keys do not match, ${key} does not match expected ${storageTestData[index].key}`);
}
if (!isClearing) {
if (newVal !== storageTestData[index].value) {
throw new Error(`Storage values do not match, ${newVal} does not match expected value ${storageTestData[index].value}`);
}
}
listenerActivations[index]++;
}
listeners.push(fn);
crmAPI.storage.onChange.addListener(fn, storageTestData[index].key);
}
assert.doesNotThrow(() => {
for (let i = 0; i < storageTestData.length; i++) {
createStorageOnChangeListener(i);
}
}, 'setting up listening for storage works');
assert.doesNotThrow(() => {
for (let i = 0; i < storageTestData.length; i++) {
if (Math.floor(Math.random() * 2)) {
listenerActivations[i] += 1;
crmAPI.storage.onChange.removeListener(listeners[i], storageTestData[i].key);
}
}
}, 'setting up listener removing for storage works');
assert.doesNotThrow(() => {
for (let i = 0; i < storageTestData.length; i++) {
crmAPI.storage.set(storageTestData[i].key, storageTestData[i].value);
}
}, 'setting storage works');
var storageTestExpected: any = {
testKey: nodeStorage.testKey
};
for (let i = 0; i < storageTestData.length; i++) {
var key = storageTestData[i].key;
if (key.indexOf('.') > -1) {
var storageCont = storageTestExpected;
var path = key.split('.');
var length = path.length - 1;
for (var j = 0; j < length; j++) {
if (storageCont[path[j]] === undefined) {
storageCont[path[j]] = {};
}
storageCont = storageCont[path[j]];
}
storageCont[path[length]] = storageTestData[i].value;
} else {
storageTestExpected[storageTestData[i].key] = storageTestData[i].value;
}
}
assert.deepEqual(crmAPI.storage.get(), storageTestExpected, 'storage is equal to expected');
//If all listeners are 2, that means they got called twice, or were removed
for (let i = 0; i < storageTestData.length; i++) {
assert.strictEqual(listenerActivations[i], 1, `listener ${i} has been called once or removed`);
}
//Fetch the data using get
for (let i = 0; i < storageTestData.length; i++) {
var val = crmAPI.storage.get(storageTestData[i].key);
assert.strictEqual(val, storageTestData[i].value,
`getting value at index ${i}: ${val} is equal to expected value ${storageTestData[i].value}`);
}
isClearing = true;
//Remove all data at the lowest level
for (var i = 0; i < storageTestData.length; i++) {
assert.doesNotThrow(() => {
crmAPI.storage.remove(storageTestData[i].key);
}, 'calling crmAPI.storage.remove does not throw');
assert.isUndefined(crmAPI.storage.get(storageTestData[i].key), 'removed data is undefined');
}
//Reset it
for (let i = 0; i < storageTestData.length; i++) {
var key = storageTestData[i].key;
let keyArr: string[] = [];
if (key.indexOf('.') > -1) {
keyArr = key.split('.');
} else {
keyArr = [key];
}
assert.doesNotThrow(() => {
crmAPI.storage.remove(keyArr[0]);
}, 'removing top-level data does not throw');
assert.isUndefined(crmAPI.storage.get(keyArr[0]), 'removed data is undefined');
}
//Set by object
assert.doesNotThrow(() => {
crmAPI.storage.set(storageTestExpected);
}, 'calling storage.set with an object does not throw');
//Check if they now match
assert.deepEqual(crmAPI.storage.get(), storageTestExpected, 'storage matches expected after object set');
});
});
describe('ContextMenuItem', () => {
describe('#setType()', () => {
it('should override the type for the tab only', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setType('checkbox');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID),
'node specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID),
'tab specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides,
'override object was created');
assert.deepEqual(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides, {
type: 'checkbox'
}, 'type was overridden');
}, 'setting type does not throw');
});
it('should override the type globally', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setType('separator', true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
type: 'separator'
}, 'type was overridden');
}, 'setting type does not throw');
});
it('should throw an error if the type is incorrect', async () => {
await asyncThrows(async () => {
//@ts-ignore
await crmAPI.contextMenuItem.setType('incorrect');
}, /Item type is not one of "normal"/,
'setting type throws if type is incorrect');
});
afterEach('Clear Override', () => {
window.globals.crmValues.nodeTabStatuses.get(NODE_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides &&
(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides = {});
window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID) &&
(window.globals.crmValues.contextMenuGlobalOverrides.set(NODE_ID, {}));
});
});
describe('#setChecked()', () => {
it('should override the checked status for the tab only', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setChecked(true);
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID),
'node specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID),
'tab specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides,
'override object was created');
assertDeepContains(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides, {
checked: true
}, 'checked status was overridden');
}, 'setting checked status does not throw');
});
it('should override the checked status globally', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setChecked(false, true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assertDeepContains(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
checked: false
}, 'checked status was overridden');
}, 'setting checked status does not throw');
});
it('should set the type to checkbox if it wasn\'t already', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setChecked(true, true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
checked: true,
type: 'checkbox'
}, 'type was changed to checkbox');
}, 'setting checked status does not throw');
});
it('should not touch the type if it already was a checkable', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setType('radio');
await crmAPI.contextMenuItem.setChecked(true, true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
checked: true,
type: 'radio'
}, 'type was not changed');
}, 'setting checked status does not throw');
});
afterEach('Clear Override', () => {
window.globals.crmValues.nodeTabStatuses.get(NODE_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides &&
(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides = {});
window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID) &&
(window.globals.crmValues.contextMenuGlobalOverrides.set(NODE_ID, {}));
});
});
describe('#setContentTypes()', () => {
it('should override the content types for the tab only', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setContentTypes(['page']);
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID),
'node specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID),
'tab specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides,
'override object was created');
assert.deepEqual(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides, {
contentTypes: ['page']
}, 'content type was overridden');
}, 'setting content types does not throw');
});
it('should override the content types globally', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setContentTypes(['audio'], true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
contentTypes: ['audio']
}, 'content type was overridden');
}, 'setting content types does not throw');
});
it('should throw an error if the content types are incorrect', async () => {
await asyncThrows(async () => {
//@ts-ignore
await crmAPI.contextMenuItem.setContentTypes(['incorrect']);
}, /Not all content types are one of /,
'setting content types throws if type is incorrect');
});
afterEach('Clear Override', () => {
window.globals.crmValues.nodeTabStatuses.get(NODE_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides &&
(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides = {});
window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID) &&
(window.globals.crmValues.contextMenuGlobalOverrides.set(NODE_ID, {}));
});
});
describe('#setVisiblity()', () => {
it('should override the visibility for the tab only', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setVisibility(true);
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID),
'node specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID),
'tab specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides,
'override object was created');
assert.deepEqual(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides, {
isVisible: true
}, 'visibility was overridden');
}, 'setting type does not throw');
});
it('should override the visibility globally', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setVisibility(false, true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
isVisible: false
}, 'visibility was overridden');
}, 'setting type does not throw');
});
afterEach('Clear Override', () => {
window.globals.crmValues.nodeTabStatuses.get(NODE_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides &&
(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides = {});
window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID) &&
(window.globals.crmValues.contextMenuGlobalOverrides.set(NODE_ID, {}));
});
});
describe('#setDisabled()', () => {
it('should override the disabled status for the tab only', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setDisabled(true);
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID),
'node specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID),
'tab specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides,
'override object was created');
assert.deepEqual(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides, {
isDisabled: true
}, 'disabled status was overridden');
}, 'setting type does not throw');
});
it('should override the disabled status globally', async () => {
await asyncDoesNotThrow(async () => {
await crmAPI.contextMenuItem.setDisabled(false, true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
isDisabled: false
}, 'disabled status was overridden');
}, 'setting type does not throw');
});
afterEach('Clear Override', () => {
window.globals.crmValues.nodeTabStatuses.get(NODE_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides &&
(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides = {});
window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID) &&
(window.globals.crmValues.contextMenuGlobalOverrides.set(NODE_ID, {}));
});
});
describe('#setName()', () => {
it('should override the name for the tab only', async () => {
await asyncDoesNotThrow(async () => {
const name = generateRandomString();
await crmAPI.contextMenuItem.setName(name);
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID),
'node specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID),
'tab specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides,
'override object was created');
assert.deepEqual(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides, {
name
}, 'name was overridden');
}, 'setting type does not throw');
});
it('should override the name globally', async () => {
await asyncDoesNotThrow(async () => {
const name = generateRandomString();
await crmAPI.contextMenuItem.setName(name, true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
name
}, 'name was overridden');
}, 'setting type does not throw');
});
afterEach('Clear Override', () => {
window.globals.crmValues.nodeTabStatuses.get(NODE_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides &&
(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides = {});
window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID) &&
(window.globals.crmValues.contextMenuGlobalOverrides.set(NODE_ID, {}));
});
});
describe('#resetName()', () => {
it('should reset the name for the tab only', async () => {
await asyncDoesNotThrow(async () => {
const changedName = generateRandomString();
await crmAPI.contextMenuItem.setName(changedName);
await crmAPI.contextMenuItem.resetName();
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID),
'node specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID),
'tab specific status was created');
assert.exists(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides,
'override object was created');
assert.deepEqual(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides, {
name: NODE_NAME
}, 'name was reset');
}, 'setting type does not throw');
});
it('should reset the name globally', async () => {
await asyncDoesNotThrow(async () => {
const changedName = generateRandomString();
await crmAPI.contextMenuItem.setName(changedName, true);
await crmAPI.contextMenuItem.resetName(true);
assert.exists(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID),
'node specific status was created');
assert.deepEqual(window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID), {
name: NODE_NAME
}, 'name was overridden');
}, 'setting type does not throw');
});
afterEach('Clear Override', () => {
window.globals.crmValues.nodeTabStatuses.get(NODE_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID) &&
window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides &&
(window.globals.crmValues.nodeTabStatuses.get(NODE_ID).tabs.get(TAB_ID).overrides = {});
window.globals.crmValues.contextMenuGlobalOverrides.get(NODE_ID) &&
(window.globals.crmValues.contextMenuGlobalOverrides.set(NODE_ID, {}));
});
});
});
describe('Libraries', () => {
before(() => {
class XHRWrapper {
public onreadystatechange: () => void;
public onload: () => void;
public readyState: number;
public method: string;
public url: string;
public status: number;
public responseText: string;
constructor() {
this.onreadystatechange = undefined;
this.onload = undefined;
this.readyState = XHRWrapper.UNSENT;
}
open(method: string, url: string) {
this.method = method;
this.url = url;
this.readyState = XHRWrapper.OPENED;
}
send() {
this.readyState = XHRWrapper.LOADING;
request(this.url, (err, res, body) => {
this.status = err ? 600 : res.statusCode;
this.readyState = XHRWrapper.DONE;
this.responseText = body;
this.onreadystatechange && this.onreadystatechange();
this.onload && this.onload();
});
}
static get UNSENT() {
return 0;
}
static get OPENED() {
return 1;
}
static get HEADERS_RECEIVED() {
return 2;
}
static get LOADING() {
return 3;
}
static get DONE() {
return 4;
}
}
window.XMLHttpRequest = XHRWrapper;
});
describe('#register()', () => {
it('should correctly register a library solely by its url and fetch it', async function () {
this.timeout(5000);
this.retries(3);
this.slow(4000);
const library = await crmAPI.libraries.register('someLibrary', {
url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js'
});
assert.isDefined(library, 'library is defined');
assert.isObject(library, 'library is an object');
assert.strictEqual(library.name, 'someLibrary', 'name matches expected');
}).timeout(10000);
it('should register a library by its code', async () => {
const library = await crmAPI.libraries.register('someOtherLibrary', {
code: 'some code'
});
assert.isDefined(library, 'library is defined');
assert.deepEqual(library, {
name: 'someOtherLibrary',
code: 'some code',
ts: {
enabled: false,
code: {}
}
});
});
});
});
describe('Chrome', () => {
before('Setup', () => {
// @ts-ignore
window.chrome = window.chrome || {};
window.chrome.runtime = window.chrome.runtime || {} as typeof window.chrome.runtime;
window.chrome.sessions = {
testReturnSimple: function(a: number, b: number) {
return a + b;
},
testReturnObject: function(a: {
x: number;
y: number;
z: number;
}, b: any[]) {
a.x = 3;
a.y = 4;
a.z = 5;
b.push(3);
b.push(4);
b.push(5);
return {a: a, b: b};
},
testCallbackSimple: function(a: number, b: number, callback: (result: number) => void) {
callback(a + b);
},
testCallbackObject: function(a: {
x: number;
y: number;
z: number;
}, b: any[], callback: (result: {
a: {
x: number;
y: number;
z: number;
};
b: any[]
}) => void) {
a.x = 3;
a.y = 4;
a.z = 5;
b.push(3);
b.push(4);
b.push(5);
callback({ a: a, b: b });
},
testCombinedSimple: function(a: number, b: number, callback: (result: number) => void) {
callback(a + b);
return a + b;
},
testCombinedObject: function(a: {
x: number;
y: number;
z: number;
}, b: any[], callback: (result: {
a: {
x: number;
y: number;
z: number;
};
b: any[]
}) => void) {
a.x = 3;
a.y = 4;
a.z = 5;
b.push(3);
b.push(4);
b.push(5);
callback({ a: a, b: b });
return {a: a, b: b};
},
testPersistentSimple: function(a: number, b: number, callback: (result: number) => void) {
callback(a + b);
callback(a - b);
callback(a * b);
},
testPersistentObject: function(a: {
x: number;
y: number;
z: number;
value: number;
}, b: any[], callback: (result: {
a: {
x: number;
y: number;
z: number;
};
b: any[]
}|{
c: {
x: number;
y: number;
z: number;
}
d: any[];
}|number) => void) {
a.x = 3;
a.y = 4;
a.z = 5;
b.push(3);
b.push(4);
b.push(5);
callback({a: a, b: b});
callback({c: a, d: b});
callback(a.value + b[0]);
},
willError: function(callback: () => void) {
window.chrome.runtime.lastError = {
message: 'Some error'
}
callback();
window.chrome.runtime.lastError = null;
}
} as any;
});
step('exists', () => {
assert.isFunction(crmAPI.chrome);
});
it('works with return values and non-object parameters', (done) => {
var val1 = Math.floor(Math.random() * 50);
var val2 = Math.floor(Math.random() * 50);
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testReturnSimple')(val1, val2).return((value) => {
assert.strictEqual(value, val1 + val2, 'returned value matches expected value');
done();
}).send();
}, 'calling chrome function does not throw');
});
it('works with return values and object-paremters', (done) => {
var val1 = {
value: Math.floor(Math.random() * 50)
};
var val2 = [Math.floor(Math.random() * 50)];
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testReturnObject')(val1, val2).return((value) => {
assert.deepEqual(value, {
a: {
value: val1.value,
x: 3,
y: 4,
z: 5
},
b: [val2[0], 3, 4, 5]
}, 'returned value matches expected');
done();
}).send();
}, 'calling chrome function does not throw');
});
it('works with callback values and non-object parameters', (done) => {
var val1 = Math.floor(Math.random() * 50);
var val2 = Math.floor(Math.random() * 50);
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testCallbackSimple')(val1, val2, (value: number) => {
assert.strictEqual(value, val1 + val2, 'returned value matches expected value');
done();
}).send();
}, 'calling chrome function does not throw');
});
it('works with callback values and object parameters', (done) => {
var val1 = {
value: Math.floor(Math.random() * 50)
};
var val2 = [Math.floor(Math.random() * 50)];
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testCallbackObject')(val1, val2, (value: {
a: {
value: number;
x: number;
y: number;
z: number;
}
b: number[];
}) => {
assert.deepEqual(value, {
a: {
value: val1.value,
x: 3,
y: 4,
z: 5
},
b: [val2[0], 3, 4, 5]
}, 'returned value matches expected');
done();
}).send();
}, 'calling chrome function does not throw');
});
it('works with combined functions and simple parameters', (done) => {
var val1 = Math.floor(Math.random() * 50);
var val2 = Math.floor(Math.random() * 50);
var promises: Promise<any>[] = [];
promises.push(new Promise((resolveCallback) => {
promises.push(new Promise((resolveReturn) => {
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testCombinedSimple')(val1, val2, (value: number) => {
assert.strictEqual(value, val1 + val2, 'returned value is equal to returned value');
resolveCallback(null);
}).return((value) => {
assert.strictEqual(value, val1 + val2, 'returned value is equal to returned value');
resolveReturn(null);
}).send();
}, 'calling chrome function does not throw');
}));
}));
Promise.all(promises).then(() => {
done();
}, (err) => {
throw err;
});
});
it('works with combined functions and object parameters', (done) => {
var val1 = {
value: Math.floor(Math.random() * 50)
};
var val2 = [Math.floor(Math.random() * 50)];
var promises: Promise<any>[] = [];
promises.push(new Promise((resolveCallback) => {
promises.push(new Promise((resolveReturn) => {
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testCombinedObject')(val1, val2, (value: {
a: {
value: number;
x: number;
y: number;
z: number;
}
b: number[];
}) => {
assert.deepEqual(value, {
a: {
value: val1.value,
x: 3,
y: 4,
z: 5
},
b: [val2[0], 3, 4, 5]
}, 'returned value matches expected');
resolveCallback(null);
}).return((value) => {
assert.deepEqual(value, {
a: {
value: val1.value,
x: 3,
y: 4,
z: 5
},
b: [val2[0], 3, 4, 5]
}, 'returned value matches expected');
resolveReturn(null);
}).send();
}, 'calling chrome function does not throw');
}));
}));
Promise.all(promises).then(() => {
done();
}, (err) => {
throw err;
});
});
it('works with persistent callbacks and simple parameters', (done) => {
var val1 = Math.floor(Math.random() * 50);
var val2 = Math.floor(Math.random() * 50);
var called = 0;
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testPersistentSimple')(val1, val2).persistent((value: number) => {
switch (called) {
case 0:
assert.strictEqual(value, val1 + val2, 'returned value matches expected');
break;
case 1:
assert.strictEqual(value, val1 - val2, 'returned value matches expected');
break;
case 2:
assert.strictEqual(value, val1 * val2, 'returned value matches expected');
done();
break;
}
called++;
}).send();
}, 'calling chrome function does not throw');
});
it('works with persistent callbacks and object parameters', (done) => {
var val1 = {
value: Math.floor(Math.random() * 50)
};
var val2 = [Math.floor(Math.random() * 50)];
var called = 0;
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.testCallbackObject')(val1, val2, (value: {
a: {
value: number;
x: number;
y: number;
z: number;
}
b: number[];
}|{
c: {
value: number;
x: number;
y: number;
z: number;
}
d: number[];
}|number) => {
switch (called) {
case 0:
assert.deepEqual(value, {
a: {
value: val1.value,
x: 3,
y: 4,
z: 5
},
b: [val2[0], 3, 4, 5]
}, 'returned value matches expected');
break;
case 1:
assert.deepEqual(value, {
c: {
value: val1.value,
x: 3,
y: 4,
z: 5
},
d: [val2[0], 3, 4, 5]
}, 'returned value matches expected');
break;
case 2:
assert.strictEqual(value, val1.value + val2[0],
'returned value matches expected');
done();
break;
}
called++;
done();
}).send();
}, 'calling chrome function does not throw');
});
it('sets crmAPI.lastError on chrome runtime lastError', (done) => {
assert.doesNotThrow(() => {
crmAPI.chrome('sessions.willError')(() => {
assert.isDefined(crmAPI.lastError);
done();
}).send();
});
});
it('should throw when crmAPI.lastError is unchecked', (done) => {
assert.doesNotThrow(() => {
crmAPI.onError = (err: Error) => {
assert.isDefined(err);
done();
};
crmAPI.chrome('sessions.willError')(() => { }).send();
});
});
});
describe('Browser', () => {
before('Setup', () => {
// @ts-ignore
window.browserAPI = window.browserAPI || {};
//@ts-ignore
window.browserAPI.alarms = {
//@ts-ignore
create: function(a, b) {
return new Promise((resolve) => {
resolve(null);
});
},
get: function(a: number, b: number) {
return new Promise((resolve) => {
resolve(a + b);
});
},
getAll: function(a: number, b: number) {
return new Promise((resolve) => {
resolve([a, b]);
});
},
//@ts-ignore
clear: function(callback) {
return new Promise((resolve) => {
//@ts-ignore
callback(1);
resolve(null);
});
},
onAlarm: {
//@ts-ignore
addListener: function(callback) {
return new Promise((resolve) => {
// @ts-ignore
callback(1);
// @ts-ignore
callback(2);
// @ts-ignore
callback(3);
resolve(null);
});
},
},
//@ts-ignore
outside: function() {
return new Promise((resolve) => {
resolve(3);
});
}
}
window.globals.availablePermissions = ['alarms'];
});
step('exists', () => {
assert.isObject(crmAPI.browser);
});
it('works with functions whose promise resolves into nothing', async () => {
await asyncDoesNotThrow(() => {
//@ts-ignore
return crmAPI.browser.alarms.create(1, 2).send();
});
});
it('works with functions whose promise resolves into something', async () => {
await asyncDoesNotThrow(async () => {
//@ts-ignore
const result = await crmAPI.browser.alarms.get.args(1, 2).send();
assert.strictEqual(result, 1 + 2, 'resolved values matches expected');
});
});
it('works with functions whose promises resolves into an object', async () => {
await asyncDoesNotThrow(async () => {
//@ts-ignore
const result = await crmAPI.browser.alarms.getAll(1, 2).send();
//@ts-ignore
assert.deepEqual(result, [1, 2], 'resolved values matches expected');
});
});
it('works with functions with a callback', async () => {
await asyncDoesNotThrow(async () => {
await new Promise(async (resolve) => {
//@ts-ignore
crmAPI.browser.alarms.clear((value) => {
assert.strictEqual(value, 1, 'resolved values matches expected');
resolve(null);
}).send();
});
});
});
it('works with functions with a persistent callback', async () => {
await asyncDoesNotThrow(async () => {
return new Promise(async (resolve) => {
let called = 0;
await crmAPI.browser.alarms.onAlarm.addListener.p(() => {
called += 1;
if (called === 3) {
resolve(null);
}
}).send();
});
});
});
it('works with functions with an "any" function', async () => {
await asyncDoesNotThrow(() => {
return crmAPI.browser.any('alarms.outside').send();
});
});
it('should throw an error when a non-existent "any" function is tried', async () => {
let warn = console.warn;
console.warn = (...args: string[]) => {
if (args[0] === 'Error:' &&
args[1] === 'Passed API does note exist') {
warn.apply(console, args);
}
};
await asyncThrows(() => {
return crmAPI.browser.any('alarms.doesnotexist').send();
}, /Passed API does not exist/, 'non-existent function throws');
console.warn = warn;
});
});
describe('GM', () => {
describe('#GM_info()', () => {
it('should return the info object', () => {
const info = crmAPI.GM.GM_info();
assert.deepEqual(info, greaseMonkeyData.info,
'returned info is the same as expected');
});
});
let storageMirror: {
[key: string]: any;
} = {};
describe('#GM_listValues()', () => {
before('Set test values', () => {
storageMirror = {};
for (let i = 0; i < 10; i++) {
const key = generateRandomString(true);
const value = generateRandomString();
crmAPI.GM.GM_setValue(key, value);
storageMirror[key] = value;
}
});
it('should return all keys', () => {
const expectedKeys = [];
for (const key in storageMirror) {
expectedKeys.push(key);
}
const actualKeys = crmAPI.GM.GM_listValues();
assert.includeMembers(actualKeys, expectedKeys,
'all keys were returned');
});
it('should not return deleted keys', () => {
const expectedKeys = [];
for (const key in storageMirror) {
if (Math.random() > 0.5) {
crmAPI.GM.GM_deleteValue(key);
} else {
expectedKeys.push(key);
}
}
const actualKeys = crmAPI.GM.GM_listValues();
assert.includeMembers(actualKeys, expectedKeys,
'deleted keys are removed');
});
});
describe('#GM_getValue()', () => {
before('Set test values', () => {
storageMirror = {};
for (let i = 0; i < 100; i++) {
const key = generateRandomString(true);
const value = generateRandomString();
crmAPI.GM.GM_setValue(key, value);
}
});
it('should return the correct value when it exists', () => {
for (const key in storageMirror) {
const expected = storageMirror[key];
const actual = crmAPI.GM.GM_getValue(key);
assert.strictEqual(actual, expected,
'returned value matches expected');
}
});
it('should return the default value if it does not exist', () => {
for (const key in storageMirror) {
const expected = generateRandomString();
const actual = crmAPI.GM.GM_getValue(`${key}x`, expected);
assert.strictEqual(actual, expected,
'returned value matches default');
}
});
});
describe('#GM_setValue()', () => {
before('Reset storagemirror', () => {
storageMirror = {};
});
it('should not throw when setting the values', function() {
this.slow(1500);
this.timeout(5000);
for (let i = 0; i < 1000; i++) {
const key = generateRandomString(true);
const randVal = Math.round(Math.random() * 100);
if (randVal <= 20) {
assert.doesNotThrow(() => {
const value = Math.random() * 10000;
storageMirror[key] = value;
crmAPI.GM.GM_setValue(key, value);
}, 'number value can be set');
} else if (randVal <= 40) {
assert.doesNotThrow(() => {
const value = Math.random() > 0.5;
storageMirror[key] = value;
crmAPI.GM.GM_setValue(key, value);
}, 'boolean value can be set');
} else if (randVal <= 60) {
assert.doesNotThrow(() => {
const value = generateRandomString();
storageMirror[key] = value;
crmAPI.GM.GM_setValue(key, value);
}, 'string value can be set');
} else if (randVal <= 80) {
assert.doesNotThrow(() => {
const value: {
[key: string]: string;
} = {};
for (let j = 0; j < Math.round(Math.random() * 100); j++) {
value[generateRandomString(true)] = generateRandomString();
}
storageMirror[key] = value;
crmAPI.GM.GM_setValue(key, value);
}, 'object value can be set');
} else {
assert.doesNotThrow(() => {
const value = [];
for (let j = 0; j < Math.round(Math.random() * 100); j++) {
value.push(generateRandomString());
}
storageMirror[key] = value;
crmAPI.GM.GM_setValue(key, value);
}, 'array value can be set');
}
}
});
it('should be possible to retrieve the values', function() {
this.timeout(500);
this.slow(200);
for (const key in storageMirror) {
const expected = storageMirror[key];
const actual = crmAPI.GM.GM_getValue(key);
if (typeof expected === 'object') {
assert.deepEqual(actual, expected,
'complex types are returned properly');
} else {
assert.strictEqual(actual, expected,
'primitive type values are returned properly');
}
}
});
it('should not change value once set', () => {
for (const key in storageMirror) {
if (typeof storageMirror[key] === 'object') {
if (Array.isArray(storageMirror[key])) {
storageMirror[key].push('x');
} else {
storageMirror[key]['x'] = 'x';
}
}
}
for (const key in storageMirror) {
const expected = storageMirror[key];
const actual = crmAPI.GM.GM_getValue(key);
if (typeof expected === 'object') {
assert.notDeepEqual(actual, expected,
'remote has not changed');
}
}
});
});
describe('#GM_deleteValue()', () => {
const deletedKeys: string[] = [];
before('Set test values', () => {
storageMirror = {};
for (let i = 0; i < 100; i++) {
const key = generateRandomString(true);
const value = generateRandomString();
crmAPI.GM.GM_setValue(key, value);
}
});
it('should be able to delete something when the key exists', () => {
assert.doesNotThrow(() => {
for (const key in storageMirror) {
if (Math.random() > 0.5) {
crmAPI.GM.GM_deleteValue(key);
deletedKeys.push(key);
}
}
}, 'deletes valus without throwing');
});
it('should do nothing when the key does not exist', () => {
assert.doesNotThrow(() => {
for (const key in storageMirror) {
//Delete the key + some string
crmAPI.GM.GM_deleteValue(key + 'x');
}
}, 'deletes valus without throwing');
});
it('should actually be deleted', () => {
for (const key in storageMirror) {
let expected = undefined;
if (deletedKeys.indexOf(key) === -1) {
expected = storageMirror[key];
}
const actual = crmAPI.GM.GM_getValue(key);
if (deletedKeys.indexOf(key) === -1) {
assert.strictEqual(actual, expected,
'undeleted keys are not affected');
} else {
assert.isUndefined(actual,
'undefined is returned when it the key does not exist')
}
}
});
});
describe('#GM_getResourceURL()', () => {
it('should return the correct URL if the resource exists', () => {
for (const name in greaseMonkeyData.resources) {
const actual = greaseMonkeyData.resources[name].crmUrl;
const expected = crmAPI.GM.GM_getResourceURL(name);
assert.strictEqual(actual, expected,
'urls match');
}
});
it('should return undefined if the resource does not exist', () => {
for (const name in greaseMonkeyData.resources) {
const expected = crmAPI.GM.GM_getResourceURL(`${name}x`);
assert.isUndefined(expected, 'returns undefined');
}
});
});
describe('#GM_getResourceString()', () => {
it('should return the correct URL if the resource exists', () => {
for (const name in greaseMonkeyData.resources) {
const actual = greaseMonkeyData.resources[name].dataString;
const expected = crmAPI.GM.GM_getResourceString(name);
assert.strictEqual(actual, expected,
'urls match');
}
});
it('should return undefined if the resource does not exist', () => {
for (const name in greaseMonkeyData.resources) {
const expected = crmAPI.GM.GM_getResourceString(`${name}x`);
assert.isUndefined(expected, 'returns undefined');
}
});
});
describe('#GM_log()', () => {
it('should be a callable function', () => {
assert.isFunction(crmAPI.GM.GM_log);
});
});
describe('#GM_openInTab()', () => {
let lastCall: {
url: string;
target: string;
} = undefined;
//@ts-ignore
window.open = (url, target) => {
lastCall = {
url, target
}
}
it('should be callable with a url', () => {
const url = generateRandomString();
crmAPI.GM.GM_openInTab(url);
assert.isDefined(lastCall, 'window.open was called');
assert.strictEqual(lastCall.url, url,
'URLs match');
});
});
describe('#GM_registerMenuCommand()', () => {
it('should be a callable function', () => {
assert.isFunction(crmAPI.GM.GM_registerMenuCommand);
assert.doesNotThrow(() => {
crmAPI.GM.GM_registerMenuCommand();
});
});
});
describe('#GM_unregisterMenuCommand()', () => {
it('should be a callable function', () => {
assert.isFunction(crmAPI.GM.GM_unregisterMenuCommand);
assert.doesNotThrow(() => {
crmAPI.GM.GM_unregisterMenuCommand();
});
});
});
describe('#GM_setClipboard()', () => {
it('should be a callable function', () => {
assert.isFunction(crmAPI.GM.GM_setClipboard);
assert.doesNotThrow(() => {
crmAPI.GM.GM_setClipboard();
});
});
});
describe('#GM_addValueChangeListener()', () => {
const calls: {
[key: string]: {
name: string;
oldValue: any;
newValue: any;
}[];
} = {};
const expectedCalls: {
[key: string]: {
name: string;
oldValue: any;
newValue: any;
}[];
} = {};
before('Set test values', () => {
storageMirror = {};
for (let i = 0; i < 100; i++) {
const key = generateRandomString(true);
const value = generateRandomString();
crmAPI.GM.GM_setValue(key, value);
}
});
it('should be able to set listeners without errors', () => {
assert.doesNotThrow(() => {
for (const key in storageMirror) {
crmAPI.GM.GM_addValueChangeListener(key, (name, oldValue, newValue) => {
calls[key] = calls[key] || [];
calls[key].push({
name, oldValue, newValue
});
});
}
}, 'function does not throw');
});
it('should call the listeners on set', () => {
for (const key in storageMirror) {
for (let i = 0; i < Math.round(Math.random() * 5); i++) {
const oldVal = crmAPI.GM.GM_getValue(key);
const newVal = generateRandomString();
crmAPI.GM.GM_setValue(key, newVal);
expectedCalls[key] = expectedCalls[key] || [];
expectedCalls[key].push({
name: key,
oldValue: oldVal,
newValue: newVal
})
}
}
assert.deepEqual(calls, expectedCalls,
'actual calls match expected');
});
it('should call the listeners on delete', () => {
for (const key in storageMirror) {
const oldVal = crmAPI.GM.GM_getValue(key);
crmAPI.GM.GM_deleteValue(key);
expectedCalls[key] = expectedCalls[key] || [];
expectedCalls[key].push({
name: key,
oldValue: oldVal,
newValue: undefined
});
}
assert.deepEqual(calls, expectedCalls,
'actual calls match expected');
});
});
describe('#GM_removeValueChangeListener()', () => {
const calls: {
[key: string]: {
name: string;
oldValue: any;
newValue: any;
}[];
} = {};
const listeners: number[] = [];
before('Set test values', () => {
storageMirror = {};
for (let i = 0; i < 100; i++) {
const key = generateRandomString(true);
const value = generateRandomString();
crmAPI.GM.GM_setValue(key, value);
listeners.push(crmAPI.GM.GM_addValueChangeListener(key, (name, oldValue, newValue) => {
calls[key] = calls[key] || [];
calls[key].push({
name, oldValue, newValue
});
}));
}
});
it('should remove listeners without throwing', () => {
for (const listener of listeners) {
assert.doesNotThrow(() => {
crmAPI.GM.GM_removeValueChangeListener(listener);
}, 'calling the function does not throw');
}
});
it('should not call any listeners when their keys are updated', () => {
for (const key in storageMirror) {
for (let i = 0; i < Math.round(Math.random() * 5); i++) {
const newVal = generateRandomString();
crmAPI.GM.GM_setValue(key, newVal);
}
}
assert.deepEqual(calls, {},
'no calls were made');
});
});
describe('#GM_getTab()', () => {
it('should be instantly called', async () => {
assert.isFunction(crmAPI.GM.GM_getTab);
await asyncDoesNotThrow(() => {
return new Promise((resolve) => {
crmAPI.GM.GM_getTab(() => {
resolve(null);
});
});
});
});
});
describe('#GM_getTabs()', () => {
it('should be instantly called', async () => {
assert.isFunction(crmAPI.GM.GM_getTabs);
await asyncDoesNotThrow(() => {
return new Promise((resolve) => {
crmAPI.GM.GM_getTabs(() => {
resolve(null);
});
});
});
});
});
describe('#GM_saveTab()', () => {
it('should be instantly called', async () => {
assert.isFunction(crmAPI.GM.GM_saveTab);
await asyncDoesNotThrow(() => {
return new Promise((resolve) => {
crmAPI.GM.GM_saveTab(() => {
resolve(null);
});
});
});
});
});
});
describe('#fetch()', () => {
it('should return the data at the URL', async function() {
this.timeout(5000);
this.slow(2500);
assert.isFunction(crmAPI.fetch);
await asyncDoesNotThrow(() => {
return new Promise(async (resolve) => {
const result = await crmAPI.fetch('https://www.example.com');
assert.isTrue(result.indexOf('example') > -1,
'page is successfully loaded');
resolve(null);
});
});
});
});
describe('#fetchBackground()', () => {
it('should return the data at the URL', async function() {
this.timeout(5000);
this.slow(2500);
assert.isFunction(crmAPI.fetchBackground);
await asyncDoesNotThrow(() => {
return new Promise(async (resolve) => {
debugger;
const result = await crmAPI.fetchBackground('https://www.example.com');
assert.isTrue(result.indexOf('example') > -1,
'page is successfully loaded');
resolve(null);
});
});
});
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Mappers from "./mappers";
import { Operation } from "./operation";
import * as Parameters from "./parameters";
const serializer = new msRest.Serializer(Mappers, true);
// specifications for new method group start
const serviceSetPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype0,
Parameters.comp0
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
requestBody: {
parameterPath: "storageServiceProperties",
mapper: {
...Mappers.StorageServiceProperties,
required: true
}
},
contentType: "application/xml; charset=utf-8",
responses: {
202: {
headersMapper: Mappers.ServiceSetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceGetPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype0,
Parameters.comp0
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.StorageServiceProperties,
headersMapper: Mappers.ServiceGetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceGetStatisticsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype0,
Parameters.comp1
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.StorageServiceStats,
headersMapper: Mappers.ServiceGetStatisticsHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceListContainersSegmentOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.prefix,
Parameters.marker0,
Parameters.maxresults,
Parameters.include0,
Parameters.timeout,
Parameters.comp2
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.ListContainersSegmentResponse,
headersMapper: Mappers.ServiceListContainersSegmentHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceGetUserDelegationKeyOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype0,
Parameters.comp3
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
requestBody: {
parameterPath: "keyInfo",
mapper: {
...Mappers.KeyInfo,
required: true
}
},
contentType: "application/xml; charset=utf-8",
responses: {
200: {
bodyMapper: Mappers.UserDelegationKey,
headersMapper: Mappers.ServiceGetUserDelegationKeyHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceGetAccountInfoOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.restype1,
Parameters.comp0
],
headerParameters: [
Parameters.version
],
responses: {
200: {
headersMapper: Mappers.ServiceGetAccountInfoHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceGetAccountInfoWithHeadOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.restype1,
Parameters.comp0
],
headerParameters: [
Parameters.version
],
responses: {
200: {
headersMapper: Mappers.ServiceGetAccountInfoWithHeadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceSubmitBatchOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp4
],
headerParameters: [
Parameters.contentLength,
Parameters.multipartContentType,
Parameters.version,
Parameters.requestId
],
requestBody: {
parameterPath: "body",
mapper: {
required: true,
serializedName: "body",
type: {
name: "Stream"
}
}
},
contentType: "application/xml; charset=utf-8",
responses: {
200: {
bodyMapper: {
serializedName: "Stream",
type: {
name: "Stream"
}
},
headersMapper: Mappers.ServiceSubmitBatchHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const containerCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype2
],
headerParameters: [
Parameters.metadata,
Parameters.access,
Parameters.version,
Parameters.requestId
],
responses: {
201: {
headersMapper: Mappers.ContainerCreateHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerGetPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype2
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.leaseId0
],
responses: {
200: {
headersMapper: Mappers.ContainerGetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerGetPropertiesWithHeadOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype2
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.leaseId0
],
responses: {
200: {
headersMapper: Mappers.ContainerGetPropertiesWithHeadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerDeleteOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype2
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
202: {
headersMapper: Mappers.ContainerDeleteHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerSetMetadataOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype2,
Parameters.comp5
],
headerParameters: [
Parameters.metadata,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince
],
responses: {
200: {
headersMapper: Mappers.ContainerSetMetadataHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerGetAccessPolicyOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype2,
Parameters.comp6
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.leaseId0
],
responses: {
200: {
bodyMapper: {
xmlElementName: "SignedIdentifier",
serializedName: "SignedIdentifiers",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SignedIdentifier"
}
}
}
},
headersMapper: Mappers.ContainerGetAccessPolicyHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerSetAccessPolicyOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype2,
Parameters.comp6
],
headerParameters: [
Parameters.access,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
requestBody: {
parameterPath: [
"options",
"containerAcl"
],
mapper: {
xmlName: "SignedIdentifiers",
xmlElementName: "SignedIdentifier",
serializedName: "containerAcl",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SignedIdentifier"
}
}
}
}
},
contentType: "application/xml; charset=utf-8",
responses: {
200: {
headersMapper: Mappers.ContainerSetAccessPolicyHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerAcquireLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7,
Parameters.restype2
],
headerParameters: [
Parameters.duration,
Parameters.proposedLeaseId0,
Parameters.version,
Parameters.requestId,
Parameters.action0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
201: {
headersMapper: Mappers.ContainerAcquireLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerReleaseLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7,
Parameters.restype2
],
headerParameters: [
Parameters.leaseId1,
Parameters.version,
Parameters.requestId,
Parameters.action1,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
200: {
headersMapper: Mappers.ContainerReleaseLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerRenewLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7,
Parameters.restype2
],
headerParameters: [
Parameters.leaseId1,
Parameters.version,
Parameters.requestId,
Parameters.action2,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
200: {
headersMapper: Mappers.ContainerRenewLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerBreakLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7,
Parameters.restype2
],
headerParameters: [
Parameters.breakPeriod,
Parameters.version,
Parameters.requestId,
Parameters.action3,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
202: {
headersMapper: Mappers.ContainerBreakLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerChangeLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7,
Parameters.restype2
],
headerParameters: [
Parameters.leaseId1,
Parameters.proposedLeaseId1,
Parameters.version,
Parameters.requestId,
Parameters.action4,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
200: {
headersMapper: Mappers.ContainerChangeLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerListBlobFlatSegmentOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.prefix,
Parameters.marker0,
Parameters.maxresults,
Parameters.include1,
Parameters.timeout,
Parameters.restype2,
Parameters.comp2
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.ListBlobsFlatSegmentResponse,
headersMapper: Mappers.ContainerListBlobFlatSegmentHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerListBlobHierarchySegmentOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.prefix,
Parameters.delimiter,
Parameters.marker0,
Parameters.maxresults,
Parameters.include1,
Parameters.timeout,
Parameters.restype2,
Parameters.comp2
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.ListBlobsHierarchySegmentResponse,
headersMapper: Mappers.ContainerListBlobHierarchySegmentHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerGetAccountInfoOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.restype1,
Parameters.comp0
],
headerParameters: [
Parameters.version
],
responses: {
200: {
headersMapper: Mappers.ContainerGetAccountInfoHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const containerGetAccountInfoWithHeadOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{containerName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.restype1,
Parameters.comp0
],
headerParameters: [
Parameters.version
],
responses: {
200: {
headersMapper: Mappers.ContainerGetAccountInfoWithHeadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const directoryCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.resource
],
headerParameters: [
Parameters.directoryProperties,
Parameters.posixPermissions,
Parameters.posixUmask,
Parameters.version,
Parameters.requestId,
Parameters.cacheControl,
Parameters.contentType,
Parameters.contentEncoding,
Parameters.contentLanguage,
Parameters.contentDisposition,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
201: {
headersMapper: Mappers.DirectoryCreateHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
const directoryRenameOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.marker1,
Parameters.pathRenameMode
],
headerParameters: [
Parameters.renameSource,
Parameters.directoryProperties,
Parameters.posixPermissions,
Parameters.posixUmask,
Parameters.sourceLeaseId,
Parameters.version,
Parameters.requestId,
Parameters.cacheControl,
Parameters.contentType,
Parameters.contentEncoding,
Parameters.contentLanguage,
Parameters.contentDisposition,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.sourceIfModifiedSince,
Parameters.sourceIfUnmodifiedSince,
Parameters.sourceIfMatches,
Parameters.sourceIfNoneMatch
],
responses: {
201: {
headersMapper: Mappers.DirectoryRenameHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
const directoryDeleteOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.recursiveDirectoryDelete,
Parameters.marker1
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.DirectoryDeleteHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
const directorySetAccessControlOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.action5
],
headerParameters: [
Parameters.owner,
Parameters.group,
Parameters.posixPermissions,
Parameters.posixAcl,
Parameters.requestId,
Parameters.version,
Parameters.leaseId0,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
200: {
headersMapper: Mappers.DirectorySetAccessControlHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
const directoryGetAccessControlOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.upn,
Parameters.action6
],
headerParameters: [
Parameters.requestId,
Parameters.version,
Parameters.leaseId0,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
200: {
headersMapper: Mappers.DirectoryGetAccessControlHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const blobDownloadOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.snapshot,
Parameters.timeout
],
headerParameters: [
Parameters.range0,
Parameters.rangeGetContentMD5,
Parameters.rangeGetContentCRC64,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
bodyMapper: {
serializedName: "Stream",
type: {
name: "Stream"
}
},
headersMapper: Mappers.BlobDownloadHeaders
},
206: {
bodyMapper: {
serializedName: "Stream",
type: {
name: "Stream"
}
},
headersMapper: Mappers.BlobDownloadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobGetPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.snapshot,
Parameters.timeout
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.BlobGetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobDeleteOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.snapshot,
Parameters.timeout
],
headerParameters: [
Parameters.deleteSnapshots,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
202: {
headersMapper: Mappers.BlobDeleteHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobSetAccessControlOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.action5
],
headerParameters: [
Parameters.owner,
Parameters.group,
Parameters.posixPermissions,
Parameters.posixAcl,
Parameters.requestId,
Parameters.version,
Parameters.leaseId0,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
200: {
headersMapper: Mappers.BlobSetAccessControlHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
const blobGetAccessControlOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.upn,
Parameters.action6
],
headerParameters: [
Parameters.requestId,
Parameters.version,
Parameters.leaseId0,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince
],
responses: {
200: {
headersMapper: Mappers.BlobGetAccessControlHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
const blobRenameOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{filesystem}/{path}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.pathRenameMode
],
headerParameters: [
Parameters.renameSource,
Parameters.directoryProperties,
Parameters.posixPermissions,
Parameters.posixUmask,
Parameters.sourceLeaseId,
Parameters.version,
Parameters.requestId,
Parameters.cacheControl,
Parameters.contentType,
Parameters.contentEncoding,
Parameters.contentLanguage,
Parameters.contentDisposition,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.sourceIfModifiedSince,
Parameters.sourceIfUnmodifiedSince,
Parameters.sourceIfMatches,
Parameters.sourceIfNoneMatch
],
responses: {
201: {
headersMapper: Mappers.BlobRenameHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
isXML: true,
serializer
};
const blobUndeleteOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp8
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
headersMapper: Mappers.BlobUndeleteHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobSetHTTPHeadersOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp0
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.blobCacheControl,
Parameters.blobContentType,
Parameters.blobContentMD5,
Parameters.blobContentEncoding,
Parameters.blobContentLanguage,
Parameters.blobContentDisposition,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.BlobSetHTTPHeadersHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobSetMetadataOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp5
],
headerParameters: [
Parameters.metadata,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.BlobSetMetadataHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobAcquireLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7
],
headerParameters: [
Parameters.duration,
Parameters.proposedLeaseId0,
Parameters.version,
Parameters.requestId,
Parameters.action0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
201: {
headersMapper: Mappers.BlobAcquireLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobReleaseLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7
],
headerParameters: [
Parameters.leaseId1,
Parameters.version,
Parameters.requestId,
Parameters.action1,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.BlobReleaseLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobRenewLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7
],
headerParameters: [
Parameters.leaseId1,
Parameters.version,
Parameters.requestId,
Parameters.action2,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.BlobRenewLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobChangeLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7
],
headerParameters: [
Parameters.leaseId1,
Parameters.proposedLeaseId1,
Parameters.version,
Parameters.requestId,
Parameters.action4,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.BlobChangeLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobBreakLeaseOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp7
],
headerParameters: [
Parameters.breakPeriod,
Parameters.version,
Parameters.requestId,
Parameters.action3,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
202: {
headersMapper: Mappers.BlobBreakLeaseHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobCreateSnapshotOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp9
],
headerParameters: [
Parameters.metadata,
Parameters.version,
Parameters.requestId,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.leaseId0
],
responses: {
201: {
headersMapper: Mappers.BlobCreateSnapshotHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobStartCopyFromURLOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.metadata,
Parameters.tier0,
Parameters.rehydratePriority,
Parameters.copySource,
Parameters.version,
Parameters.requestId,
Parameters.sourceIfModifiedSince,
Parameters.sourceIfUnmodifiedSince,
Parameters.sourceIfMatches,
Parameters.sourceIfNoneMatch,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.leaseId0
],
responses: {
202: {
headersMapper: Mappers.BlobStartCopyFromURLHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobCopyFromURLOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.metadata,
Parameters.tier0,
Parameters.copySource,
Parameters.version,
Parameters.requestId,
Parameters.xMsRequiresSync,
Parameters.sourceIfModifiedSince,
Parameters.sourceIfUnmodifiedSince,
Parameters.sourceIfMatches,
Parameters.sourceIfNoneMatch,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.leaseId0
],
responses: {
202: {
headersMapper: Mappers.BlobCopyFromURLHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobAbortCopyFromURLOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.copyId,
Parameters.timeout,
Parameters.comp10
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.copyActionAbortConstant,
Parameters.leaseId0
],
responses: {
204: {
headersMapper: Mappers.BlobAbortCopyFromURLHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobSetTierOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp11
],
headerParameters: [
Parameters.tier1,
Parameters.rehydratePriority,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0
],
responses: {
200: {
headersMapper: Mappers.BlobSetTierHeaders
},
202: {
headersMapper: Mappers.BlobSetTierHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobGetAccountInfoOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.restype1,
Parameters.comp0
],
headerParameters: [
Parameters.version
],
responses: {
200: {
headersMapper: Mappers.BlobGetAccountInfoHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blobGetAccountInfoWithHeadOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.restype1,
Parameters.comp0
],
headerParameters: [
Parameters.version
],
responses: {
200: {
headersMapper: Mappers.BlobGetAccountInfoWithHeadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const pageBlobCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.contentLength,
Parameters.metadata,
Parameters.blobContentLength,
Parameters.blobSequenceNumber,
Parameters.pageBlobAccessTier,
Parameters.version,
Parameters.requestId,
Parameters.blobType0,
Parameters.blobContentType,
Parameters.blobContentEncoding,
Parameters.blobContentLanguage,
Parameters.blobContentMD5,
Parameters.blobCacheControl,
Parameters.blobContentDisposition,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
201: {
headersMapper: Mappers.PageBlobCreateHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobUploadPagesOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp12
],
headerParameters: [
Parameters.contentLength,
Parameters.transactionalContentCrc64,
Parameters.range0,
Parameters.version,
Parameters.requestId,
Parameters.pageWrite0,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifSequenceNumberLessThanOrEqualTo,
Parameters.ifSequenceNumberLessThan,
Parameters.ifSequenceNumberEqualTo,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
requestBody: {
parameterPath: "body",
mapper: {
required: true,
serializedName: "body",
type: {
name: "Stream"
}
}
},
contentType: "application/octet-stream",
responses: {
201: {
headersMapper: Mappers.PageBlobUploadPagesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobClearPagesOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp12
],
headerParameters: [
Parameters.contentLength,
Parameters.range0,
Parameters.version,
Parameters.requestId,
Parameters.pageWrite1,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifSequenceNumberLessThanOrEqualTo,
Parameters.ifSequenceNumberLessThan,
Parameters.ifSequenceNumberEqualTo,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
201: {
headersMapper: Mappers.PageBlobClearPagesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobUploadPagesFromURLOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp12
],
headerParameters: [
Parameters.sourceUrl,
Parameters.sourceRange0,
Parameters.sourceContentMD5,
Parameters.sourceContentcrc64,
Parameters.contentLength,
Parameters.range1,
Parameters.version,
Parameters.requestId,
Parameters.pageWrite0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.leaseId0,
Parameters.ifSequenceNumberLessThanOrEqualTo,
Parameters.ifSequenceNumberLessThan,
Parameters.ifSequenceNumberEqualTo,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.sourceIfModifiedSince,
Parameters.sourceIfUnmodifiedSince,
Parameters.sourceIfMatches,
Parameters.sourceIfNoneMatch
],
responses: {
201: {
headersMapper: Mappers.PageBlobUploadPagesFromURLHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobGetPageRangesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.snapshot,
Parameters.timeout,
Parameters.comp13
],
headerParameters: [
Parameters.range0,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
bodyMapper: Mappers.PageList,
headersMapper: Mappers.PageBlobGetPageRangesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobGetPageRangesDiffOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.snapshot,
Parameters.timeout,
Parameters.prevsnapshot,
Parameters.comp13
],
headerParameters: [
Parameters.range0,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
bodyMapper: Mappers.PageList,
headersMapper: Mappers.PageBlobGetPageRangesDiffHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobResizeOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp0
],
headerParameters: [
Parameters.blobContentLength,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.PageBlobResizeHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobUpdateSequenceNumberOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp0
],
headerParameters: [
Parameters.sequenceNumberAction,
Parameters.blobSequenceNumber,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
200: {
headersMapper: Mappers.PageBlobUpdateSequenceNumberHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const pageBlobCopyIncrementalOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp14
],
headerParameters: [
Parameters.metadata,
Parameters.copySource,
Parameters.version,
Parameters.requestId,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
202: {
headersMapper: Mappers.PageBlobCopyIncrementalHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const appendBlobCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.contentLength,
Parameters.metadata,
Parameters.version,
Parameters.requestId,
Parameters.blobType1,
Parameters.blobContentType,
Parameters.blobContentEncoding,
Parameters.blobContentLanguage,
Parameters.blobContentMD5,
Parameters.blobCacheControl,
Parameters.blobContentDisposition,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
responses: {
201: {
headersMapper: Mappers.AppendBlobCreateHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const appendBlobAppendBlockOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp15
],
headerParameters: [
Parameters.contentLength,
Parameters.transactionalContentCrc64,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.maxSize,
Parameters.appendPosition,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
requestBody: {
parameterPath: "body",
mapper: {
required: true,
serializedName: "body",
type: {
name: "Stream"
}
}
},
contentType: "application/xml; charset=utf-8",
responses: {
201: {
headersMapper: Mappers.AppendBlobAppendBlockHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const appendBlobAppendBlockFromUrlOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp15
],
headerParameters: [
Parameters.sourceUrl,
Parameters.sourceRange1,
Parameters.sourceContentMD5,
Parameters.sourceContentcrc64,
Parameters.contentLength,
Parameters.version,
Parameters.requestId,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.leaseId0,
Parameters.maxSize,
Parameters.appendPosition,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.sourceIfModifiedSince,
Parameters.sourceIfUnmodifiedSince,
Parameters.sourceIfMatches,
Parameters.sourceIfNoneMatch
],
responses: {
201: {
headersMapper: Mappers.AppendBlobAppendBlockFromUrlHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const blockBlobUploadOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.contentLength,
Parameters.metadata,
Parameters.tier0,
Parameters.version,
Parameters.requestId,
Parameters.blobType2,
Parameters.blobContentType,
Parameters.blobContentEncoding,
Parameters.blobContentLanguage,
Parameters.blobContentMD5,
Parameters.blobCacheControl,
Parameters.blobContentDisposition,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
requestBody: {
parameterPath: "body",
mapper: {
required: true,
serializedName: "body",
type: {
name: "Stream"
}
}
},
contentType: "application/octet-stream",
responses: {
201: {
headersMapper: Mappers.BlockBlobUploadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blockBlobStageBlockOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.blockId,
Parameters.timeout,
Parameters.comp16
],
headerParameters: [
Parameters.contentLength,
Parameters.transactionalContentCrc64,
Parameters.version,
Parameters.requestId,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm
],
requestBody: {
parameterPath: "body",
mapper: {
required: true,
serializedName: "body",
type: {
name: "Stream"
}
}
},
contentType: "application/octet-stream",
responses: {
201: {
headersMapper: Mappers.BlockBlobStageBlockHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blockBlobStageBlockFromURLOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.blockId,
Parameters.timeout,
Parameters.comp16
],
headerParameters: [
Parameters.contentLength,
Parameters.sourceUrl,
Parameters.sourceRange1,
Parameters.sourceContentMD5,
Parameters.sourceContentcrc64,
Parameters.version,
Parameters.requestId,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.leaseId0,
Parameters.sourceIfModifiedSince,
Parameters.sourceIfUnmodifiedSince,
Parameters.sourceIfMatches,
Parameters.sourceIfNoneMatch
],
responses: {
201: {
headersMapper: Mappers.BlockBlobStageBlockFromURLHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blockBlobCommitBlockListOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp17
],
headerParameters: [
Parameters.transactionalContentCrc64,
Parameters.metadata,
Parameters.tier0,
Parameters.version,
Parameters.requestId,
Parameters.blobCacheControl,
Parameters.blobContentType,
Parameters.blobContentEncoding,
Parameters.blobContentLanguage,
Parameters.blobContentMD5,
Parameters.blobContentDisposition,
Parameters.leaseId0,
Parameters.encryptionKey,
Parameters.encryptionKeySha256,
Parameters.encryptionAlgorithm,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.ifMatch,
Parameters.ifNoneMatch
],
requestBody: {
parameterPath: "blocks",
mapper: {
...Mappers.BlockLookupList,
required: true
}
},
contentType: "application/xml; charset=utf-8",
responses: {
201: {
headersMapper: Mappers.BlockBlobCommitBlockListHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const blockBlobGetBlockListOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{containerName}/{blob}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.snapshot,
Parameters.listType,
Parameters.timeout,
Parameters.comp17
],
headerParameters: [
Parameters.version,
Parameters.requestId,
Parameters.leaseId0
],
responses: {
200: {
bodyMapper: Mappers.BlockList,
headersMapper: Mappers.BlockBlobGetBlockListHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const Specifications: { [key: number]: msRest.OperationSpec } = {};
Specifications[Operation.Service_SetProperties] = serviceSetPropertiesOperationSpec;
Specifications[Operation.Service_GetProperties] = serviceGetPropertiesOperationSpec;
Specifications[Operation.Service_GetStatistics] = serviceGetStatisticsOperationSpec;
Specifications[Operation.Service_ListContainersSegment] = serviceListContainersSegmentOperationSpec;
Specifications[Operation.Service_GetUserDelegationKey] = serviceGetUserDelegationKeyOperationSpec;
Specifications[Operation.Service_GetAccountInfo] = serviceGetAccountInfoOperationSpec;
Specifications[Operation.Service_GetAccountInfoWithHead] = serviceGetAccountInfoWithHeadOperationSpec;
Specifications[Operation.Service_SubmitBatch] = serviceSubmitBatchOperationSpec;
Specifications[Operation.Container_Create] = containerCreateOperationSpec;
Specifications[Operation.Container_GetProperties] = containerGetPropertiesOperationSpec;
Specifications[Operation.Container_GetPropertiesWithHead] = containerGetPropertiesWithHeadOperationSpec;
Specifications[Operation.Container_Delete] = containerDeleteOperationSpec;
Specifications[Operation.Container_SetMetadata] = containerSetMetadataOperationSpec;
Specifications[Operation.Container_GetAccessPolicy] = containerGetAccessPolicyOperationSpec;
Specifications[Operation.Container_SetAccessPolicy] = containerSetAccessPolicyOperationSpec;
Specifications[Operation.Container_AcquireLease] = containerAcquireLeaseOperationSpec;
Specifications[Operation.Container_ReleaseLease] = containerReleaseLeaseOperationSpec;
Specifications[Operation.Container_RenewLease] = containerRenewLeaseOperationSpec;
Specifications[Operation.Container_BreakLease] = containerBreakLeaseOperationSpec;
Specifications[Operation.Container_ChangeLease] = containerChangeLeaseOperationSpec;
Specifications[Operation.Container_ListBlobFlatSegment] = containerListBlobFlatSegmentOperationSpec;
Specifications[Operation.Container_ListBlobHierarchySegment] = containerListBlobHierarchySegmentOperationSpec;
Specifications[Operation.Container_GetAccountInfo] = containerGetAccountInfoOperationSpec;
Specifications[Operation.Container_GetAccountInfoWithHead] = containerGetAccountInfoWithHeadOperationSpec;
Specifications[Operation.Directory_Create] = directoryCreateOperationSpec;
Specifications[Operation.Directory_Rename] = directoryRenameOperationSpec;
Specifications[Operation.Directory_Delete] = directoryDeleteOperationSpec;
Specifications[Operation.Directory_SetAccessControl] = directorySetAccessControlOperationSpec;
Specifications[Operation.Directory_GetAccessControl] = directoryGetAccessControlOperationSpec;
Specifications[Operation.Blob_Download] = blobDownloadOperationSpec;
Specifications[Operation.Blob_GetProperties] = blobGetPropertiesOperationSpec;
Specifications[Operation.Blob_Delete] = blobDeleteOperationSpec;
Specifications[Operation.Blob_SetAccessControl] = blobSetAccessControlOperationSpec;
Specifications[Operation.Blob_GetAccessControl] = blobGetAccessControlOperationSpec;
Specifications[Operation.Blob_Rename] = blobRenameOperationSpec;
Specifications[Operation.Blob_Undelete] = blobUndeleteOperationSpec;
Specifications[Operation.Blob_SetHTTPHeaders] = blobSetHTTPHeadersOperationSpec;
Specifications[Operation.Blob_SetMetadata] = blobSetMetadataOperationSpec;
Specifications[Operation.Blob_AcquireLease] = blobAcquireLeaseOperationSpec;
Specifications[Operation.Blob_ReleaseLease] = blobReleaseLeaseOperationSpec;
Specifications[Operation.Blob_RenewLease] = blobRenewLeaseOperationSpec;
Specifications[Operation.Blob_ChangeLease] = blobChangeLeaseOperationSpec;
Specifications[Operation.Blob_BreakLease] = blobBreakLeaseOperationSpec;
Specifications[Operation.Blob_CreateSnapshot] = blobCreateSnapshotOperationSpec;
Specifications[Operation.Blob_StartCopyFromURL] = blobStartCopyFromURLOperationSpec;
Specifications[Operation.Blob_CopyFromURL] = blobCopyFromURLOperationSpec;
Specifications[Operation.Blob_AbortCopyFromURL] = blobAbortCopyFromURLOperationSpec;
Specifications[Operation.Blob_SetTier] = blobSetTierOperationSpec;
Specifications[Operation.Blob_GetAccountInfo] = blobGetAccountInfoOperationSpec;
Specifications[Operation.Blob_GetAccountInfoWithHead] = blobGetAccountInfoWithHeadOperationSpec;
Specifications[Operation.PageBlob_Create] = pageBlobCreateOperationSpec;
Specifications[Operation.PageBlob_UploadPages] = pageBlobUploadPagesOperationSpec;
Specifications[Operation.PageBlob_ClearPages] = pageBlobClearPagesOperationSpec;
Specifications[Operation.PageBlob_UploadPagesFromURL] = pageBlobUploadPagesFromURLOperationSpec;
Specifications[Operation.PageBlob_GetPageRanges] = pageBlobGetPageRangesOperationSpec;
Specifications[Operation.PageBlob_GetPageRangesDiff] = pageBlobGetPageRangesDiffOperationSpec;
Specifications[Operation.PageBlob_Resize] = pageBlobResizeOperationSpec;
Specifications[Operation.PageBlob_UpdateSequenceNumber] = pageBlobUpdateSequenceNumberOperationSpec;
Specifications[Operation.PageBlob_CopyIncremental] = pageBlobCopyIncrementalOperationSpec;
Specifications[Operation.AppendBlob_Create] = appendBlobCreateOperationSpec;
Specifications[Operation.AppendBlob_AppendBlock] = appendBlobAppendBlockOperationSpec;
Specifications[Operation.AppendBlob_AppendBlockFromUrl] = appendBlobAppendBlockFromUrlOperationSpec;
Specifications[Operation.BlockBlob_Upload] = blockBlobUploadOperationSpec;
Specifications[Operation.BlockBlob_StageBlock] = blockBlobStageBlockOperationSpec;
Specifications[Operation.BlockBlob_StageBlockFromURL] = blockBlobStageBlockFromURLOperationSpec;
Specifications[Operation.BlockBlob_CommitBlockList] = blockBlobCommitBlockListOperationSpec;
Specifications[Operation.BlockBlob_GetBlockList] = blockBlobGetBlockListOperationSpec;
export default Specifications; | the_stack |
import { setup, gql, fakeUser, setupFakeMailer } from './setup'
import Supertest from 'supertest'
import { auth } from '@tensei/auth'
import { rest } from '@tensei/rest'
import { text } from '@tensei/common'
import { graphql } from '@tensei/graphql'
jest.mock('purest', () => {
return () => {}
})
test('Registers auth resources when plugin is registered', async () => {
const {
ctx: { resources }
} = await setup([auth().plugin()])
expect(
resources.find(resource => resource.data.name === 'User')
).toBeDefined()
})
test('Can customize the name of the authenticator user', async () => {
const {
ctx: { resources }
} = await setup([auth().user('Customer').plugin()])
expect(
resources.find(resource => resource.data.name === 'Customer')
).toBeDefined()
})
test('Can enable email verification for auth', async () => {
const {
ctx: {
orm: { em }
},
app
} = await setup([
auth()
.user('Customer')
.verifyEmails()
.refreshTokens()
.setup(({ user }) => {
user.fields([text('Name').nullable()])
})
.plugin(),
graphql().plugin()
])
const client = Supertest(app)
const user = fakeUser()
const response = await client.post(`/graphql`).send({
query: gql`
mutation register($name: String!, $email: String!, $password: String!) {
register(object: { name: $name, email: $email, password: $password }) {
customer {
id
email
emailVerifiedAt
}
accessToken
}
}
`,
variables: {
name: user.firstName,
email: user.email,
password: user.password
}
})
expect(response.status).toBe(200)
const registeredCustomer: any = await em.findOne('Customer', {
email: user.email
})
expect(response.body.data.register.customer.id).toBe(
registeredCustomer.id.toString()
)
expect(registeredCustomer.emailVerificationToken).toBeDefined()
const verify_email_response = await client
.post(`/graphql`)
.send({
query: gql`
mutation confirmEmail($emailVerificationToken: String!) {
confirmEmail(
object: { emailVerificationToken: $emailVerificationToken }
) {
id
email
emailVerifiedAt
}
}
`,
variables: {
emailVerificationToken: registeredCustomer.emailVerificationToken
}
})
.set('Authorization', `Bearer ${response.body.data.register.accessToken}`)
expect(verify_email_response.body.data.confirmEmail).toEqual({
id: registeredCustomer.id.toString(),
email: registeredCustomer.email,
emailVerifiedAt: expect.any(String)
})
})
test('Can request a password reset and reset password', async () => {
const mailerMock = {
send: jest.fn(),
sendRaw: jest.fn()
}
const {
ctx: {
orm: { em }
},
app
} = await setup([
auth().verifyEmails().refreshTokens().user('Student').plugin(),
graphql().plugin(),
setupFakeMailer(mailerMock)
])
const client = Supertest(app)
const user = em.create('Student', fakeUser())
await em.persistAndFlush(user)
const response = await client.post(`/graphql`).send({
query: gql`
mutation requestPasswordReset($email: String!) {
requestPasswordReset(object: { email: $email })
}
`,
variables: {
email: user.email
}
})
expect(response.body).toEqual({
data: { requestPasswordReset: true }
})
const passwordReset: any = await em.findOne('PasswordReset', {
email: user.email
})
const UPDATED_PASSWORD = 'UPDATED_PASSWORD'
expect(passwordReset).not.toBe(null)
const resetPassword_response = await client.post(`/graphql`).send({
query: gql`
mutation resetPassword(
$email: String!
$password: String!
$token: String!
) {
resetPassword(
object: { email: $email, token: $token, password: $password }
)
}
`,
variables: {
email: user.email,
password: UPDATED_PASSWORD,
token: passwordReset.token
}
})
expect(resetPassword_response.status).toBe(200)
expect(resetPassword_response.body).toEqual({
data: { resetPassword: true }
})
const login_response = await client.post(`/graphql`).send({
query: gql`
mutation login($email: String!, $password: String!) {
login(object: { email: $email, password: $password }) {
student {
id
email
}
}
}
`,
variables: {
password: UPDATED_PASSWORD,
email: user.email
}
})
expect(login_response.status).toBe(200)
expect(login_response.body.data.login).toEqual({
student: {
id: user.id.toString(),
email: user.email
}
})
})
test('access tokens and refresh tokens are generated correctly', async done => {
const jwtExpiresIn = 2 // in seconds
const refreshTokenExpiresIn = 4 // in seconds
const {
ctx: {
orm: { em }
},
app
} = await setup([
auth()
.verifyEmails()
.refreshTokens()
.user('Student')
.setup(({ user }) => {
user.fields([text('Name').nullable()])
})
.configureTokens({
accessTokenExpiresIn: jwtExpiresIn,
refreshTokenExpiresIn
})
.plugin(),
graphql().plugin()
])
const client = Supertest(app)
const user = em.create('Student', fakeUser())
await em.persistAndFlush(user)
const login_response = await client.post(`/graphql`).send({
query: gql`
mutation login($email: String!, $password: String!) {
login(object: { email: $email, password: $password }) {
accessToken
refreshToken
student {
id
email
}
}
}
`,
variables: {
password: 'password',
email: user.email
}
})
const accessToken: string = login_response.body.data.login.accessToken
const refreshToken: string = login_response.body.data.login.refreshToken
setTimeout(async () => {
// Wait for the jwt to expire, then run a test, make sure its invalid and fails.
const authenticated_response = await client
.post(`/graphql`)
.send({
query: gql`
query authenticated {
authenticated {
id
name
email
}
}
`
})
.set('Authorization', `Bearer ${accessToken}`)
expect(authenticated_response.body.data).toBeNull()
expect(authenticated_response.body.errors[0].message).toBe('Unauthorized.')
// Refresh the jwt with the valid refresh token. Expect to get a new, valid JWT
const refreshToken_response = await client.post(`/graphql`).send({
query: gql`
mutation refreshToken($refreshToken: String!) {
refreshToken(object: { refreshToken: $refreshToken }) {
accessToken
refreshToken
student {
id
email
}
}
}
`,
variables: {
refreshToken: refreshToken
}
})
expect(refreshToken_response.body.data.refreshToken).toEqual({
accessToken: expect.any(String),
refreshToken: expect.any(String),
student: {
id: user.id.toString(),
email: user.email
}
})
// Make a request with the refreshed jwt. Expect it to return a valid authenticated user
const authenticated_refreshed_response = await client
.post(`/graphql`)
.send({
query: gql`
query authenticated {
authenticated {
id
name
email
}
}
`
})
.set(
'Authorization',
`Bearer ${refreshToken_response.body.data.refreshToken.accessToken}`
)
expect(authenticated_refreshed_response.body.data.authenticated).toEqual({
name: null,
id: user.id.toString(),
email: user.email
})
}, jwtExpiresIn * 1000)
setTimeout(async () => {
// After the refresh token has expired, make a call to confirm it can no longer return fresh and new jwts
const invalid_refreshToken_response = await client.post(`/graphql`).send({
query: gql`
mutation refreshToken($refreshToken: String!) {
refreshToken(object: { refreshToken: $refreshToken }) {
accessToken
refreshToken
student {
id
email
}
}
}
`,
variables: {
refreshToken: refreshToken
}
})
expect(invalid_refreshToken_response.body.errors[0].message).toBe(
'Invalid refresh token.'
)
done()
}, refreshTokenExpiresIn * 1000)
const authenticated_response = await client
.post(`/graphql`)
.send({
query: gql`
query authenticated {
authenticated {
id
name
email
}
}
`
})
.set('Authorization', `Bearer ${accessToken}`)
const refreshToken_has_no_access_response = await client
.post(`/graphql`)
.send({
query: gql`
query authenticated {
authenticated {
id
name
email
}
}
`
})
.set('Authorization', `Bearer ${refreshToken}`)
expect(refreshToken_has_no_access_response.body.data).toBeNull()
expect(refreshToken_has_no_access_response.body.errors[0].message).toBe(
'Unauthorized.'
)
expect(authenticated_response.body.data.authenticated).toEqual({
name: null,
id: user.id.toString(),
email: user.email
})
// @ts-ignore
}, 10000)
test('if a refresh token is used twice (compromised), the user is automatically blocked', async () => {
const {
ctx: {
orm: { em }
},
app
} = await setup([
auth().user('Customer').refreshTokens().plugin(),
graphql().plugin()
])
const client = Supertest(app)
const user = em.create('Customer', fakeUser())
await em.persistAndFlush(user)
const login_response = await client.post(`/graphql`).send({
query: gql`
mutation login($email: String!, $password: String!) {
login(object: { email: $email, password: $password }) {
accessToken
refreshToken
customer {
id
email
}
}
}
`,
variables: {
password: 'password',
email: user.email
}
})
const { refreshToken } = login_response.body.data.login
const refreshToken_response = await client.post(`/graphql`).send({
query: gql`
mutation refreshToken($refreshToken: String!) {
refreshToken(object: { refreshToken: $refreshToken }) {
accessToken
refreshToken
customer {
email
}
}
}
`,
variables: {
refreshToken
}
})
expect(refreshToken_response.status).toBe(200)
expect(refreshToken_response.body.data.refreshToken).toEqual({
accessToken: expect.any(String),
refreshToken: expect.any(String),
customer: {
email: expect.any(String)
}
})
const compromised_refreshToken_response = await client.post(`/graphql`).send({
query: gql`
mutation refreshToken($refreshToken: String!) {
refreshToken(object: { refreshToken: $refreshToken }) {
accessToken
refreshToken
customer {
id
email
}
}
}
`,
variables: {
refreshToken
}
})
expect(compromised_refreshToken_response.status).toBe(200)
expect(compromised_refreshToken_response.body.errors[0].message).toBe(
'Invalid refresh token.'
)
const login_response_after_blocked = await client.post(`/graphql`).send({
query: gql`
mutation login($email: String!, $password: String!) {
login(object: { email: $email, password: $password }) {
accessToken
refreshToken
customer {
id
email
}
}
}
`,
variables: {
password: 'password',
email: user.email
}
})
expect(login_response_after_blocked.status).toBe(200)
expect(login_response_after_blocked.body.errors[0].message).toBe(
'Your account is temporarily disabled.'
)
})
test('registers new users with email/password based authentication', async () => {
const { app } = await setup([
auth().verifyEmails().user('Student').plugin(),
graphql().plugin()
])
const client = Supertest(app)
const user = fakeUser()
const register_response = await client.post(`/graphql`).send({
query: gql`
mutation register($email: String!, $password: String!) {
register(object: { email: $email, password: $password }) {
student {
id
email
emailVerifiedAt
}
}
}
`,
variables: {
email: user.email,
password: 'password'
}
})
expect(register_response.status).toBe(200)
expect(register_response.body.data.register.student).toEqual({
id: expect.any(String),
email: user.email,
emailVerifiedAt: null
})
})
test('authentication works when refresh tokens are disabled', async () => {
const { app } = await setup([
auth().verifyEmails().user('Student').plugin(),
graphql().plugin()
])
const client = Supertest(app)
const user = fakeUser()
const register_response = await client.post(`/graphql`).send({
query: gql`
mutation register($email: String!, $password: String!) {
register(object: { email: $email, password: $password }) {
student {
id
email
emailVerifiedAt
}
}
}
`,
variables: {
email: user.email,
password: 'password'
}
})
expect(register_response.status).toBe(200)
const login_response = await client.post(`/graphql`).send({
query: gql`
mutation login($email: String!, $password: String!) {
login(object: { email: $email, password: $password }) {
student {
id
email
emailVerifiedAt
}
accessToken
}
}
`,
variables: {
email: user.email,
password: 'password'
}
})
expect(login_response.status).toBe(200)
expect(login_response.body.data.login.student).toEqual({
id: expect.any(String),
email: user.email,
emailVerifiedAt: null
})
})
test('can signup with social authentication', async () => {
const githubConfig = {
key: 'TEST_KEY',
secret: 'TEST_SECRET'
}
process.env.HOST = '0.0.0.0'
process.env.PORT = '4400'
const { app, ctx } = await setup([
auth()
.verifyEmails()
.user('Doctor')
.social('github', githubConfig)
.plugin(),
rest().plugin()
])
const client = Supertest(app)
const getResponse = await client.get('/connect/github')
expect(getResponse.status).toBe(302)
expect(getResponse.headers.location).toBe(
`https://github.com/login/oauth/authorize?client_id=${githubConfig.key}&response_type=code&redirect_uri=http%3A%2F%2F0.0.0.0%3A4400%2Fconnect%2Fgithub%2Fcallback&scope=user%2Cuser%3Aemail`
)
const fakeIdentity = {
provider: 'github',
accessToken: 'TEST_ACCESS_TOKEN',
temporalToken: 'TEST_TEMPORAL_TOKEN',
email: 'test@email.com',
payload: JSON.stringify({
email: 'test@email.com'
}),
providerUserId: 'TEST_providerUserId'
}
await ctx.orm.em.persistAndFlush(
ctx.orm.em.create('OauthIdentity', fakeIdentity)
)
const postResponse = await client.post('/api/social/confirm').send({
accessToken: fakeIdentity.temporalToken
})
expect(postResponse.status).toBe(200)
expect(postResponse.body).toMatchObject({
data: {
doctor: {
email: fakeIdentity.email,
emailVerifiedAt: expect.any(String)
}
}
})
})
test('can verify registered user email', async () => {
const { app, ctx } = await setup([
auth().verifyEmails().user('Student').plugin(),
rest().plugin()
])
const client = Supertest(app)
const user = fakeUser()
const registerResponse = await client.post('/api/register').send(user)
const savedUser = await ctx.orm.em.findOne<{
email: string
emailVerificationToken: string
}>('Student', {
email: user.email
})
const response = await client
.post('/api/emails/verification/confirm')
.send({
emailVerificationToken: savedUser.emailVerificationToken
})
.set('Authorization', `Bearer ${registerResponse.body.data.accessToken}`)
expect(response.status).toBe(200)
expect(response.body.data.emailVerifiedAt).toBeDefined()
}) | the_stack |
import * as fs from 'fs';
import util from 'util';
import * as Tp from 'thingpedia';
import * as ThingTalk from 'thingtalk';
import JSONStream from 'JSONStream';
import csvparse from 'csv-parse';
import * as StreamUtils from '../../../lib/utils/stream-utils';
import { snakecase } from '../lib/utils';
import { clean } from '../../../lib/utils/misc-utils';
const URL = 'https://query.wikidata.org/sparql';
const Type = ThingTalk.Type;
const _cache = new Map();
const WikidataUnitToTTUnit : Record<string, string> = {
// time
'millisecond': 'ms',
'second': 's',
'minute': 'min',
'hour': 'h',
'day': 'day',
'week': 'week',
'month': 'mon',
'year': 'year',
// length
'millimetre': 'mm',
'centimetre': 'cm',
'metre': 'm',
'kilometre': 'km',
'inch': 'in',
'foot': 'ft',
'mile': 'mi',
// area
'square millimetre': 'mm2',
'square centimetre': 'cm2',
'square metre': 'm2',
'square kilometre': 'km2',
'square inch': 'in2',
'square foot': 'ft2',
'square mile': 'mi2',
// volume
'cubic millimetre': 'mm3',
'cubic centimetre': 'cm3',
'cubic metre': 'm3',
'cubic kilometre': 'km3',
'cubic inch': 'in3',
'cubic foot': 'ft3',
'cubic mile': 'mi3',
'gallon (US)': 'gal',
'gallon (UK)': 'galuk',
'liquid quart (US)': 'quart',
'quart (UK)': 'qtuk',
'liquid pint': 'pint',
'pint (UK)': 'pintuk',
'litre': 'l',
'hectoliter': 'hl',
'centilitre': 'cl',
'millilitre': 'ml',
'teaspoon': 'tsp',
'tablespoon': 'tbsp',
'cup': 'cup',
'fluid ounce': 'floz',
// speed
'metre per second': 'mps',
'kilometre per hour': 'kmph',
'miles per hour': 'mph',
// weight
'kilogram': 'kg',
'gram': 'g',
'milligram': 'mg',
'pound': 'lb',
'ounce': 'oz',
// pressure
'pascal': 'Pa',
'bar': 'bar',
'pound per square inch': 'psi',
'millimeter of mercury': 'mmHg',
'standard atmosphere': 'atm',
// temperature
'degree Celsius': 'C',
'degree Fahrenheit': 'F',
'kelvin': 'K',
// energy
'kilojoule': 'KJ',
'kilocalorie': 'kcal',
// file and memory size
'byte': 'byte',
'kilobyte': 'KB',
'kibibyte': 'KiB',
'megabyte': 'MB',
'mebibyte': 'MiB',
'gigabyte': 'GB',
'gibibyte': 'GiB',
'terabyte': 'TB',
'tebibyte': 'TiB',
// power
'watt': 'W',
'kilowatt': 'kW',
// luminous flux, luminous power
'lumen': 'lm',
// luminous emittance
'lux': 'lx',
// decibel
'decibel': 'dB',
// decibel-milliwatts,
'dBm': 'dBm',
// currency
'United States dollar': 'usd',
'euro': 'eur',
'renminbi': 'cny',
'Iranian rial': 'irr',
'Hong Kong dollar': 'hkd',
'Japanese yen': 'jpy',
'South Korean won': 'krw',
'pound sterling': 'gbp',
'Indian rupee': 'inr',
'Canadian dollar': 'cad',
'Australian dollar': 'aud',
'Swiss franc': 'chf',
};
/**
* Covert wikidata unit into thingtalk unit
* @param wikidataUnit
*/
function unitConverter(wikidataUnit : string) : string {
return WikidataUnitToTTUnit[wikidataUnit];
}
/**
* Run SPARQL query on wikidata endpoint and retrieve results
* @param {string} query: SPARQL query
* @returns {Promise<*>}
*/
async function wikidataQuery(query : string) : Promise<any[]> {
if (_cache.has(query))
return _cache.get(query);
try {
const result = await Tp.Helpers.Http.get(`${URL}?query=${encodeURIComponent(query)}`, {
accept: 'application/json'
});
const parsed = JSON.parse(result).results.bindings;
_cache.set(query, parsed);
return parsed;
} catch(e) {
throw new Error('The connection timed out waiting for a response');
}
}
/**
* Get the label of a given property
* @param {string} propertyId: the id of the property
* @returns {Promise<null|string>}: the label of the property
*/
async function getPropertyLabel(propertyId : string) : Promise<string|null> {
const query = `SELECT DISTINCT ?propLabel WHERE {
?prop wikibase:directClaim wdt:${propertyId} .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
} LIMIT 1`;
const result = await wikidataQuery(query);
if (result.length > 0)
return result[0].propLabel.value;
return null;
}
/**
* Get alternative labels of a given property
* @param {string} propertyId: the id of the property
* @returns {Promise<Array.string>}: the label of the property
*/
async function getPropertyAltLabels(propertyId : string) : Promise<string[]|null> {
const query = `SELECT DISTINCT ?propAltLabel WHERE {
?prop wikibase:directClaim wdt:${propertyId} .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}`;
const result = await wikidataQuery(query);
if (result.length > 0 && result[0].propAltLabel)
return result[0].propAltLabel.value.split(',');
return null;
}
/**
* Get the label of a given item
* @param {string} itemId: the id of the item
* @returns {Promise<null|string>}: the label of the item
*/
async function getItemLabel(itemId : string) : Promise<string|null> {
const query = `SELECT ?label WHERE {
wd:${itemId} rdfs:label ?label .
FILTER (langMatches( lang(?label), "en" ) )
} LIMIT 1`;
const result = await wikidataQuery(query);
if (result.length > 0)
return result[0].label.value;
return null;
}
/**
* Get a list of common properties given a domain
* @param {string} domainId: the id of the domain, e.g. "Q5" for human domain
* @returns {Promise<Array.string>}: a list of property ids
*/
async function getPropertyList(domainId : string) : Promise<string[]> {
const query = `SELECT ?property WHERE {
wd:${domainId} wdt:P1963 ?property .
}`;
const result = await wikidataQuery(query);
return result.map((r : any) => r.property.value.slice('http://www.wikidata.org/entity/'.length));
}
/**
* Get the value type constraint (Q21510865) of a property
* @param {string} propertyId
* @returns {Promise<Array.Object<id,value>>} A list of allowed value types and their labels
*/
async function getValueTypeConstraint(propertyId : string) : Promise<Array<Record<string, string>>> {
const query = `SELECT ?value ?valueLabel WHERE {
wd:${propertyId} p:P2302 ?statement .
?statement ps:P2302 wd:Q21510865 .
?statement pq:P2308 ?value .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}`;
const result = await wikidataQuery(query);
return result.map((r : any) => {
return { id: r.value.value, label: r.valueLabel.value };
});
}
/**
* Get the one-of constraint (Q21510859) of a property
* This allows to detect Enum types
*
* @param propertyId
* @returns {Promise<Array.String>} A list of enum values
*/
async function getOneOfConstraint(propertyId : string) : Promise<string[]> {
const query = `SELECT ?value ?valueLabel WHERE {
wd:${propertyId} p:P2302 ?statement .
?statement ps:P2302 wd:Q21510859 .
?statement pq:P2305 ?value .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}`;
const result = await wikidataQuery(query);
return result.map((r) => r.valueLabel.value);
}
/**
* Get the allowed units (Q21514353) of a property
* This allows to detect Measure types
*
* @param propertyId
* @returns {Promise<Array.String>} A list of allowed units
*/
async function getAllowedUnits(propertyId : string) : Promise<string[]> {
const query = `SELECT ?value ?valueLabel WHERE {
wd:${propertyId} p:P2302 ?statement .
?statement ps:P2302 wd:Q21514353 .
?statement pq:P2305 ?value .
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}`;
const result = await wikidataQuery(query);
return result.map((r) => r.valueLabel.value);
}
/**
* Get the range of a numeric field
*
* @param propertyId
* @returns {Object<max, min>|null} A list of allowed units
*/
async function getRangeConstraint(propertyId : string) : Promise<Record<string, number>|null> {
const query = `SELECT ?max ?min WHERE {
wd:${propertyId} p:P2302 ?statement .
?statement ps:P2302 wd:Q21510860 .
?statement pq:P2312 ?max .
?statement pq:P2313 ?min .
}`;
const result = await wikidataQuery(query);
if (result.length > 0) {
const range : Record<string, number> = {};
if (result[0].max)
range.max = result[0].max.value;
if (result[0].min)
range.min = result[0].min.value;
if (Object.keys(range).length > 0)
return range;
}
return null;
}
/**
* Get the class (instance of) of a given wikidata property or entity
* @param {string} id: the id of a property or an entity
* @returns {Promise<Array.string>}: list of classes
*/
async function getClasses(id : string) : Promise<string[]> {
const query = `SELECT ?class WHERE {
wd:${id} wdt:P31 ?class .
}`;
const result = await wikidataQuery(query);
return result.map((r) => r.class.value.slice('http://www.wikidata.org/entity/'.length));
}
/**
* Get wikidata equivalent of a given wikidata property or entity
* @param {string} id: the id of a property or an entity
* @returns {Promise<Array.string>}: list of classes
*/
async function getEquivalent(id : string) : Promise<string[]> {
const query = `SELECT ?class WHERE {
wd:${id} wdt:P460 ?class .
}`;
const result = await wikidataQuery(query);
return result.map((r) => r.class.value.slice('http://www.wikidata.org/entity/'.length));
}
async function getType(property : string) : Promise<InstanceType<typeof Type>> {
const classes = await getClasses(property);
if (classes.includes('Q18636219')) // Wikidata property with datatype 'time'
return Type.Date;
const units = await getAllowedUnits(property);
if (units.length > 0) {
if (units.includes('kilogram'))
return new Type.Measure('kg');
if (units.includes('metre') || units.includes('kilometre'))
return new Type.Measure('m');
if (units.includes('second') || units.includes('year'))
return new Type.Measure('ms');
if (units.includes('degree Celsius'))
return new Type.Measure('C');
if (units.includes('metre per second') || units.includes('kilometre per second'))
return new Type.Measure('mps');
if (units.includes('square metre'))
return new Type.Measure('m2');
if (units.includes('cubic metre'))
return new Type.Measure('m3');
if (units.includes('percent'))
return Type.Number;
if (units.includes('United States dollar'))
return Type.Currency;
if (units.includes('years old'))
return Type.Number; // To-do
if (units.includes('gram per cubic metre'))
return Type.Number; // To-do
console.error(`Unknown measurement type with unit ${units.join(', ')} for ${property}`);
return Type.Number;
}
const range = await getRangeConstraint(property);
if (range)
return Type.Number;
const subpropertyOf = await wikidataQuery(`SELECT ?value WHERE { wd:${property} wdt:P1647 ?value. } `);
if (subpropertyOf.some((property) => property.value.value === 'http://www.wikidata.org/entity/P18'))
return new Type.Entity('tt:picture');
if (subpropertyOf.some((property) => property.value.value === 'http://www.wikidata.org/entity/P2699'))
return new Type.Entity('tt:url');
// majority or arrays of string so this may be better default.
return Type.String;
}
function argnameFromLabel(label : string) : string {
// if label is a keyword or starts with number
if (ThingTalk.Syntax.KEYWORDS.has(label) || /^\d/.test(label))
label = `_${label}`;
return snakecase(label)
.replace(/'/g, '') // remove apostrophe
.replace(/,/g, '') // remove comma
.replace(/_\/_/g, '_or_') // replace slash by or
.replace(/[(|)]/g, '') // replace parentheses
.replace(/-/g, '_') // replace -
.replace(/\s/g, '_') // replace whitespace
.normalize("NFD").replace(/[\u0300-\u036f]/g, "") // remove accent
.replace(/[\W]+/g, '');
}
function getElementType(type : InstanceType<typeof Type>) : InstanceType<typeof Type> {
if (type instanceof Type.Array)
return getElementType(type.elem as InstanceType<typeof Type>);
return type;
}
async function readJson(file : string) {
const data = new Map();
const pipeline = fs.createReadStream(file).pipe(JSONStream.parse('$*'));
pipeline.on('data', (item : { key : string, value : string}) => {
data.set(item.key, item.value);
});
pipeline.on('error', (error : Error) => console.error(error));
await StreamUtils.waitEnd(pipeline);
return data;
}
async function dumpMap(file : string, map : Map<string, any>) {
const data : Record<string, any> = {};
for (const [key, value] of map)
data[key] = value instanceof Map ? Object.fromEntries(value) : value;
await util.promisify(fs.writeFile)(file, JSON.stringify(data, undefined, 2));
}
class Domains {
private _path : string;
private _map : Record<string, Record<string, any>>;
private _domains : string[];
private _csqaTypes : string[];
private _wikidataTypes : string[];
constructor(options : { path : string }) {
this._path = options.path;
this._map = {};
this._domains = [];
this._csqaTypes = [];
this._wikidataTypes = [];
}
get domains() {
return this._domains;
}
get wikidataTypes() {
return this._wikidataTypes;
}
async init() {
const pipeline = fs.createReadStream(this._path).pipe(csvparse({
columns: ['domain', 'csqa-type', 'wikidata-types', 'all-types'],
delimiter: '\t',
relax: true
}));
pipeline.on('data', (row) => {
this._domains.push(row.domain);
if (!this._csqaTypes.includes(row['csqa-type']))
this._csqaTypes.push(row['csqa-type']);
for (const entry of row['wikidata-types'].split(' ')) {
const type = entry.split(':')[0];
if (!this._wikidataTypes.includes(type))
this._wikidataTypes.push(type);
}
const csqaType = row['csqa-type'];
const wikidataTypes = row['wikidata-types'].split(' ').map((x : string) => x.split(':')[0]);
const wikidataTypeLabels = row['wikidata-types'].split(' ').map((x : string) => x.split(':')[1]);
this._map[row.domain] = {
'csqa-type': csqaType,
'wikidata-types': wikidataTypes,
'wikidata-types-labels': wikidataTypeLabels.map(clean),
'wikidata-subject': [csqaType, ...wikidataTypes],
};
});
pipeline.on('error', (error) => console.error(error));
await StreamUtils.waitEnd(pipeline);
}
getCSQAType(domain : string) : string {
return this._map[domain]['csqa-type'];
}
getWikidataTypes(domain : string) : string[] {
return this._map[domain]['wikidata-types'];
}
getWikidataTypeLabels(domain : string) : string[] {
return this._map[domain]['wikidata-types-labels'];
}
getWikidataSubjects(domain : string) : string[] {
return this._map[domain]['wikidata-subject'];
}
getDomainByCSQAType(csqaType : string) : string|null {
for (const [domain, map] of Object.entries(this._map)) {
if (map['csqa-type'] === csqaType)
return domain;
}
return null;
}
getDomainsByWikidataType(wikidataType : string) : string[] {
const domains = [];
for (const [domain, map] of Object.entries(this._map)) {
if (map['wikidata-types'].includes(wikidataType))
domains.push(domain);
}
return domains;
}
getDomainsByWikidataTypes(wikidataTypes : string[]) : string[] {
const domains = wikidataTypes.map((type : string) => this.getDomainsByWikidataType(type));
return [...new Set(domains.flat())];
}
}
export {
unitConverter,
wikidataQuery,
getPropertyLabel,
getPropertyAltLabels,
getItemLabel,
getPropertyList,
getValueTypeConstraint,
getOneOfConstraint,
getAllowedUnits,
getRangeConstraint,
getClasses,
getEquivalent,
getType,
getElementType,
readJson,
dumpMap,
argnameFromLabel,
Domains
}; | the_stack |
import {are_in_browser, initCarr, merge, asyncForEach, asyncSeries, ext_classname, initString, int_classname, descriptor2typestr} from './util';
import SafeMap from './SafeMap';
import {dumpStats} from './methods';
import {ClassData, ReferenceClassData, ArrayClassData} from './ClassData';
import {BootstrapClassLoader, ClassLoader} from './ClassLoader';
import * as fs from 'fs';
import * as path from 'path';
import * as buffer from 'buffer';
import {JVMThread} from './threading';
import {ThreadStatus, JVMStatus} from './enums';
import Heap from './heap';
import assert from './assert';
import {JVMOptions} from './interfaces';
import * as JVMTypes from '../includes/JVMTypes';
import Parker from './parker';
import ThreadPool from './threadpool';
import * as JDKInfo from '../vendor/java_home/jdk.json';
import global from './global';
import getGlobalRequire from './global_require';
import * as BrowserFS from 'browserfs';
import * as DoppioJVM from './doppiojvm';
import {setImmediate} from 'browserfs';
declare var RELEASE: boolean;
if (typeof RELEASE === 'undefined') global.RELEASE = false;
// For version information.
let pkg: any;
if (are_in_browser()) {
pkg = require('../package.json');
} else {
pkg = require('../../../package.json');
}
// XXX: We currently initialize these classes at JVM bootup. This is expensive.
// We should attempt to prune this list as much as possible.
var coreClasses = [
'Ljava/lang/String;',
'Ljava/lang/Class;', 'Ljava/lang/ClassLoader;',
'Ljava/lang/reflect/Constructor;', 'Ljava/lang/reflect/Field;',
'Ljava/lang/reflect/Method;',
'Ljava/lang/Error;', 'Ljava/lang/StackTraceElement;',
'Ljava/lang/System;',
'Ljava/lang/Thread;',
'Ljava/lang/ThreadGroup;',
'Ljava/lang/Throwable;',
'Ljava/nio/ByteOrder;',
'Lsun/misc/VM;', 'Lsun/reflect/ConstantPool;', 'Ljava/lang/Byte;',
'Ljava/lang/Character;', 'Ljava/lang/Double;', 'Ljava/lang/Float;',
'Ljava/lang/Integer;', 'Ljava/lang/Long;', 'Ljava/lang/Short;',
'Ljava/lang/Void;', 'Ljava/io/FileDescriptor;',
'Ljava/lang/Boolean;', '[Lsun/management/MemoryManagerImpl;',
'[Lsun/management/MemoryPoolImpl;',
// Contains important FS constants used by natives. These constants are
// inlined into JCL class files, so it typically never gets initialized
// implicitly by the JVM.
'Lsun/nio/fs/UnixConstants;'
];
/**
* Encapsulates a single JVM instance.
*/
class JVM {
private systemProperties: {[prop: string]: string} = null;
private internedStrings: SafeMap<JVMTypes.java_lang_String> = new SafeMap<JVMTypes.java_lang_String>();
private bsCl: BootstrapClassLoader = null;
private threadPool: ThreadPool<JVMThread> = null;
private natives: { [clsName: string]: { [methSig: string]: Function } } = {};
// 20MB heap
// @todo Make heap resizeable.
private heap: Heap = new Heap(20 * 1024 * 1024);
private nativeClasspath: string[] = null;
private startupTime: Date = new Date();
private terminationCb: (code: number) => void = null;
// The initial JVM thread used to kick off execution.
private firstThread: JVMThread = null;
private responsiveness: number | (() => number) = null;
private enableSystemAssertions: boolean = false;
private enabledAssertions: boolean | string[] = false;
private disabledAssertions: string[] = [];
private printJITCompilation: boolean = false;
private systemClassLoader: ClassLoader = null;
private nextRef: number = 0;
// Set of all of the methods we want vtrace to be enabled on.
// DEBUG builds only.
private vtraceMethods: {[fullSig: string]: boolean} = {};
// [DEBUG] directory to dump compiled code to.
private dumpCompiledCodeDir: string = null;
// Handles parking/unparking threads.
private parker = new Parker();
// The current status of the JVM.
private status: JVMStatus = JVMStatus.BOOTING;
// The JVM's planned exit code.
private exitCode: number = 0;
// is JIT disabled?
private jitDisabled: boolean = false;
private dumpJITStats: boolean = false;
// Get the environment's require variable, indirectly.
// Hidden from webpack and other builders, as it confuses them.
private globalRequire: Function = null;
public static isReleaseBuild(): boolean {
return typeof(RELEASE) !== 'undefined' && RELEASE;
}
private static getNativeMethodModules(): (() => any)[] {
if (!this._haveAddedBuiltinNativeModules) {
// NOTE: Replace with an ES6 import when we switch to a supporting bundler like Rollup.
// Currently cannot import these above to avoid circular imports, which Webpack does not
// support.
JVM.registerNativeModule(require('./natives/doppio').default);
JVM.registerNativeModule(require('./natives/java_io').default);
JVM.registerNativeModule(require('./natives/java_lang').default);
JVM.registerNativeModule(require('./natives/java_net').default);
JVM.registerNativeModule(require('./natives/java_nio').default);
JVM.registerNativeModule(require('./natives/java_security').default);
JVM.registerNativeModule(require('./natives/java_util').default);
JVM.registerNativeModule(require('./natives/sun_font').default);
JVM.registerNativeModule(require('./natives/sun_management').default);
JVM.registerNativeModule(require('./natives/sun_misc').default);
JVM.registerNativeModule(require('./natives/sun_net').default);
JVM.registerNativeModule(require('./natives/sun_nio').default);
JVM.registerNativeModule(require('./natives/sun_reflect').default);
this._haveAddedBuiltinNativeModules = true;
}
return this._nativeMethodModules;
}
private static _nativeMethodModules: (() => any)[] = [];
private static _haveAddedBuiltinNativeModules = false;
/**
* Registers a JavaScript module that provides particular native methods with Doppio.
* All new JVMs constructed will auto-run this module to add its natives.
*/
public static registerNativeModule(mod: () => any): void {
this._nativeMethodModules.push(mod);
}
/**
* (Async) Construct a new instance of the Java Virtual Machine.
*/
constructor(opts: JVMOptions, cb: (e: any, jvm?: JVM) => void) {
if (typeof(opts.doppioHomePath) !== 'string') {
throw new TypeError("opts.doppioHomePath *must* be specified.");
}
opts = <JVMOptions> merge(JVM.getDefaultOptions(opts.doppioHomePath), opts);
this.jitDisabled = opts.intMode;
this.dumpJITStats = opts.dumpJITStats;
var bootstrapClasspath: string[] = opts.bootstrapClasspath.map((p: string): string => path.resolve(p)),
// JVM bootup tasks, from first to last task.
bootupTasks: {(next: (err?: any) => void): void}[] = [],
firstThread: JVMThread,
firstThreadObj: JVMTypes.java_lang_Thread;
// Sanity checks.
if (!Array.isArray(opts.bootstrapClasspath) || opts.bootstrapClasspath.length === 0) {
throw new TypeError("opts.bootstrapClasspath must be specified as an array of file paths.");
}
if (!Array.isArray(opts.classpath)) {
throw new TypeError("opts.classpath must be specified as an array of file paths.");
}
if (typeof(opts.javaHomePath) !== 'string') {
throw new TypeError("opts.javaHomePath must be specified.");
}
if (!opts.nativeClasspath) {
opts.nativeClasspath = [];
}
if (!Array.isArray(opts.nativeClasspath)) {
throw new TypeError("opts.nativeClasspath must be specified as an array of file paths.");
}
this.nativeClasspath = opts.nativeClasspath;
if (opts.enableSystemAssertions) {
this.enableSystemAssertions = opts.enableSystemAssertions;
}
if (opts.enableAssertions) {
this.enabledAssertions = opts.enableAssertions;
}
if (opts.disableAssertions) {
this.disabledAssertions = opts.disableAssertions;
}
this.responsiveness = opts.responsiveness;
this._initSystemProperties(bootstrapClasspath,
opts.classpath.map((p: string): string => path.resolve(p)),
path.resolve(opts.javaHomePath),
path.resolve(opts.tmpDir),
opts.properties);
/**
* Task #1: Initialize native methods.
*/
bootupTasks.push((next: (err?: any) => void): void => {
this.initializeNatives(next);
});
/**
* Task #2: Construct the bootstrap class loader.
*/
bootupTasks.push((next: (err?: any) => void): void => {
this.bsCl =
new BootstrapClassLoader(this.systemProperties['java.home'], bootstrapClasspath, next);
});
/**
* Task #3: Construct the thread pool, resolve thread class, and construct
* the first thread.
*/
bootupTasks.push((next: (err?: any) => void): void => {
this.threadPool = new ThreadPool<JVMThread>((): boolean => { return this.threadPoolIsEmpty(); });
// Resolve Ljava/lang/Thread so we can fake a thread.
// NOTE: This should never actually use the Thread object unless
// there's an error loading java/lang/Thread and associated classes.
this.bsCl.resolveClass(null, 'Ljava/lang/Thread;', (threadCdata: ReferenceClassData<JVMTypes.java_lang_Thread>) => {
if (threadCdata == null) {
// Failed.
next("Failed to resolve java/lang/Thread.");
} else {
// Construct a thread.
firstThreadObj = new (threadCdata.getConstructor(null))(null);
firstThreadObj.$thread = firstThread = this.firstThread = new JVMThread(this, this.threadPool, firstThreadObj);
firstThreadObj.ref = 1;
firstThreadObj['java/lang/Thread/priority'] = 5;
firstThreadObj['java/lang/Thread/name'] = initCarr(this.bsCl, 'main');
firstThreadObj['java/lang/Thread/blockerLock'] = new ((<ReferenceClassData<JVMTypes.java_lang_Object>> this.bsCl.getResolvedClass('Ljava/lang/Object;')).getConstructor(firstThread))(firstThread);
next();
}
});
});
/**
* Task #4: Preinitialize some essential JVM classes, and initializes the
* JVM's ThreadGroup once that class is initialized.
*/
bootupTasks.push((next: (err?: any) => void): void => {
asyncForEach<string>(coreClasses, (coreClass: string, nextItem: (err?: any) => void) => {
this.bsCl.initializeClass(firstThread, coreClass, (cdata: ClassData) => {
if (cdata == null) {
nextItem(`Failed to initialize ${coreClass}`);
} else {
// One of the later preinitialized classes references Thread.group.
// Initialize the system's ThreadGroup now.
if (coreClass === 'Ljava/lang/ThreadGroup;') {
// Construct a ThreadGroup object for the first thread.
var threadGroupCons = (<ReferenceClassData<JVMTypes.java_lang_ThreadGroup>> cdata).getConstructor(firstThread),
groupObj = new threadGroupCons(firstThread);
groupObj['<init>()V'](firstThread, null, (e?: JVMTypes.java_lang_Throwable) => {
// Tell the initial thread to use this group.
firstThreadObj['java/lang/Thread/group'] = groupObj;
nextItem(e);
});
} else {
nextItem();
}
}
});
}, next);
});
/**
* Task #5: Initialize the system class.
*/
bootupTasks.push((next: (err?: any) => void): void => {
// Initialize the system class (initializes things like println/etc).
var sysInit = <typeof JVMTypes.java_lang_System> (<ReferenceClassData<JVMTypes.java_lang_System>> this.bsCl.getInitializedClass(firstThread, 'Ljava/lang/System;')).getConstructor(firstThread);
sysInit['java/lang/System/initializeSystemClass()V'](firstThread, null, next);;
});
/**
* Task #6: Initialize the application's
*/
bootupTasks.push((next: (err?: any) => void) => {
var clCons = <typeof JVMTypes.java_lang_ClassLoader> (<ReferenceClassData<JVMTypes.java_lang_ClassLoader>> this.bsCl.getInitializedClass(firstThread, 'Ljava/lang/ClassLoader;')).getConstructor(firstThread);
clCons['java/lang/ClassLoader/getSystemClassLoader()Ljava/lang/ClassLoader;'](firstThread, null, (e?: JVMTypes.java_lang_Throwable, rv?: JVMTypes.java_lang_ClassLoader) => {
if (e) {
next(e);
} else {
this.systemClassLoader = rv.$loader;
firstThreadObj['java/lang/Thread/contextClassLoader'] = rv;
// Initialize assertion data.
// TODO: Is there a better way to force this? :|
let defaultAssertionStatus = this.enabledAssertions === true ? 1 : 0;
rv['java/lang/ClassLoader/setDefaultAssertionStatus(Z)V'](firstThread, [defaultAssertionStatus], next);
}
});
});
/**
* Task #7: Initialize DoppioJVM's security provider for things like cryptographically strong RNG.
*/
bootupTasks.push((next: (err?: any) => void) => {
this.bsCl.initializeClass(firstThread, 'Ldoppio/security/DoppioProvider;', (cdata) => {
next(cdata ? null : new Error(`Failed to initialize DoppioProvider.`));
});
});
// Perform bootup tasks, and then trigger the callback function.
asyncSeries(bootupTasks, (err?: any): void => {
// XXX: Without setImmediate, the firstThread won't clear out the stack
// frame that triggered us, and the firstThread won't transition to a
// 'terminated' status.
setImmediate(() => {
if (err) {
this.status = JVMStatus.TERMINATED;
cb(err);
} else {
this.status = JVMStatus.BOOTED;
cb(null, this);
}
});
});
}
public getResponsiveness():number {
const resp = this.responsiveness;
if (typeof resp === 'number') {
return resp;
} else if (typeof resp === 'function') {
return resp();
}
}
public static getDefaultOptions(doppioHome: string): JVMOptions {
let javaHome = path.join(doppioHome, 'vendor', 'java_home');
return {
doppioHomePath: doppioHome,
classpath: ['.'],
bootstrapClasspath: JDKInfo.classpath.map((item) => path.join(javaHome, item)),
javaHomePath: javaHome,
nativeClasspath: [],
enableSystemAssertions: false,
enableAssertions: false,
disableAssertions: null,
properties: {},
tmpDir: '/tmp',
responsiveness: 1000,
intMode: false,
dumpJITStats: false
};
}
/**
* Get the URL to the version of the JDK that DoppioJVM was compiled with.
*/
public static getCompiledJDKURL(): string {
return JDKInfo.url;
}
/**
* Get the JDK information that DoppioJVM was compiled against.
*/
public static getJDKInfo(): any {
return JDKInfo;
}
public getSystemClassLoader(): ClassLoader {
return this.systemClassLoader;
}
/**
* Get the next "ref" number for JVM objects.
*/
public getNextRef(): number {
return this.nextRef++;
}
/**
* Retrieve the JVM's parker. Handles parking/unparking threads.
*/
public getParker(): Parker {
return this.parker;
}
/**
* Run the specified class on this JVM instance.
* @param className The name of the class to run. Can be specified in either
* foo.bar.Baz or foo/bar/Baz format.
* @param args Command line arguments passed to the class.
* @param cb Called when the JVM finishes executing. Called with 'true' if
* the JVM exited normally, 'false' if there was an error.
*/
public runClass(className: string, args: string[], cb: (code: number) => void): void {
if (this.status !== JVMStatus.BOOTED) {
switch (this.status) {
case JVMStatus.BOOTING:
throw new Error(`JVM is currently booting up. Please wait for it to call the bootup callback, which you passed to the constructor.`);
case JVMStatus.RUNNING:
throw new Error(`JVM is already running.`);
case JVMStatus.TERMINATED:
throw new Error(`This JVM has already terminated. Please create a new JVM.`);
case JVMStatus.TERMINATING:
throw new Error(`This JVM is currently terminating. You should create a new JVM for each class you wish to run.`);
}
}
this.terminationCb = cb;
var thread = this.firstThread;
assert(thread != null, `Thread isn't created yet?`);
// Convert foo.bar.Baz => Lfoo/bar/Baz;
className = int_classname(className);
// Initialize the class.
this.systemClassLoader.initializeClass(thread, className, (cdata: ReferenceClassData<any>) => {
// If cdata is null, there was an error that ended execution.
if (cdata != null) {
// Convert the arguments.
var strArrCons = (<ArrayClassData<JVMTypes.java_lang_String>> this.bsCl.getInitializedClass(thread, '[Ljava/lang/String;')).getConstructor(thread),
jvmifiedArgs = new strArrCons(thread, args.length), i: number;
for (i = 0; i < args.length; i++) {
jvmifiedArgs.array[i] = initString(this.bsCl, args[i]);
}
// Find the main method, and run it.
this.status = JVMStatus.RUNNING;
var cdataStatics = <any> cdata.getConstructor(thread);
if (cdataStatics['main([Ljava/lang/String;)V']) {
cdataStatics['main([Ljava/lang/String;)V'](thread, [jvmifiedArgs]);
} else {
thread.throwNewException("Ljava/lang/NoSuchMethodError;", `Could not find main method in class ${cdata.getExternalName()}.`);
}
} else {
process.stdout.write(`Error: Could not find or load main class ${ext_classname(className)}\n`);
// Erroneous exit.
this.terminationCb(1);
}
});
}
/**
* Returns 'true' if confined to interpreter mode
*/
public isJITDisabled(): boolean {
return this.jitDisabled;
}
/**
* [DEBUG] Returns 'true' if the specified method should be vtraced.
*/
public shouldVtrace(sig: string): boolean {
return this.vtraceMethods[sig] === true;
}
/**
* [DEBUG] Specify a method to vtrace.
*/
public vtraceMethod(sig: string): void {
this.vtraceMethods[sig] = true;
}
/**
* Run the specified JAR file on this JVM instance.
* @param args Command line arguments passed to the class.
* @param cb Called when the JVM finishes executing. Called with 'true' if
* the JVM exited normally, 'false' if there was an error.
*/
public runJar(args: string[], cb: (code: number) => void): void {
this.runClass('doppio.JarLauncher', args, cb);
}
/**
* Called when the ThreadPool is empty.
*/
private threadPoolIsEmpty(): boolean {
var systemClass: ReferenceClassData<JVMTypes.java_lang_System>,
systemCons: typeof JVMTypes.java_lang_System;
switch (this.status) {
case JVMStatus.BOOTING:
// Ignore empty thread pools during boot process.
return false;
case JVMStatus.BOOTED:
assert(false, `Thread pool should not become empty after JVM is booted, but before it begins to run.`);
return false;
case JVMStatus.RUNNING:
this.status = JVMStatus.TERMINATING;
systemClass = <any> this.bsCl.getInitializedClass(this.firstThread, 'Ljava/lang/System;');
assert(systemClass !== null, `Invariant failure: System class must be initialized when JVM is in RUNNING state.`);
systemCons = <any> systemClass.getConstructor(this.firstThread);
// This is a normal, non-erroneous exit. When this function completes, threadPoolIsEmpty() will be invoked again.
systemCons['java/lang/System/exit(I)V'](this.firstThread, [0]);
return false;
case JVMStatus.TERMINATED:
assert(false, `Invariant failure: Thread pool cannot be emptied post-JVM termination.`);
return false;
case JVMStatus.TERMINATING:
if (!RELEASE && this.dumpJITStats) {
dumpStats();
}
this.status = JVMStatus.TERMINATED;
if (this.terminationCb) {
this.terminationCb(this.exitCode);
}
this.firstThread.close();
return true;
}
}
/**
* Check if the JVM has started running the main class.
*/
public hasVMBooted(): boolean {
return !(this.status === JVMStatus.BOOTING || this.status === JVMStatus.BOOTED);
}
/**
* Completely halt the JVM.
*/
public halt(status: number): void {
this.exitCode = status;
this.status = JVMStatus.TERMINATING;
this.threadPool.getThreads().forEach((t) => {
t.setStatus(ThreadStatus.TERMINATED);
});
}
/**
* Retrieve the given system property.
*/
public getSystemProperty(prop: string): string {
return this.systemProperties[prop];
}
/**
* Retrieve an array of all of the system property names.
*/
public getSystemPropertyNames(): string[] {
return Object.keys(this.systemProperties);
}
/**
* Retrieve the unmanaged heap.
*/
public getHeap(): Heap {
return this.heap;
}
/**
* Interns the given JavaScript string. Returns the interned string.
*/
public internString(str: string, javaObj?: JVMTypes.java_lang_String): JVMTypes.java_lang_String {
if (this.internedStrings.has(str)) {
return this.internedStrings.get(str);
} else {
if (!javaObj) {
javaObj = initString(this.bsCl, str);
}
this.internedStrings.set(str, javaObj);
return javaObj;
}
}
/**
* Evaluate native modules. Emulates CommonJS functionality.
*/
private evalNativeModule(mod: string): any {
if (!this.globalRequire) {
this.globalRequire = getGlobalRequire();
}
let rv: any;
/**
* Called by the native method file. Registers the package's native
* methods with the JVM.
*/
function registerNatives(defs: any): void {
rv = defs;
}
// Provide the natives with the Doppio API, if needed.
const globalRequire = this.globalRequire;
/**
* An emulation of CommonJS require() for the modules.
*/
function moduleRequire(name: string): any {
switch(name) {
case 'doppiojvm':
case '../doppiojvm':
return DoppioJVM;
case 'fs':
return fs;
case 'path':
return path;
case 'buffer':
return buffer;
case 'browserfs':
return BrowserFS;
default:
return globalRequire(name);
}
}
/**
* Emulate AMD module 'define' function for natives compiled as AMD modules.
*/
function moduleDefine(resources: string[], module: Function): void {
let args: any[] = [];
resources.forEach(function(resource) {
switch (resource) {
case 'require':
args.push(moduleRequire);
break;
case 'exports':
args.push({});
break;
default:
args.push(moduleRequire(resource));
break;
}
});
module.apply(null, args);
}
const modFcn = new Function("require", "define", "registerNatives", "process", "DoppioJVM", "Buffer", mod);
modFcn(moduleRequire, moduleDefine, registerNatives, process, DoppioJVM, Buffer);
return rv;
}
/**
* Register native methods with the virtual machine.
*/
public registerNatives(newNatives: { [clsName: string]: { [methSig: string]: Function } }): void {
var clsName: string, methSig: string;
for (clsName in newNatives) {
if (newNatives.hasOwnProperty(clsName)) {
if (!this.natives.hasOwnProperty(clsName)) {
this.natives[clsName] = {};
}
var clsMethods = newNatives[clsName];
for (methSig in clsMethods) {
if (clsMethods.hasOwnProperty(methSig)) {
// Don't check if it exists already. This allows us to overwrite
// native methods dynamically at runtime.
this.natives[clsName][methSig] = clsMethods[methSig];
}
}
}
}
}
/**
* Convenience function. Register a single native method with the virtual
* machine. Can be used to update existing native methods based on runtime
* information.
*/
public registerNative(clsName: string, methSig: string, native: Function): void {
this.registerNatives({ [clsName]: { [methSig]: native } });
}
/**
* Retrieve the native method for the given method of the given class.
* Returns null if none found.
*/
public getNative(clsName: string, methSig: string): Function {
clsName = descriptor2typestr(clsName);
if (this.natives.hasOwnProperty(clsName)) {
var clsMethods = this.natives[clsName];
if (clsMethods.hasOwnProperty(methSig)) {
return clsMethods[methSig];
}
}
return null;
}
/**
* !!DO NOT MUTATE THE RETURNED VALUE!!
* Used by the find_invalid_natives tool.
*/
public getNatives(): { [clsName: string]: { [methSig: string]: Function } } {
return this.natives;
}
/**
* Loads in all of the native method modules prior to execution.
* Currently a hack around our
* @todo Make neater with async stuff.
*/
private initializeNatives(doneCb: () => void): void {
const registeredModules = JVM.getNativeMethodModules();
for (let i = 0; i < registeredModules.length; i++) {
this.registerNatives(registeredModules[i]());
}
var nextDir = () => {
if (i === this.nativeClasspath.length) {
// Next phase: Load up the files.
let count: number = processFiles.length;
if (count === 0) {
return doneCb();
}
processFiles.forEach((file: string) => {
fs.readFile(file, (err: any, data: NodeBuffer) => {
if (!err) {
this.registerNatives(this.evalNativeModule(data.toString()));
}
if (--count === 0) {
doneCb();
}
});
});
} else {
var dir = this.nativeClasspath[i++];
fs.readdir(dir, (err: any, files: string[]) => {
if (err) {
return doneCb();
}
var j: number, file: string;
for (j = 0; j < files.length; j++) {
file = files[j];
if (file.substring(file.length - 3, file.length) === '.js') {
processFiles.push(path.join(dir, file));
}
}
nextDir();
});
}
}, i: number = 0, processFiles: string[] = [];
nextDir();
}
/**
* [Private] Same as reset_system_properties, but called by the constructor.
*/
private _initSystemProperties(bootstrapClasspath: string[], javaClassPath: string[], javaHomePath: string, tmpDir: string, opts: {[name: string]: string}): void {
this.systemProperties = merge({
'java.class.path': javaClassPath.join(':'),
'java.home': javaHomePath,
'java.ext.dirs': path.join(javaHomePath, 'lib', 'ext'),
'java.io.tmpdir': tmpDir,
'sun.boot.class.path': bootstrapClasspath.join(':'),
'file.encoding': 'UTF-8',
'java.vendor': 'Doppio',
'java.version': '1.8',
'java.vendor.url': 'https://github.com/plasma-umass/doppio',
'java.class.version': '52.0',
'java.specification.version': '1.8',
'line.separator': '\n',
'file.separator': path.sep,
'path.separator': ':',
'user.dir': path.resolve('.'),
'user.home': '.',
'user.name': 'DoppioUser',
'os.name': 'doppio',
'os.arch': 'js',
'os.version': '0',
'java.vm.name': 'DoppioJVM 32-bit VM',
'java.vm.version': pkg.version,
'java.vm.vendor': 'PLASMA@UMass',
'java.awt.headless': (are_in_browser()).toString(), // true if we're using the console frontend
'java.awt.graphicsenv': 'classes.awt.CanvasGraphicsEnvironment',
'jline.terminal': 'jline.UnsupportedTerminal', // we can't shell out to `stty`,
'sun.arch.data.model': '32', // Identify as 32-bit, because that's how we act.
'sun.jnu.encoding': "UTF-8" // Determines how Java parses command line options.
}, opts);
}
/**
* Retrieves the bootstrap class loader.
*/
public getBootstrapClassLoader(): BootstrapClassLoader {
return this.bsCl;
}
public getStartupTime(): Date {
return this.startupTime;
}
/**
* Returns `true` if system assertions are enabled, false otherwise.
*/
public areSystemAssertionsEnabled(): boolean {
return this.enableSystemAssertions;
}
/**
* Get a listing of classes with assertions enabled. Can also return 'true' or 'false.
*/
public getEnabledAssertions(): string[] | boolean {
return this.enabledAssertions;
}
/**
* Get a listing of classes with assertions disabled.
*/
public getDisabledAssertions(): string[] {
return this.disabledAssertions;
}
public setPrintJITCompilation(enabledOrNot: boolean) {
this.printJITCompilation = enabledOrNot;
}
public shouldPrintJITCompilation(): boolean {
return this.printJITCompilation;
}
/**
* Specifies a directory to dump compiled code to.
*/
public dumpCompiledCode(dir: string): void {
this.dumpCompiledCodeDir = dir;
}
public shouldDumpCompiledCode(): boolean {
return this.dumpCompiledCodeDir !== null;
}
public dumpObjectDefinition(cls: ClassData, evalText: string): void {
if (this.shouldDumpCompiledCode()) {
fs.writeFile(path.resolve(this.dumpCompiledCodeDir, cls.getExternalName() + ".js"), evalText, () => {});
}
}
public dumpBridgeMethod(methodSig: string, evalText: string): void {
if (this.shouldDumpCompiledCode()) {
fs.appendFile(path.resolve(this.dumpCompiledCodeDir, "vmtarget_bridge_methods.dump"), `${methodSig}:\n${evalText}\n\n`, () => {});
}
}
public dumpCompiledMethod(methodSig: string, pc: number, code: string): void {
if (this.shouldDumpCompiledCode()) {
fs.appendFile(path.resolve(this.dumpCompiledCodeDir, 'JIT_compiled_methods.dump'), `${methodSig}:${pc}:\n${code}\n\n`, () => {});
}
}
/**
* Asynchronously dumps JVM state to a file. Currently limited to thread
* state.
*/
public dumpState(filename: string, cb: (er: any) => void): void {
fs.appendFile(filename, this.threadPool.getThreads().map((t: JVMThread) => `Thread ${t.getRef()}:\n` + t.getPrintableStackTrace()).join("\n\n"), cb);
}
}
export default JVM; | the_stack |
import {
assertFails,
assertSucceeds,
firestore,
} from '@firebase/rules-unit-testing'
import { renderHook } from '@testing-library/react-hooks'
import { expectType } from 'tsd'
import { FTypes, STypes, TypedFirestore } from '../../core'
import { useTypedDocument, useTypedQuery } from '../../hooks'
import { _web } from '../../lib/firestore-types'
import { postAData, userData } from '../_fixtures/data'
import {
firestoreSchema,
IPostA,
IPostB,
IUser,
IUserLocal,
PostSchema,
UserSchema,
} from '../_fixtures/firestore-schema'
import { authedApp } from '../_infrastructure/_app'
import { expectAnyTimestamp, expectEqualRef } from '../_utils/firestore'
const _tcollections = (app: _web.Firestore) => {
const typedFirestore = new TypedFirestore(firestoreSchema, firestore, app)
void (() => {
typedFirestore.collection(
// @ts-expect-error: wrong collection name
'users',
)
})
const versions = typedFirestore.collection('versions')
const v1 = versions.doc('v1')
void (() => {
v1.collection(
// @ts-expect-error: wrong collection name
'posts',
)
})
const users = v1.collection('users')
const teenUsers = v1.collectionQuery('users', (q) => q.teen())
const usersOrderedById = v1.collectionQuery('users', (q) => q.orderById())
const user = users.doc('user')
const posts = user.collection('posts')
const post = posts.doc('post')
const usersGroup = typedFirestore.collectionGroup('users', 'versions.users')
const teenUsersGroup = typedFirestore.collectionGroupQuery(
'users',
'versions.users',
(q) => q.teen(),
)
return {
typedFirestore,
versions,
v1,
users,
user,
teenUsers,
usersOrderedById,
posts,
post,
usersGroup,
teenUsersGroup,
}
}
const app = authedApp('user').firestore()
const appUnauthed = authedApp('unauthed').firestore()
const r = _tcollections(app)
const ur = _tcollections(appUnauthed)
type UserU = IUserLocal &
STypes.DocumentMeta<_web.Firestore> &
STypes.HasLoc<'versions.users'> &
STypes.HasT<IUser> &
STypes.HasId
type PostU = (IPostA | IPostB) &
STypes.DocumentMeta<_web.Firestore> &
STypes.HasLoc<'versions.users.posts'> &
STypes.HasT<IPostA | IPostB> &
STypes.HasId
describe('types', () => {
test('decoder', () => {
expectType<
(data: IUser, snap: FTypes.QueryDocumentSnap<IUser>) => IUserLocal
>(UserSchema.decoder)
expectType<undefined>(PostSchema.decoder)
})
test('UAt', () => {
expectType<UserU>(
{} as STypes.DocDataAt<
typeof firestoreSchema,
_web.Firestore,
'versions.users'
>,
)
expectType<PostU>(
// @ts-expect-error: wrong U type
{} as STypes.DocDataAt<
typeof firestoreSchema,
_web.Firestore,
'versions.users'
>,
)
})
})
describe('refs', () => {
test('ref equality', () => {
expectEqualRef(r.users.raw, app.collection('versions/v1/users'), false)
expectEqualRef(r.user.raw, app.doc('versions/v1/users/user'), false)
expectEqualRef(r.users.raw, r.v1.collection('users').raw)
expectEqualRef(r.user.raw, r.v1.collection('users').doc('user').raw)
})
test('query equality', () => {
expectEqualRef(
r.users.raw.where('age', '>=', 10).where('age', '<', 20),
r.teenUsers.raw,
)
expectEqualRef(
r.usersGroup.raw.where('age', '>=', 10).where('age', '<', 20),
r.teenUsersGroup.raw,
)
expectEqualRef(
r.users.raw.orderBy(firestore.FieldPath.documentId()),
r.usersOrderedById.raw,
)
})
test('doc() argument', () => {
const a = r.users.doc()
const b = r.users.doc(undefined)
expect(a.id).toHaveLength(20)
expect(b.id).toHaveLength(20)
})
})
describe('class structure', () => {
test('parent of root collection is undefined', () => {
const parentOfRootCollection: undefined = r.versions.parentDocument()
expect(parentOfRootCollection).toBeUndefined()
})
test.each([
{
p: 'versions',
l: 'versions',
instances: [r.versions, r.v1.parentCollection()],
},
{
p: 'versions/v1',
l: 'versions',
instances: [
r.v1,
r.users.parentDocument(),
r.typedFirestore.wrapDocument(r.v1.raw),
],
},
{
p: 'versions/v1/users',
l: 'versions.users',
instances: [r.users, r.user.parentCollection()],
},
{
p: 'versions/v1/users/user',
l: 'versions.users',
instances: [
r.user,
r.posts.parentDocument(),
r.typedFirestore.wrapDocument(r.user.raw),
],
},
{
p: 'versions/v1/users/user/posts',
l: 'versions.users.posts',
instances: [r.posts, r.post.parentCollection()],
},
{
p: 'versions/v1/users/user/posts/post',
l: 'versions.users.posts',
instances: [
r.post,
r.typedFirestore.wrapDocument(r.post.raw),
r.typedFirestore.wrapDocument<typeof r.user.raw>(
// @ts-expect-error: wrong doc type
r.post.raw,
),
],
},
])('path, loc (C, D): %p', ({ p, l, instances }) => {
const firstInstance = instances[0]!
for (const instance of instances) {
expect(instance.path).toBe(p)
expect(instance.loc).toEqual(l)
expectEqualRef(instance.raw, firstInstance.raw)
}
})
test.each([
{
l: 'versions.users',
instances: [r.teenUsers],
},
{
l: 'versions.users',
instances: [r.usersGroup],
},
{
l: 'versions.users',
instances: [r.teenUsersGroup],
},
])('loc (Q): %p', ({ l, instances }) => {
for (const instance of instances) {
expect(instance.loc).toEqual(l)
}
})
})
const usersRaw = app.collection('versions').doc('v1').collection('users')
const createInitialUserAndPost = async () => {
await usersRaw.doc('user').set(userData as any)
await usersRaw
.doc('user')
.collection('posts')
.doc('post')
.set(postAData as any)
}
describe('read', () => {
beforeEach(createInitialUserAndPost)
test.each([
{ get: () => r.typedFirestore.runTransaction((tt) => tt.get(r.user)) },
r.user,
r.posts.parentDocument(),
r.typedFirestore.wrapDocument(r.user.raw),
])('get doc - user %#', async (ref) => {
const snap: _web.DocumentSnapshot<UserU> = await ref.get()
// @ts-expect-error: wrong data type
const snapError: _web.DocumentSnapshot<PostU> = await ref.get()
const data = snap.data()!
expectType<UserU>(data)
// @ts-expect-error: wrong data type
expectType<PostU>(data)
expect(data).toMatchObject({
...userData,
timestamp: expect.any(String),
id: snap.id,
})
})
test.each([
{ get: () => r.typedFirestore.runTransaction((tt) => tt.get(r.post)) },
r.post,
r.typedFirestore.wrapDocument(r.post.raw),
])('get doc - post %#', async (ref) => {
const snap: _web.DocumentSnapshot<PostU> = await ref.get()
// @ts-expect-error: wrong data type
const snapError: _web.DocumentSnapshot<UserU> = await ref.get()
const data = snap.data()!
expectType<PostU>(data)
// @ts-expect-error: wrong data type
expectType<UserU>(data)
expect(data).toMatchObject({
...postAData,
id: snap.id,
})
})
test.each([r.users, r.user.parentCollection()])(
'get collection - users %#',
async (ref) => {
const snap: _web.QuerySnapshot<UserU> = await ref.get()
// @ts-expect-error: wrong data type
const snapError: _web.QuerySnapshot<PostU> = await ref.get()
expect(snap.docs).toHaveLength(1)
const data = snap.docs[0]!.data()
expectType<UserU>(data)
// @ts-expect-error: wrong data type
expectType<PostU>(data)
expect(data).toMatchObject({
...userData,
timestamp: expect.any(String),
id: snap.docs[0].id,
})
},
)
test.each([r.teenUsers, r.teenUsersGroup])(
'get query - users %#',
async (query) => {
const snap: _web.QuerySnapshot<UserU> = await query.get()
// @ts-expect-error: wrong data type
const snapError: _web.QuerySnapshot<PostU> = await query.get()
expect(snap.docs).toHaveLength(1)
const data = snap.docs[0]!.data()
expectType<UserU>(data)
// @ts-expect-error: wrong data type
expectType<PostU>(data)
expect(data).toMatchObject({
...userData,
timestamp: expect.any(String),
id: snap.docs[0].id,
})
},
)
test.each([
{
get: async () => {
const usersSnap = await r.users.get()
const userRef = r.typedFirestore.wrapDocument(usersSnap.docs[0]!.ref)
return userRef.collection('posts').get()
},
},
r.posts,
r.post.parentCollection(),
])('get collection - posts %#', async (ref) => {
const snap: _web.QuerySnapshot<PostU> = await ref.get()
// @ts-expect-error: wrong data type
const snapError: _web.QuerySnapshot<UserU> = await ref.get()
expect(snap.docs).toHaveLength(1)
const data = snap.docs[0]!.data()
expectType<PostU>(data)
// @ts-expect-error: wrong data type
expectType<UserU>(data)
expect(data).toMatchObject({
...postAData,
id: snap.docs[0].id,
})
})
})
describe('write', () => {
test.each([
async () => {
await r.user.create(userData)
// @ts-expect-error: wrong data type
void (() => r.user.create(postData))
},
async () => {
const b = r.typedFirestore.batch()
b.create(r.user, userData)
// @ts-expect-error: wrong data type
void (() => b.create(r.user, postAData))
await b.commit()
},
async () => {
await r.typedFirestore.runTransaction(async (tt) => {
tt.create(r.user, userData)
// @ts-expect-error: wrong data type
void (() => tt.create(r.user, postAData))
})
},
])('create user %#', async (fn) => {
await fn()
const snapRaw = await usersRaw.doc('user').get()
expect(snapRaw.data()).toMatchObject({
...userData,
_createdAt: expectAnyTimestamp(),
_updatedAt: expectAnyTimestamp(),
timestamp: expectAnyTimestamp(),
})
})
test('create user (empty array)', async () => {
await assertSucceeds(r.user.create({ ...userData, tags: [] }))
})
test('create user (fails due to invalid timestamp)', async () => {
await assertSucceeds(
r.user.raw.set({
...userData,
_createdAt: firestore.FieldValue.serverTimestamp(),
_updatedAt: firestore.FieldValue.serverTimestamp(),
} as any),
)
await assertSucceeds(
r.user.raw.set({
...userData,
_createdAt: firestore.FieldValue.serverTimestamp(),
} as any),
)
await assertFails(
r.user.raw.set({
...userData,
_createdAt: firestore.FieldValue.serverTimestamp(),
_updatedAt: firestore.Timestamp.fromDate(new Date()),
} as any),
)
})
test('create user (fails due to wrong type)', async () => {
await assertFails(
r.user.create({
...userData,
// @ts-expect-error: tags.id
tags: [{ id: '0', name: 'tag0' }],
}),
)
await assertFails(
r.user.create({
...userData,
// @ts-expect-error: options.a
options: { a: 1, b: 'value' },
}),
)
})
test('create user (fails due to unauthed)', async () => {
await assertFails(ur.user.create(userData))
})
describe('write to non-existing doc', () => {
test('setMerge succeeds', async () => {
await expect(r.user.setMerge(userData)).resolves.toBeUndefined()
})
test('update fails', async () => {
await expect(r.user.update(userData)).rejects.toThrowError()
})
})
})
describe('write (with existing doc)', () => {
beforeEach(createInitialUserAndPost)
const userUpdateData = {
name: 'name1-updated',
tags: firestore.FieldValue.arrayUnion({ id: 2, name: 'tag2' }),
}
for (const op of ['setMerge', 'update'] as const) {
test.each([
async () => {
await r.user[op](userUpdateData)
// @ts-expect-error: wrong data type
void (() => r.user[op](postAData))
},
async () => {
const b = r.typedFirestore.batch()
b[op](r.user, userUpdateData)
// @ts-expect-error: wrong data type
void (() => b[op](r.user, postAData))
await b.commit()
},
async () => {
await r.typedFirestore.runTransaction(async (tt) => {
tt[op](r.user, userUpdateData)
// @ts-expect-error: wrong data type
void (() => tt[op](r.user, postAData))
})
},
])(`${op} user %#`, async (fn) => {
await fn()
const snapRaw = await usersRaw.doc('user').get()
expect(snapRaw.data()).toMatchObject({
...userData,
name: 'name1-updated',
tags: [...userData.tags, { id: 2, name: 'tag2' }],
_updatedAt: expectAnyTimestamp(),
timestamp: expectAnyTimestamp(),
})
})
test.each([
async () => {
await r.typedFirestore.runTransaction(async (tt) => {
const tsnap = await tt.get(r.user)
tt[op](r.user, {
age: tsnap.data()!.age + 1,
})
})
},
])(`${op} user (transaction using .get()) %#`, async (fn) => {
await fn()
const snapRaw = await usersRaw.doc('user').get()
expect(snapRaw.data()).toMatchObject({
...userData,
age: userData.age + 1,
_updatedAt: expectAnyTimestamp(),
timestamp: expectAnyTimestamp(),
})
})
}
test.each([
async () => {
await r.user.delete()
},
async () => {
const b = r.typedFirestore.batch()
b.delete(r.user)
await b.commit()
},
async () => {
await r.typedFirestore.runTransaction(async (tt) => {
tt.delete(r.user)
})
},
])('delete user %#', async (fn) => {
await fn()
const snapRaw = await usersRaw.doc('user').get()
expect(snapRaw.exists).toBeFalsy()
})
})
describe('hooks', () => {
beforeEach(createInitialUserAndPost)
const initialResult = {
error: undefined,
loading: true,
data: undefined,
snap: undefined,
}
test('useTypedDocument', async () => {
const { result, waitForNextUpdate, unmount } = renderHook(() =>
useTypedDocument(r.user),
)
expect(result.current).toEqual(initialResult)
await waitForNextUpdate()
expect(result.current).toMatchObject({
error: undefined,
loading: false,
data: { ...userData, timestamp: expect.any(String) },
})
expectEqualRef(result.current.snap!.ref, r.user.raw)
expectType<UserU>(result.current.data!)
// @ts-expect-error: wrong data type
expectType<PostU>(result.current.data!)
unmount()
})
test('useTypedDocument with transformer', async () => {
const { result, waitForNextUpdate, unmount } = renderHook(() =>
useTypedDocument(r.user, (data) => data.name),
)
expect(result.current).toEqual(initialResult)
await waitForNextUpdate()
expect(result.current).toMatchObject({
error: undefined,
loading: false,
data: userData.name,
})
expectEqualRef(result.current.snap!.ref, r.user.raw)
expectType<string>(result.current.data!)
// @ts-expect-error: wrong data type
expectType<number>(result.current.data!)
unmount()
})
test('useTypedQuery', async () => {
const { result, waitForNextUpdate, unmount } = renderHook(() =>
useTypedQuery(r.users),
)
expect(result.current).toEqual(initialResult)
await waitForNextUpdate()
expect(result.current).toMatchObject({
error: undefined,
loading: false,
data: [{ ...userData, timestamp: expect.any(String) }],
})
expectEqualRef(result.current.snap!.docs[0]!.ref, r.user.raw)
expectType<UserU>(result.current.data![0]!)
// @ts-expect-error: wrong data type
expectType<PostU>(result.current.data![0]!)
unmount()
})
test('useTypedQuery with transformer', async () => {
const { result, waitForNextUpdate, unmount } = renderHook(() =>
useTypedQuery(r.users, (data) => data.name),
)
expect(result.current).toEqual(initialResult)
await waitForNextUpdate()
expect(result.current).toMatchObject({
error: undefined,
loading: false,
data: [userData.name],
})
expectEqualRef(result.current.snap!.docs[0]!.ref, r.user.raw)
expectType<string>(result.current.data![0]!)
// @ts-expect-error: wrong data type
expectType<number>(result.current.data![0]!)
unmount()
})
}) | the_stack |
import type {Fiber} from 'react-reconciler';
import type {ReactWrapper} from 'enzyme';
import React, {createRef} from 'react';
import {mount} from 'enzyme';
import {getChildrenIds, getFibersIndices, getFibersKeys} from '../__shared__';
import {addChild, getFiberFromElementInstance} from '../../src';
import {invariant, Invariant} from '../../src/invariant';
import {warning} from '../../src/warning';
// Refs.
const parentRef = createRef<HTMLDivElement>();
const childRef = createRef<HTMLDivElement>();
// Wrappers.
let parentWrapper: ReactWrapper;
let childWrapper: ReactWrapper;
// Fibers.
let parent: Fiber;
let child: Fiber;
beforeEach(() => {
// Mount the components.
parentWrapper = mount(
<div ref={parentRef}>
<div key="1" id="1" />
<div key="2" id="2" />
</div>
);
childWrapper = mount(
<div>
<div key="3" id="3" ref={childRef} />
</div>
);
// (type fixing).
invariant(parentRef.current !== null && childRef.current !== null);
parent = getFiberFromElementInstance(parentRef.current);
child = getFiberFromElementInstance(childRef.current);
// Clear the mock.
(warning as jest.Mock).mockClear();
});
describe('How addChild( ) works', () => {
test('Add a child at the beginning', () => {
const position = addChild(parent, child, 0);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['3', '1', '2']);
});
test('Add a child at the bottom', () => {
const position = addChild(parent, child, -1);
// The position is correct.
expect(position).toBe(2);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['1', '2', '3']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '2', '3']);
});
test('Add a child in the position of the child with the key "1"', () => {
const position = addChild(parent, child, '1');
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['3', '1', '2']);
});
test('Add a child in the position of the child with the key "2"', () => {
const position = addChild(parent, child, '2');
// The position is correct.
expect(position).toBe(1);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['1', '3', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '3', '2']);
});
test('(Provide a not valid position index) Add a child at the bottom', () => {
const position = addChild(parent, child, 5);
// The position is correct.
expect(position).toBe(2);
// Warning calls.
expect(warning).toHaveBeenCalledTimes(1);
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['1', '2', '3']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '2', '3']);
});
test('(Provide a not valid position key) Add a child at the bottom', () => {
const position = addChild(parent, child, '5');
// The position is correct.
expect(position).toBe(2);
// Warning calls.
expect(warning).toHaveBeenCalledTimes(1);
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['1', '2', '3']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '2', '3']);
});
test('(With only parent alternate) Add a child at the beginning', () => {
// Generate the parent alternate.
parentWrapper.setProps({});
invariant(parent.alternate !== null);
const position = addChild(parent.alternate, child, 0);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent.alternate)).toEqual([0, 1, 2]);
expect(getFibersIndices(parent)).toEqual([0, 1]);
// The keys are in the correct order.
expect(getFibersKeys(parent.alternate)).toEqual(['3', '1', '2']);
expect(getFibersKeys(parent)).toEqual(['1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['3', '1', '2']);
});
test('(With only child alternate) Add a child at the beginning', () => {
// Generate the child alternate.
childWrapper.setProps({});
invariant(child.alternate !== null);
const position = addChild(parent, child, 0);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['3', '1', '2']);
// The alternate is not removed.
expect(child.alternate).not.toBe(null);
// The alternate references are removed.
expect(child.alternate.return).toBe(null);
expect(child.alternate.sibling).toBe(null);
});
test('(With parent and child alternates) Add a child at the beginning', () => {
// Generate the child and parent alternates.
parentWrapper.setProps({});
childWrapper.setProps({});
invariant(parent.alternate !== null);
invariant(child.alternate !== null);
const position = addChild(parent.alternate, child, 0);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent.alternate)).toEqual([0, 1, 2]);
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent.alternate)).toEqual(['3', '1', '2']);
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['3', '1', '2']);
});
test('(With parent and child alternates) Add a child in the position of the child with the key "2"', () => {
// Generate the child and parent alternates.
parentWrapper.setProps({});
childWrapper.setProps({});
invariant(parent.alternate !== null);
invariant(child.alternate !== null);
const position = addChild(parent.alternate, child, '2');
// The position is correct.
expect(position).toBe(1);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent.alternate)).toEqual([0, 1, 2]);
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent.alternate)).toEqual(['1', '3', '2']);
expect(getFibersKeys(parent)).toEqual(['1', '3', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '3', '2']);
});
test('(Enable skipUpdate option) Add a child but not update the DOM', () => {
const position = addChild(parent, child, 0, true);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).not.toHaveBeenCalled();
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '2']);
});
test('(The child element is not found) Add a child but not update the DOM', () => {
child.stateNode = null;
const position = addChild(parent, child, 0);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).toHaveBeenCalledTimes(1);
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '2']);
});
test('(The child element before is not found) Add a child but not update the DOM', () => {
// (type fixing).
invariant(parent.child !== null);
parent.child.stateNode = null;
const position = addChild(parent, child, 0);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).toHaveBeenCalledTimes(1);
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '2']);
});
test('(The container element is not found) Add a child but not update the DOM', () => {
parent.stateNode = null;
const position = addChild(parent, child, 0);
// The position is correct.
expect(position).toBe(0);
// Warning calls.
expect(warning).toHaveBeenCalledTimes(1);
// The indices are updated.
expect(getFibersIndices(parent)).toEqual([0, 1, 2]);
// The keys are in the correct order.
expect(getFibersKeys(parent)).toEqual(['3', '1', '2']);
// The children are in the correct order.
expect(getChildrenIds(parentWrapper.getDOMNode())).toEqual(['1', '2']);
});
test('(Provide an index less than -1) Throw an Invariant', () => {
expect(() => {
addChild(parent, child, -2);
}).toThrow(Invariant);
});
}); | the_stack |
import * as fs from 'fs';
import { Answers, prompt } from 'inquirer';
import * as _ from 'lodash';
import * as path from 'path';
import { clean, gte, minVersion, satisfies, validRange } from 'semver';
import { Args } from '../../Constants';
import { debug, green, l, nl, red } from '../../Helper/Logging';
import { SentryCli, SentryCliProps } from '../../Helper/SentryCli';
import { BaseIntegration } from './BaseIntegration';
const MIN_NEXTJS_VERSION = '10.0.8'; // Must be a fixed version: `X.Y.Z`
const PROPERTIES_FILENAME = 'sentry.properties';
const SENTRYCLIRC_FILENAME = '.sentryclirc';
const GITIGNORE_FILENAME = '.gitignore';
const CONFIG_DIR = 'configs/';
const MERGEABLE_CONFIG_INFIX = 'wizardcopy';
// for those files which can go in more than one place, the list of places they
// could go (the first one which works will be used)
const TEMPLATE_DESTINATIONS: { [key: string]: string[] } = {
'_error.js': ['pages', 'src/pages'],
'next.config.js': ['.'],
'sentry.server.config.js': ['.'],
'sentry.client.config.js': ['.'],
};
let appPackage: any = {};
try {
appPackage = require(path.join(process.cwd(), 'package.json'));
} catch {
// We don't need to have this
}
export class NextJs extends BaseIntegration {
protected _sentryCli: SentryCli;
constructor(protected _argv: Args) {
super(_argv);
this._sentryCli = new SentryCli(this._argv);
}
public async emit(answers: Answers): Promise<Answers> {
const dsn = _.get(answers, ['config', 'dsn', 'public'], null);
nl();
const sentryCliProps = this._sentryCli.convertAnswersToProperties(answers);
await this._createSentryCliConfig(sentryCliProps);
const configDirectory = path.join(
__dirname,
'..',
'..',
'..',
'NextJs',
CONFIG_DIR,
);
if (fs.existsSync(configDirectory)) {
this._createNextConfig(configDirectory, dsn);
} else {
debug(
`Couldn't find ${configDirectory}, probably because you ran this from inside of \`/lib\` rather than \`/dist\``,
);
nl();
}
l(
'For more information, see https://docs.sentry.io/platforms/javascript/guides/nextjs/',
);
nl();
return {};
}
public async shouldConfigure(_answers: Answers): Promise<Answers> {
if (this._shouldConfigure) {
return this._shouldConfigure;
}
nl();
let userAnswers: Answers = { continue: true };
if (!this._checkDep('next', true) && !this._argv.quiet) {
userAnswers = await prompt({
message:
'There were errors during your project checkup, do you still want to continue?',
name: 'continue',
default: false,
type: 'confirm',
});
}
nl();
if (!userAnswers['continue']) {
throw new Error('Please install the required dependencies to continue.');
}
this._shouldConfigure = Promise.resolve({ nextjs: true });
// eslint-disable-next-line @typescript-eslint/unbound-method
return this.shouldConfigure;
}
private async _createSentryCliConfig(
cliProps: SentryCliProps,
): Promise<void> {
const { 'auth/token': authToken, ...cliPropsToWrite } = cliProps;
/**
* To not commit the auth token to the VCS, instead of adding it to the
* properties file (like the rest of props), it's added to the Sentry CLI
* config, which is added to the gitignore. This way makes the properties
* file safe to commit without exposing any auth tokens.
*/
if (authToken) {
try {
await fs.promises.appendFile(
SENTRYCLIRC_FILENAME,
this._sentryCli.dumpConfig({ auth: { token: authToken } }),
);
green(`✓ Successfully added the auth token to ${SENTRYCLIRC_FILENAME}`);
} catch {
red(
`⚠ Could not add the auth token to ${SENTRYCLIRC_FILENAME}, ` +
`please add it to identify your user account:\n${authToken}`,
);
nl();
}
} else {
red(
`⚠ Did not find an auth token, please add your token to ${SENTRYCLIRC_FILENAME}`,
);
l(
'To generate an auth token, visit https://sentry.io/settings/account/api/auth-tokens/',
);
l(
'To learn how to configure Sentry CLI, visit ' +
'https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#configure-sentry-cli',
);
}
await this._addToGitignore(
SENTRYCLIRC_FILENAME,
`⚠ Could not add ${SENTRYCLIRC_FILENAME} to ${GITIGNORE_FILENAME}, ` +
'please add it to not commit your auth key.',
);
try {
await fs.promises.writeFile(
`./${PROPERTIES_FILENAME}`,
this._sentryCli.dumpProperties(cliPropsToWrite),
);
green(`✓ Successfully created sentry.properties`);
} catch {
red(`⚠ Could not add org and project data to ${PROPERTIES_FILENAME}`);
l(
'See docs for a manual setup: https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#configure-sentry-cli',
);
}
nl();
}
private async _addToGitignore(
filepath: string,
errorMsg: string,
): Promise<void> {
/**
* Don't check whether the given file is ignored because:
* 1. It's tricky to check it without git.
* 2. Git might not be installed or accessible.
* 3. It's convenient to use a module to interact with git, but it would
* increase the size x2 approximately. Docs say to run the Wizard without
* installing it, and duplicating the size would slow the set-up down.
* 4. The Wizard is meant to be run once.
* 5. A message is logged informing users it's been added to the gitignore.
* 6. It will be added to the gitignore as many times as it runs - not a big
* deal.
* 7. It's straightforward to remove it from the gitignore.
*/
try {
await fs.promises.appendFile(
GITIGNORE_FILENAME,
`\n# Sentry\n${filepath}\n`,
);
green(`✓ ${filepath} added to ${GITIGNORE_FILENAME}`);
} catch {
red(errorMsg);
}
}
private _createNextConfig(configDirectory: string, dsn: any): void {
const templates = fs.readdirSync(configDirectory);
for (const template of templates) {
this._setTemplate(
configDirectory,
template,
TEMPLATE_DESTINATIONS[template],
dsn,
);
}
red(
'⚠ Performance monitoring is enabled capturing 100% of transactions.\n' +
' Learn more in https://docs.sentry.io/product/performance/',
);
nl();
}
private _setTemplate(
configDirectory: string,
templateFile: string,
destinationOptions: string[],
dsn: string,
): void {
const templatePath = path.join(configDirectory, templateFile);
for (const destinationDir of destinationOptions) {
if (!fs.existsSync(destinationDir)) {
continue;
}
const destinationPath = path.join(destinationDir, templateFile);
// in case the file in question already exists, we'll make a copy with
// `MERGEABLE_CONFIG_INFIX` inserted just before the extension, so as not
// to overwrite the existing file
const mergeableFilePath = path.join(
destinationDir,
this._spliceInPlace(
templateFile.split('.'),
-1,
0,
MERGEABLE_CONFIG_INFIX,
).join('.'),
);
if (!fs.existsSync(destinationPath)) {
this._fillAndCopyTemplate(templatePath, destinationPath, dsn);
} else if (!fs.existsSync(mergeableFilePath)) {
this._fillAndCopyTemplate(templatePath, mergeableFilePath, dsn);
red(
`File \`${templateFile}\` already exists, so created \`${mergeableFilePath}\`.\n` +
'Please merge those files.',
);
nl();
} else {
red(
`Both \`${templateFile}\` and \`${mergeableFilePath}\` already exist.\n` +
'Please merge those files.',
);
nl();
}
return;
}
red(
`Could not find appropriate destination for \`${templateFile}\`. Tried: ${destinationOptions}.`,
);
nl();
}
private _fillAndCopyTemplate(
sourcePath: string,
targetPath: string,
dsn: string,
): void {
const templateContent = fs.readFileSync(sourcePath).toString();
const filledTemplate = templateContent.replace('___DSN___', dsn);
fs.writeFileSync(targetPath, filledTemplate);
}
private _checkDep(packageName: string, minVersion?: boolean): boolean {
const depVersion = _.get(
appPackage,
['dependencies', packageName],
'0.0.0',
);
const devDepVersion = _.get(
appPackage,
['devDependencies', packageName],
'0.0.0',
);
if (
!_.get(appPackage, `dependencies.${packageName}`, false) &&
!_.get(appPackage, `devDependencies.${packageName}`, false)
) {
red(`✗ ${packageName} isn't in your dependencies`);
red(` please install it with yarn/npm`);
return false;
} else if (
!this._fulfillsMinVersion(depVersion) &&
!this._fulfillsMinVersion(devDepVersion)
) {
red(
`✗ Your installed version of \`${packageName}\` is not supported, >=${MIN_NEXTJS_VERSION} needed.`,
);
return false;
} else {
if (minVersion) {
green(`✓ ${packageName} >= ${MIN_NEXTJS_VERSION} is installed`);
} else {
green(`✓ ${packageName} is installed`);
}
return true;
}
}
private _fulfillsMinVersion(version: string): boolean {
// The latest version, which at the moment is greater than the minimum
// version, shouldn't be a blocker in the wizard.
if (version === 'latest') {
return true;
}
const cleanedVersion = clean(version);
if (cleanedVersion) {
// gte(x, y) : true if x >= y
return gte(cleanedVersion, MIN_NEXTJS_VERSION);
}
const minVersionRange = `>=${MIN_NEXTJS_VERSION}`;
const userVersionRange = validRange(version);
const minUserVersion = minVersion(userVersionRange);
if (minUserVersion == null) {
// This should never happen
return false;
}
return satisfies(minUserVersion, minVersionRange);
}
private _spliceInPlace(
arr: Array<any>,
start: number,
deleteCount: number,
...inserts: any[]
): Array<any> {
arr.splice(start, deleteCount, ...inserts);
return arr;
}
} | the_stack |
'use strict';
import { GenericObject } from './../types/index';
import {
app,
protocol,
BrowserWindow,
Menu,
MenuItemConstructorOptions,
Tray,
shell,
dialog,
ipcMain,
} from 'electron';
import {
createProtocol,
installVueDevtools,
} from 'vue-cli-plugin-electron-builder/lib';
import * as Splashscreen from '@trodi/electron-splashscreen';
import { join } from 'path';
import { readFileSync } from 'fs';
import { get } from 'lodash-es';
import * as defaultTranslations from './i18n/en';
import { autoUpdater } from 'electron-updater';
import marked from 'marked';
const pkg = JSON.parse(
readFileSync(
join(
process.platform !== 'win32' ? '/' : '',
app.getAppPath(),
'package.json'
)
).toString()
);
const isDevelopment = process.env.NODE_ENV !== 'production';
const isMac = process.platform === 'darwin';
let menu: Menu | null = null;
declare const __static: any;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win: BrowserWindow;
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } },
]);
function loadWhatsNew() {
const news = readFileSync(`${__static}/WHATSNEW.md`).toString();
win.webContents.send('whatsnew-data', marked(news));
}
function createAppMenu(translations: any, disabledMap: GenericObject = {}) {
const menuRouter = (where: string) => {
// tslint:disable-next-line: variable-name
return (_menuItem: any, window: BrowserWindow) => {
window.webContents.send('navigate', where);
};
};
// tslint:disable-next-line: no-parameter-reassignment
translations = translations || defaultTranslations.default.en;
const template: MenuItemConstructorOptions[] = [
{
label: get(translations, ['appMenu', 'config'], 'Config'),
submenu: [
{
accelerator: 'CommandOrControl+Alt+S',
label: get(
translations,
['appMenu', 'settings'],
'Settings'
),
click: menuRouter('configure'),
},
{
accelerator: 'CommandOrControl+Alt+E',
label: get(translations, ['appMenu', 'export'], 'Export'),
click: () => {
const saveTo = dialog.showSaveDialogSync({
defaultPath: `etcd-manager-settings.json`,
properties: ['dontAddToRecent', 'createDirectory'],
} as any);
if (saveTo) {
win.webContents.send('app-config-data', saveTo);
}
},
},
{
accelerator: 'CommandOrControl+Alt+I',
label: get(translations, ['appMenu', 'import'], 'Import'),
click: () => {
const saveTo = dialog.showOpenDialogSync({
properties: ['openFile'],
filters: [{
extensions: ['json', 'JSON'],
name: 'foo',
}],
});
if (saveTo) {
try {
const data = JSON.parse(readFileSync(saveTo[0]).toString());
win.webContents.send('config-data', data);
} catch (e) {
win.webContents.send('error-notification', 'common.messages.invalidFileError');
}
}
},
},
],
},
{
label: get(translations, ['appMenu', 'edit'], 'Edit'),
// @ts-ignore
submenu: [
{
role: 'undo',
label: get(translations, ['appMenu', 'undo'], 'Undo'),
},
{
role: 'redo',
label: get(translations, ['appMenu', 'redo'], 'Redo'),
},
{ type: 'separator' },
{
role: 'cut',
label: get(translations, ['appMenu', 'cut'], 'Cut'),
},
{
role: 'copy',
label: get(translations, ['appMenu', 'copy'], 'Copy'),
},
{
role: 'paste',
label: get(translations, ['appMenu', 'paste'], 'Paste'),
},
...(isMac
? [
{
role: 'pasteAndMatchStyle',
label: get(
translations,
['appMenu', 'pasteAndMatchStyle'],
'Paste and match style'
),
},
]
: []),
{
role: 'delete',
label: get(translations, ['appMenu', 'delete'], 'Delete'),
},
{ type: 'separator' },
{
role: 'selectAll',
label: get(
translations,
['appMenu', 'selectAll'],
'Select all'
),
},
],
},
{
label: get(translations, ['appMenu', 'view'], 'View'),
// @ts-ignore
submenu: [
...(isDevelopment
? [
{
role: 'reload',
label: get(
translations,
['appMenu', 'reload'],
'Reload'
),
},
{
role: 'forcereload',
label: get(
translations,
['appMenu', 'forcereload'],
'Force reload'
),
},
]
: []),
{ type: 'separator' },
{
role: 'resetzoom',
label: get(
translations,
['appMenu', 'resetzoom'],
'Reset zoom'
),
},
{
role: 'zoomin',
label: get(translations, ['appMenu', 'zoomin'], 'Zoom in'),
},
{
role: 'zoomout',
label: get(
translations,
['appMenu', 'zoomout'],
'Zoom out'
),
},
{ type: 'separator' },
{
role: 'togglefullscreen',
label: get(
translations,
['appMenu', 'togglefullscreen'],
'Toggle fullscreen'
),
},
{ type: 'separator' },
...(isDevelopment
? [
{
role: 'toggledevtools',
label: get(
translations,
['appMenu', 'toggledevtools'],
'Toggle DevTools'
),
},
]
: []),
,
],
},
{
label: get(translations, ['appMenu', 'manage'], 'Manage'),
enabled: disabledMap.manage,
visible: process.platform === 'darwin' ? true : disabledMap.manage,
acceleratorWorksWhenHidden: false,
submenu: [
{
label: get(
translations,
['appMenu', 'settings'],
'Settings'
),
accelerator: 'CommandOrControl+Alt+S',
click: menuRouter('configure'),
},
{
label: get(translations, ['appMenu', 'cluster'], 'Cluster'),
accelerator: 'CommandOrControl+Alt+C',
click: menuRouter('cluster'),
},
{
label: get(translations, ['appMenu', 'keys'], 'Keys'),
accelerator: 'CommandOrControl+Alt+K',
click: menuRouter('keys'),
},
{
label: get(
translations,
['appMenu', 'watchers'],
'Watchers'
),
accelerator: 'CommandOrControl+Alt+W',
click: menuRouter('watchers'),
},
{
label: get(translations, ['appMenu', 'roles'], 'Roles'),
accelerator: 'CommandOrControl+Alt+R',
click: menuRouter('roles'),
},
{
label: get(translations, ['appMenu', 'users'], 'Users'),
accelerator: 'CommandOrControl+Alt+U',
click: menuRouter('users'),
},
{
label: get(translations, ['appMenu', 'leases'], 'Leases'),
enabled: disabledMap.lease,
visible: process.platform === 'darwin' ? true : disabledMap.lease,
accelerator: 'CommandOrControl+Alt+L',
click: menuRouter('leases'),
},
],
},
{
label: get(translations, ['appMenu', 'help'], 'Help'),
// @ts-ignore
submenu: [
{
label: get(
translations,
['appMenu', 'reportBug'],
'Report a bug'
),
accelerator: 'CommandOrControl+Alt+B',
click: () => {
shell.openExternal(pkg.bugs.url);
},
},
],
},
];
template.unshift(
// @ts-ignore
isMac
? {
label: app.getName(),
submenu: [
{
role: 'about',
label: get(
translations,
['appMenu', 'about'],
'About'
),
},
{ type: 'separator' },
{
role: 'services',
label: get(
translations,
['appMenu', 'services'],
'Services'
),
},
{ type: 'separator' },
{
role: 'hide',
label: get(translations, ['appMenu', 'hide'], 'Hide'),
},
{
role: 'hideothers',
label: get(
translations,
['appMenu', 'hideothers'],
'Hide others'
),
},
{
role: 'unhide',
label: get(
translations,
['appMenu', 'unhide'],
'Unhide'
),
},
{ type: 'separator' },
{
role: 'quit',
label: get(translations, ['appMenu', 'quit'], 'Quit'),
},
],
}
: {
label: get(translations, ['appMenu', 'file'], 'File'),
submenu: [
{
role: 'quit',
label: get(translations, ['appMenu', 'quit'], 'Quit'),
},
],
}
);
menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
// tslint:disable-next-line: variable-name
function setAboutPanel(_translations: any = defaultTranslations.default.en) {
const year = new Date().getFullYear();
if (process.platform !== 'win32') {
app.setAboutPanelOptions({
applicationName: 'ETCD Manager',
applicationVersion: app.getVersion(),
copyright: `Copyright ${year} by Contributors. All rights reserved.`,
credits: 'Contributors',
website: 'http://www.etcdmanager.io',
iconPath: join(__static, '/icons/64x64.png'),
});
}
}
function createWindow() {
// Create the browser window.
const mainOpts = {
width: 800,
height: 600,
title: 'ETCD Manager',
icon: join(__static, '/icons/64x64.png'),
webPreferences: {
nodeIntegration: true,
},
};
const config: Splashscreen.Config = {
windowOpts: mainOpts,
templateUrl: `${__static}/splash.html`,
minVisible: 2000,
splashScreenOpts: {
width: 800,
height: 600,
},
};
win = Splashscreen.initSplashScreen(config);
win.setTitle('ETCD Manager');
win.on('page-title-updated', (e) => {
e.preventDefault();
});
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string);
if (!process.env.IS_TEST) {
win.webContents.openDevTools();
}
} else {
createProtocol('app');
// Load the index.html when not in development
win.loadURL('app://./index.html');
autoUpdater.checkForUpdatesAndNotify();
}
win.maximize();
win.on('closed', () => {});
}
ipcMain.on('ssl_file_check', (_event: any, cert: string, id: string) => {
try {
const data = readFileSync(cert);
win.webContents.send('ssl_data', {
id,
data,
fileName: cert,
});
} catch (e) {
throw e;
}
});
ipcMain.on('ssl_dialog_open', (_event: any, id: string) => {
const saveTo = dialog.showOpenDialogSync({
properties: ['openFile'],
});
if (saveTo) {
try {
const data = readFileSync(saveTo[0]);
win.webContents.send('ssl_data', {
id,
data,
fileName: saveTo[0],
});
} catch (e) {
throw e;
}
}
});
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installVueDevtools();
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString());
}
}
createAppMenu(defaultTranslations.default.en);
setAboutPanel();
createWindow();
// tslint:disable-next-line: variable-name
ipcMain.on(
'update-menu',
(_event: any, translations: any, disabledMap: GenericObject) => {
createAppMenu(translations, disabledMap);
setAboutPanel(translations);
}
);
ipcMain.on('whatsnew-load', () => {
loadWhatsNew();
});
return new Tray(join(__static, '/icons/24x24.png'));
});
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', (data) => {
if (data === 'graceful-exit') {
app.quit();
}
});
} else {
process.on('SIGTERM', () => {
app.quit();
});
}
} | the_stack |
import {
WebDNNWebGLContext,
WebGLUniformItem,
} from "../../../../interface/backend/webgl/webglContext";
import { WebGLTensor } from "../../../../interface/backend/webgl/webglTensor";
import { OperatorEntry } from "../../../../interface/core/operator";
import { Tensor } from "../../../../interface/core/tensor";
import { Conv } from "../../../base/conv";
import {
shaderGenHeader,
shaderGenOutput,
shaderGenTensorNDGet,
shaderGenTensorNDGetUniformItem,
shaderGenTensorOutputCoordsWithReturn,
shaderGenTensorOutputUniform,
shaderGenTensorOutputUniformItem,
} from "../../shaderHelper";
export class WebGLConv extends Conv {
constructor() {
super("webgl");
}
async run(context: WebDNNWebGLContext, inputs: Tensor[]): Promise<Tensor[]> {
context.assertsWebGLTensorArray(inputs);
const inputX = inputs[0],
inputW = inputs[1],
inputB = inputs[2];
// TODO: 2D以外対応
if (inputX.ndim !== 4) {
throw new Error("Conv other than 2D is not yet supported");
}
const {
batch,
dilations,
group,
kernelShape,
pads,
strides,
inShape,
outShape,
chIn,
chInPerGroup,
chOut,
chOutPerGroup,
} = this.calcShape(inputX.dims, inputW.dims);
if (
inputX.dimPerPixel !== 1 ||
inputW.dimPerPixel !== 1 ||
(inputB && inputB.dimPerPixel !== 1)
) {
throw new Error();
}
const im2colData = context.emptyTensor([
group *
batch *
outShape[0] *
outShape[1] *
chInPerGroup *
kernelShape[0] *
kernelShape[1],
]);
await this.im2col(
context,
inputX,
im2colData,
batch,
dilations,
group,
kernelShape,
pads,
strides,
inShape,
outShape,
chIn,
chInPerGroup,
chOut,
chOutPerGroup
);
const matmulData = context.emptyTensor([
group * batch * outShape[0] * outShape[1] * chOutPerGroup,
]);
await this.matmul(
context,
im2colData,
inputW,
matmulData,
group,
batch * outShape[0] * outShape[1],
chInPerGroup * kernelShape[0] * kernelShape[1],
chOutPerGroup
);
im2colData.dispose();
const output = context.emptyTensor([
batch,
chOut,
outShape[0],
outShape[1],
]);
if (inputB) {
const transposeData = context.emptyTensor([
batch * chOut * outShape[0] * outShape[1],
]);
await this.transpose(
context,
matmulData,
transposeData,
group,
batch,
outShape[0] * outShape[1],
chOutPerGroup
);
matmulData.dispose();
await this.bias(
context,
transposeData,
inputB,
output,
batch,
chOut,
outShape[0] * outShape[1]
);
transposeData.dispose();
} else {
await this.transpose(
context,
matmulData,
output,
group,
batch,
outShape[0] * outShape[1],
chOutPerGroup
);
matmulData.dispose();
}
return [output];
}
private async im2col(
context: WebDNNWebGLContext,
dX: WebGLTensor,
dI: WebGLTensor,
batch: number,
dilations: number[],
group: number,
kernelShape: number[],
pads: number[],
strides: number[],
inShape: number[],
outShape: number[],
chIn: number,
chInPerGroup: number,
chOut: number,
chOutPerGroup: number
) {
const kernelName = `conv_im2col`;
if (!context.hasKernel(kernelName)) {
const kernelSource = `${shaderGenHeader(context.webgl2)}
${shaderGenTensorOutputUniform(1)}
uniform int GROUP;
uniform int BATCH;
uniform int O0;
uniform int O1;
uniform int CI;
uniform int CIPG;
uniform int K0;
uniform int K1;
uniform int S0;
uniform int S1;
uniform int P0;
uniform int P1;
uniform int D0;
uniform int D1;
uniform int IS0;
uniform int IS1;
${shaderGenTensorNDGet("tex_input", 1, context.webgl2)}
void main() {
${shaderGenTensorOutputCoordsWithReturn(1)}
int rem = tex_output_flat;
int quo = rem / K0;
int k1 = rem - quo * K1;
rem = quo;
quo = rem / K0;
int k0 = rem - quo * K0;
rem = quo;
quo = rem / CIPG;
int ci = rem - quo * CIPG;
rem = quo;
quo = rem / O1;
int o1 = rem - quo * O1;
rem = quo;
quo = rem / O0;
int o0 = rem - quo * O0;
rem = quo;
quo = rem / BATCH;
int b = rem - quo * BATCH;
int g = quo;
int in0 = o0 * S0 - P0 + k0 * D0;
int in1 = o1 * S1 - P1 + k1 * D1;
float s = 0.0;
if (in0 >= 0 && in0 < IS0 && in1 >= 0 && in1 < IS1) {
s = get_tex_input(((b * CI + g * CIPG + ci) * IS0 + in0) * IS1 + in1);
}
${shaderGenOutput("s", context.webgl2)}
return;
}
`;
context.addKernel(kernelName, kernelSource);
}
const uniforms: WebGLUniformItem[] = [
...shaderGenTensorNDGetUniformItem("tex_input", [1], dX, context.webgl2),
...shaderGenTensorOutputUniformItem([dI.length], dI, context.webgl2),
{ name: "GROUP", type: "int", value: group },
{ name: "BATCH", type: "int", value: batch },
{ name: "O0", type: "int", value: outShape[0] },
{ name: "O1", type: "int", value: outShape[1] },
{ name: "CI", type: "int", value: chIn },
{ name: "CIPG", type: "int", value: chInPerGroup },
{ name: "K0", type: "int", value: kernelShape[0] },
{ name: "K1", type: "int", value: kernelShape[1] },
{ name: "S0", type: "int", value: strides[0] },
{ name: "S1", type: "int", value: strides[1] },
{ name: "P0", type: "int", value: pads[0] },
{ name: "P1", type: "int", value: pads[1] },
{ name: "D0", type: "int", value: dilations[0] },
{ name: "D1", type: "int", value: dilations[1] },
{ name: "IS0", type: "int", value: inShape[0] },
{ name: "IS1", type: "int", value: inShape[1] },
];
await context.runKernel(
kernelName,
[{ tensor: dX, name: "tex_input" }],
dI,
uniforms
);
}
private async matmul(
context: WebDNNWebGLContext,
dI: WebGLTensor,
dW: WebGLTensor,
dT: WebGLTensor,
group: number,
bout: number,
cinkhkw: number,
chOutPerGroup: number
) {
/*
* DI(group, bout, cinkhkw) * dW(group, coutpergroup, cinkhkw) -> dT(group, bout, coutpergroup)
* ループ回数は定数が必要
*/
const kernelName = `conv_matmul_${cinkhkw}`;
if (!context.hasKernel(kernelName)) {
const kernelSource = `${shaderGenHeader(context.webgl2)}
${shaderGenTensorOutputUniform(1)}
#define cinkhkw ${cinkhkw}
uniform int GROUP;
uniform int BOUT;
uniform int COPG;
${shaderGenTensorNDGet("tex_input_w", 1, context.webgl2)}
${shaderGenTensorNDGet("tex_input_i", 1, context.webgl2)}
void main() {
${shaderGenTensorOutputCoordsWithReturn(1)}
int rem = tex_output_flat;
int quo = rem / COPG;
int x = rem - quo * COPG;
rem = quo;
quo = rem / BOUT;
int y = rem - quo * BOUT;
int g = quo;
float s = 0.0;
for (int ip = 0; ip < cinkhkw; ip++) {
s += get_tex_input_i((g * BOUT + y) * cinkhkw + ip) * get_tex_input_w((g * COPG + x) * cinkhkw + ip);
}
${shaderGenOutput("s", context.webgl2)}
return;
}
`;
context.addKernel(kernelName, kernelSource);
}
const uniforms: WebGLUniformItem[] = [
...shaderGenTensorNDGetUniformItem(
"tex_input_w",
[1],
dW,
context.webgl2
),
...shaderGenTensorNDGetUniformItem(
"tex_input_i",
[1],
dI,
context.webgl2
),
...shaderGenTensorOutputUniformItem([dT.length], dT, context.webgl2),
{ name: "GROUP", type: "int", value: group },
{ name: "BOUT", type: "int", value: bout },
{ name: "COPG", type: "int", value: chOutPerGroup },
];
await context.runKernel(
kernelName,
[
{ tensor: dW, name: "tex_input_w" },
{ tensor: dI, name: "tex_input_i" },
],
dT,
uniforms
);
}
private async transpose(
context: WebDNNWebGLContext,
dT: WebGLTensor,
dO: WebGLTensor,
group: number,
batch: number,
outarea: number,
chOutPerGroup: number
) {
// DT(group, batch, outh, outw, choutpergroup) -> dO(batch, group, choutpergroup, outh, outw)
const kernelName = `conv_transpose`;
if (!context.hasKernel(kernelName)) {
const kernelSource = `${shaderGenHeader(context.webgl2)}
${shaderGenTensorOutputUniform(1)}
uniform int GROUP;
uniform int BATCH;
uniform int COPG;
uniform int OUTAREA;
${shaderGenTensorNDGet("tex_input", 1, context.webgl2)}
void main() {
${shaderGenTensorOutputCoordsWithReturn(1)}
int rem = tex_output_flat;
int quo = rem / OUTAREA;
int x = rem - quo * OUTAREA;
rem = quo;
quo = rem / COPG;
int c = rem - quo * COPG;
rem = quo;
quo = rem / GROUP;
int g = rem - quo * GROUP;
int b = quo;
float s = 0.0;
s = get_tex_input(((g * BATCH + b) * OUTAREA + x) * COPG + c);
${shaderGenOutput("s", context.webgl2)}
return;
}
`;
context.addKernel(kernelName, kernelSource);
}
const uniforms: WebGLUniformItem[] = [
...shaderGenTensorNDGetUniformItem("tex_input", [1], dT, context.webgl2),
...shaderGenTensorOutputUniformItem([dO.length], dO, context.webgl2),
{ name: "GROUP", type: "int", value: group },
{ name: "BATCH", type: "int", value: batch },
{ name: "COPG", type: "int", value: chOutPerGroup },
{ name: "OUTAREA", type: "int", value: outarea },
];
await context.runKernel(
kernelName,
[{ tensor: dT, name: "tex_input" }],
dO,
uniforms
);
}
private async bias(
context: WebDNNWebGLContext,
dI: WebGLTensor,
dB: WebGLTensor,
dO: WebGLTensor,
batch: number,
chOut: number,
outarea: number
) {
const kernelName = `conv_bias`;
if (!context.hasKernel(kernelName)) {
const kernelSource = `${shaderGenHeader(context.webgl2)}
${shaderGenTensorOutputUniform(1)}
uniform int BATCH;
uniform int COUT;
uniform int OUTAREA;
${shaderGenTensorNDGet("tex_input_i", 1, context.webgl2)}
${shaderGenTensorNDGet("tex_input_b", 1, context.webgl2)}
void main() {
${shaderGenTensorOutputCoordsWithReturn(1)}
int rem = tex_output_flat;
int quo = rem / OUTAREA;
int x = rem - quo * OUTAREA;
rem = quo;
quo = rem / COUT;
int c = rem - quo * COUT;
int b = quo;
float s = 0.0;
s = get_tex_input_i(tex_output_flat) + get_tex_input_b(c);
${shaderGenOutput("s", context.webgl2)}
return;
}
`;
context.addKernel(kernelName, kernelSource);
}
const uniforms: WebGLUniformItem[] = [
...shaderGenTensorNDGetUniformItem(
"tex_input_i",
[1],
dI,
context.webgl2
),
...shaderGenTensorNDGetUniformItem(
"tex_input_b",
[1],
dB,
context.webgl2
),
...shaderGenTensorOutputUniformItem([dO.length], dO, context.webgl2),
{ name: "BATCH", type: "int", value: batch },
{ name: "COUT", type: "int", value: chOut },
{ name: "OUTAREA", type: "int", value: outarea },
];
await context.runKernel(
kernelName,
[
{ tensor: dI, name: "tex_input_i" },
{ tensor: dB, name: "tex_input_b" },
],
dO,
uniforms
);
}
}
export function getOpEntries(): OperatorEntry[] {
return [
{
opType: "Conv",
backend: "webgl",
opsetMin: 1,
factory: () => new WebGLConv(),
},
];
} | the_stack |
import {IOas30NodeVisitor, IOasNodeVisitor} from "../../visitors/visitor.iface";
import {OasExtensibleNode} from "../enode.model";
import {Oas30SchemaDefinition} from "./schema.model";
import {Oas30ResponseDefinition} from "./response.model";
import {Oas30ParameterDefinition} from "./parameter.model";
import {Oas30ExampleDefinition} from "./example.model";
import {Oas30RequestBodyDefinition} from "./request-body.model";
import {Oas30HeaderDefinition} from "./header.model";
import {Oas30SecurityScheme} from "./security-scheme.model";
import {Oas30LinkDefinition} from "./link.model";
import {Oas30CallbackDefinition} from "./callback.model";
/**
* Models an OAS 3.0 Components object. Example:
*
* {
* "schemas": {
* "Category": {
* "type": "object",
* "properties": {
* "id": {
* "type": "integer",
* "format": "int64"
* },
* "name": {
* "type": "string"
* }
* }
* },
* "Tag": {
* "type": "object",
* "properties": {
* "id": {
* "type": "integer",
* "format": "int64"
* },
* "name": {
* "type": "string"
* }
* }
* }
* }
* },
* "parameters": {
* "skipParam": {
* "name": "skip",
* "in": "query",
* "description": "number of items to skip",
* "required": true,
* "schema": {
* "type": "integer",
* "format": "int32"
* }
* },
* "limitParam": {
* "name": "limit",
* "in": "query",
* "description": "max records to return",
* "required": true,
* "schema" : {
* "type": "integer",
* "format": "int32"
* }
* }
* },
* "responses": {
* "NotFound": {
* "description": "Entity not found."
* },
* "IllegalInput": {
* "description": "Illegal input for operation."
* },
* "GeneralError": {
* "description": "General Error",
* "content": {
* "application/json": {
* "schema": {
* "$ref": "#/components/schemas/GeneralError"
* }
* }
* }
* }
* },
* "securitySchemes": {
* "api_key": {
* "type": "apiKey",
* "name": "api_key",
* "in": "header"
* },
* "petstore_auth": {
* "type": "oauth2",
* "flows": {
* "implicit": {
* "authorizationUrl": "http://example.org/api/oauth/dialog",
* "scopes": {
* "write:pets": "modify pets in your account",
* "read:pets": "read your pets"
* }
* }
* }
* }
* }
* }
*/
export class Oas30Components extends OasExtensibleNode {
public schemas: Oas30SchemaComponents = new Oas30SchemaComponents();
public responses: Oas30ResponseComponents = new Oas30ResponseComponents();
public parameters: Oas30ParameterComponents = new Oas30ParameterComponents();
public examples: Oas30ExampleComponents = new Oas30ExampleComponents();
public requestBodies: Oas30RequestBodyComponents = new Oas30RequestBodyComponents();
public headers: Oas30HeaderComponents = new Oas30HeaderComponents();
public securitySchemes: Oas30SecuritySchemeComponents = new Oas30SecuritySchemeComponents();
public links: Oas30LinkComponents = new Oas30LinkComponents();
public callbacks: Oas30CallbackComponents = new Oas30CallbackComponents();
/**
* Accepts the given OAS node visitor and calls the appropriate method on it to visit this node.
* @param visitor
*/
public accept(visitor: IOasNodeVisitor): void {
let viz: IOas30NodeVisitor = visitor as IOas30NodeVisitor;
viz.visitComponents(this);
}
/**
* Creates a schema definition.
* @param name
* @return {Oas30SchemaDefinition}
*/
public createSchemaDefinition(name: string): Oas30SchemaDefinition {
let rval: Oas30SchemaDefinition = new Oas30SchemaDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a schema definition.
* @param name
* @param schemaDefinition
*/
public addSchemaDefinition(name: string, schemaDefinition: Oas30SchemaDefinition): void {
this.schemas[name] = schemaDefinition;
}
/**
* Gets a single schema definition by name.
* @param name
* @return {Oas30SchemaDefinition}
*/
public getSchemaDefinition(name: string): Oas30SchemaDefinition {
return this.schemas[name];
}
/**
* Removes a single schema definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30SchemaDefinition}
*/
public removeSchemaDefinition(name: string): Oas30SchemaDefinition {
let rval: Oas30SchemaDefinition = this.schemas[name];
if (rval) {
delete this.schemas[name];
}
return rval;
}
/**
* Gets a list of all schema definitions.
* @return {Oas30SchemaDefinition[]}
*/
public getSchemaDefinitions(): Oas30SchemaDefinition[] {
let rval: Oas30SchemaDefinition[] = [];
for (let name in this.schemas) {
rval.push(this.schemas[name]);
}
return rval;
}
/**
* Creates a response definition.
* @param name
* @return {Oas30ResponseDefinition}
*/
public createResponseDefinition(name: string): Oas30ResponseDefinition {
let rval: Oas30ResponseDefinition = new Oas30ResponseDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a response definition.
* @param name
* @param responseDefinition
*/
public addResponseDefinition(name: string, responseDefinition: Oas30ResponseDefinition): void {
this.responses[name] = responseDefinition;
}
/**
* Gets a single response definition by name.
* @param name
* @return {Oas30ResponseDefinition}
*/
public getResponseDefinition(name: string): Oas30ResponseDefinition {
return this.responses[name];
}
/**
* Removes a single response definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30ResponseDefinition}
*/
public removeResponseDefinition(name: string): Oas30ResponseDefinition {
let rval: Oas30ResponseDefinition = this.responses[name];
if (rval) {
delete this.responses[name];
}
return rval;
}
/**
* Gets a list of all response definitions.
* @return {Oas30ResponseDefinition[]}
*/
public getResponseDefinitions(): Oas30ResponseDefinition[] {
let rval: Oas30ResponseDefinition[] = [];
for (let name in this.responses) {
rval.push(this.responses[name]);
}
return rval;
}
/**
* Creates a parameter definition.
* @param name
* @return {Oas30ParameterDefinition}
*/
public createParameterDefinition(name: string): Oas30ParameterDefinition {
let rval: Oas30ParameterDefinition = new Oas30ParameterDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a parameter definition.
* @param name
* @param parameterDefinition
*/
public addParameterDefinition(name: string, parameterDefinition: Oas30ParameterDefinition): void {
this.parameters[name] = parameterDefinition;
}
/**
* Gets a single parameter definition by name.
* @param name
* @return {Oas30ParameterDefinition}
*/
public getParameterDefinition(name: string): Oas30ParameterDefinition {
return this.parameters[name];
}
/**
* Removes a single parameter definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30ParameterDefinition}
*/
public removeParameterDefinition(name: string): Oas30ParameterDefinition {
let rval: Oas30ParameterDefinition = this.parameters[name];
if (rval) {
delete this.parameters[name];
}
return rval;
}
/**
* Gets a list of all parameter definitions.
* @return {Oas30ParameterDefinition[]}
*/
public getParameterDefinitions(): Oas30ParameterDefinition[] {
let rval: Oas30ParameterDefinition[] = [];
for (let name in this.parameters) {
rval.push(this.parameters[name]);
}
return rval;
}
/**
* Creates a example definition.
* @param name
* @return {Oas30ExampleDefinition}
*/
public createExampleDefinition(name: string): Oas30ExampleDefinition {
let rval: Oas30ExampleDefinition = new Oas30ExampleDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a example definition.
* @param name
* @param exampleDefinition
*/
public addExampleDefinition(name: string, exampleDefinition: Oas30ExampleDefinition): void {
this.examples[name] = exampleDefinition;
}
/**
* Gets a single example definition by name.
* @param name
* @return {Oas30ExampleDefinition}
*/
public getExampleDefinition(name: string): Oas30ExampleDefinition {
return this.examples[name];
}
/**
* Removes a single example definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30ExampleDefinition}
*/
public removeExampleDefinition(name: string): Oas30ExampleDefinition {
let rval: Oas30ExampleDefinition = this.examples[name];
if (rval) {
delete this.examples[name];
}
return rval;
}
/**
* Gets a list of all example definitions.
* @return {Oas30ExampleDefinition[]}
*/
public getExampleDefinitions(): Oas30ExampleDefinition[] {
let rval: Oas30ExampleDefinition[] = [];
for (let name in this.examples) {
rval.push(this.examples[name]);
}
return rval;
}
/**
* Creates a request body definition.
* @param name
* @return {Oas30RequestBodyDefinition}
*/
public createRequestBodyDefinition(name: string): Oas30RequestBodyDefinition {
let rval: Oas30RequestBodyDefinition = new Oas30RequestBodyDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a request body definition.
* @param name
* @param requestBodyDefinition
*/
public addRequestBodyDefinition(name: string, requestBodyDefinition: Oas30RequestBodyDefinition): void {
this.requestBodies[name] = requestBodyDefinition;
}
/**
* Gets a single request body definition by name.
* @param name
* @return {Oas30RequestBodyDefinition}
*/
public getRequestBodyDefinition(name: string): Oas30RequestBodyDefinition {
return this.requestBodies[name];
}
/**
* Removes a single request body definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30RequestBodyDefinition}
*/
public removeRequestBodyDefinition(name: string): Oas30RequestBodyDefinition {
let rval: Oas30RequestBodyDefinition = this.requestBodies[name];
if (rval) {
delete this.requestBodies[name];
}
return rval;
}
/**
* Gets a list of all request body definitions.
* @return {Oas30RequestBodyDefinition[]}
*/
public getRequestBodyDefinitions(): Oas30RequestBodyDefinition[] {
let rval: Oas30RequestBodyDefinition[] = [];
for (let name in this.requestBodies) {
rval.push(this.requestBodies[name]);
}
return rval;
}
/**
* Creates a header definition.
* @param name
* @return {Oas30HeaderDefinition}
*/
public createHeaderDefinition(name: string): Oas30HeaderDefinition {
let rval: Oas30HeaderDefinition = new Oas30HeaderDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a header definition.
* @param name
* @param headerDefinition
*/
public addHeaderDefinition(name: string, headerDefinition: Oas30HeaderDefinition): void {
this.headers[name] = headerDefinition;
}
/**
* Gets a single header definition by name.
* @param name
* @return {Oas30HeaderDefinition}
*/
public getHeaderDefinition(name: string): Oas30HeaderDefinition {
return this.headers[name];
}
/**
* Removes a single header definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30HeaderDefinition}
*/
public removeHeaderDefinition(name: string): Oas30HeaderDefinition {
let rval: Oas30HeaderDefinition = this.headers[name];
if (rval) {
delete this.headers[name];
}
return rval;
}
/**
* Gets a list of all header definitions.
* @return {Oas30HeaderDefinition[]}
*/
public getHeaderDefinitions(): Oas30HeaderDefinition[] {
let rval: Oas30HeaderDefinition[] = [];
for (let name in this.headers) {
rval.push(this.headers[name]);
}
return rval;
}
/**
* Creates a security scheme definition.
* @param name
* @return {Oas30SecurityScheme}
*/
public createSecurityScheme(name: string): Oas30SecurityScheme {
let rval: Oas30SecurityScheme = new Oas30SecurityScheme(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a security scheme definition.
* @param name
* @param securityScheme
*/
public addSecurityScheme(name: string, securityScheme: Oas30SecurityScheme): void {
this.securitySchemes[name] = securityScheme;
}
/**
* Gets a single security scheme definition by name.
* @param name
* @return {Oas30SecurityScheme}
*/
public getSecurityScheme(name: string): Oas30SecurityScheme {
return this.securitySchemes[name];
}
/**
* Removes a single security scheme definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30SecurityScheme}
*/
public removeSecurityScheme(name: string): Oas30SecurityScheme {
let rval: Oas30SecurityScheme = this.securitySchemes[name];
if (rval) {
delete this.securitySchemes[name];
}
return rval;
}
/**
* Gets a list of all security scheme definitions.
* @return {Oas30SecurityScheme[]}
*/
public getSecuritySchemes(): Oas30SecurityScheme[] {
let rval: Oas30SecurityScheme[] = [];
for (let name in this.securitySchemes) {
rval.push(this.securitySchemes[name]);
}
return rval;
}
/**
* Creates a link definition.
* @param name
* @return {Oas30LinkDefinition}
*/
public createLinkDefinition(name: string): Oas30LinkDefinition {
let rval: Oas30LinkDefinition = new Oas30LinkDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a link definition.
* @param name
* @param linkDefinition
*/
public addLinkDefinition(name: string, linkDefinition: Oas30LinkDefinition): void {
this.links[name] = linkDefinition;
}
/**
* Gets a single link definition by name.
* @param name
* @return {Oas30LinkDefinition}
*/
public getLinkDefinition(name: string): Oas30LinkDefinition {
return this.links[name];
}
/**
* Removes a single link definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30LinkDefinition}
*/
public removeLinkDefinition(name: string): Oas30LinkDefinition {
let rval: Oas30LinkDefinition = this.links[name];
if (rval) {
delete this.links[name];
}
return rval;
}
/**
* Gets a list of all link definitions.
* @return {Oas30LinkDefinition[]}
*/
public getLinkDefinitions(): Oas30LinkDefinition[] {
let rval: Oas30LinkDefinition[] = [];
for (let name in this.links) {
rval.push(this.links[name]);
}
return rval;
}
/**
* Creates a callback definition.
* @param name
* @return {Oas30CallbackDefinition}
*/
public createCallbackDefinition(name: string): Oas30CallbackDefinition {
let rval: Oas30CallbackDefinition = new Oas30CallbackDefinition(name);
rval._ownerDocument = this._ownerDocument;
rval._parent = this;
return rval;
}
/**
* Adds a callback definition.
* @param name
* @param callbackDefinition
*/
public addCallbackDefinition(name: string, callbackDefinition: Oas30CallbackDefinition): void {
this.callbacks[name] = callbackDefinition;
}
/**
* Gets a single callback definition by name.
* @param name
* @return {Oas30CallbackDefinition}
*/
public getCallbackDefinition(name: string): Oas30CallbackDefinition {
return this.callbacks[name];
}
/**
* Removes a single callback definition and returns it. This may return null or undefined if none found.
* @param name
* @return {Oas30CallbackDefinition}
*/
public removeCallbackDefinition(name: string): Oas30CallbackDefinition {
let rval: Oas30CallbackDefinition = this.callbacks[name];
if (rval) {
delete this.callbacks[name];
}
return rval;
}
/**
* Gets a list of all callback definitions.
* @return {Oas30CallbackDefinition[]}
*/
public getCallbackDefinitions(): Oas30CallbackDefinition[] {
let rval: Oas30CallbackDefinition[] = [];
for (let name in this.callbacks) {
rval.push(this.callbacks[name]);
}
return rval;
}
}
export class Oas30SchemaComponents {
[key: string]: Oas30SchemaDefinition;
}
export class Oas30ResponseComponents {
[key: string]: Oas30ResponseDefinition;
}
export class Oas30ParameterComponents {
[key: string]: Oas30ParameterDefinition;
}
export class Oas30ExampleComponents {
[key: string]: Oas30ExampleDefinition;
}
export class Oas30RequestBodyComponents {
[key: string]: Oas30RequestBodyDefinition;
}
export class Oas30HeaderComponents {
[key: string]: Oas30HeaderDefinition;
}
export class Oas30SecuritySchemeComponents {
[key: string]: Oas30SecurityScheme;
}
export class Oas30LinkComponents {
[key: string]: Oas30LinkDefinition;
}
export class Oas30CallbackComponents {
[key: string]: Oas30CallbackDefinition;
} | the_stack |
import {OasLibraryUtils} from "../src/library.utils";
import {Oas30Document} from "../src/models/3.0/document.model";
import {Oas20Document} from "../src/models/2.0/document.model";
export interface TestSpec {
name: string;
input: string;
expected: string;
debug?: boolean;
}
/**
* Tests for the transformation of a 2.0 document into a 3.0 document.
*/
describe("Transformation", () => {
let TESTS: TestSpec[] = [
/** Simple Tests **/
/** ************ **/
{
name: "Simple (Easy 2.0 spec)",
input: "tests/fixtures/transformation/simple/simplest.input.json",
expected: "tests/fixtures/transformation/simple/simplest.expected.json"
},
{
name: "Simple (Info)",
input: "tests/fixtures/transformation/simple/simple-info.input.json",
expected: "tests/fixtures/transformation/simple/simple-info.expected.json"
},
{
name: "Simple (Info+Extensions)",
input: "tests/fixtures/transformation/simple/simple-info-extensions.input.json",
expected: "tests/fixtures/transformation/simple/simple-info-extensions.expected.json"
},
{
name: "Simple (Server)",
input: "tests/fixtures/transformation/simple/simple-server.input.json",
expected: "tests/fixtures/transformation/simple/simple-server.expected.json"
},
{
name: "Simple (Server+Schemes)",
input: "tests/fixtures/transformation/simple/simple-server-with-schemes.input.json",
expected: "tests/fixtures/transformation/simple/simple-server-with-schemes.expected.json"
},
/** Paths Tests **/
/** *********** **/
{
name: "Paths (GET)",
input: "tests/fixtures/transformation/paths/paths-get.input.json",
expected: "tests/fixtures/transformation/paths/paths-get.expected.json"
},
{
name: "Paths (All Operations)",
input: "tests/fixtures/transformation/paths/paths-all-operations.input.json",
expected: "tests/fixtures/transformation/paths/paths-all-operations.expected.json"
},
{
name: "Paths (Default Response)",
input: "tests/fixtures/transformation/paths/paths-default-response.input.json",
expected: "tests/fixtures/transformation/paths/paths-default-response.expected.json"
},
{
name: "Paths (External Docs)",
input: "tests/fixtures/transformation/paths/paths-externalDocs.input.json",
expected: "tests/fixtures/transformation/paths/paths-externalDocs.expected.json"
},
{
name: "Paths (GET+Params)",
input: "tests/fixtures/transformation/paths/paths-get-with-params.input.json",
expected: "tests/fixtures/transformation/paths/paths-get-with-params.expected.json"
},
{
name: "Paths (GET+Tags)",
input: "tests/fixtures/transformation/paths/paths-get-with-tags.input.json",
expected: "tests/fixtures/transformation/paths/paths-get-with-tags.expected.json"
},
{
name: "Paths (Path Params)",
input: "tests/fixtures/transformation/paths/paths-path-with-params.input.json",
expected: "tests/fixtures/transformation/paths/paths-path-with-params.expected.json"
},
{
name: "Paths (Path Ref)",
input: "tests/fixtures/transformation/paths/paths-ref.input.json",
expected: "tests/fixtures/transformation/paths/paths-ref.expected.json"
},
{
name: "Paths (Response+Examples)",
input: "tests/fixtures/transformation/paths/paths-response-with-examples.input.json",
expected: "tests/fixtures/transformation/paths/paths-response-with-examples.expected.json"
},
{
name: "Paths (Response+Headers)",
input: "tests/fixtures/transformation/paths/paths-response-with-headers.input.json",
expected: "tests/fixtures/transformation/paths/paths-response-with-headers.expected.json"
},
{
name: "Paths (Response+Schema)",
input: "tests/fixtures/transformation/paths/paths-response-with-schema.input.json",
expected: "tests/fixtures/transformation/paths/paths-response-with-schema.expected.json"
},
{
name: "Paths (Responses)",
input: "tests/fixtures/transformation/paths/paths-responses.input.json",
expected: "tests/fixtures/transformation/paths/paths-responses.expected.json"
},
{
name: "Paths (Responses+Extensions)",
input: "tests/fixtures/transformation/paths/paths-responses-with-extensions.input.json",
expected: "tests/fixtures/transformation/paths/paths-responses-with-extensions.expected.json"
},
{
name: "Paths (Security)",
input: "tests/fixtures/transformation/paths/paths-security.input.json",
expected: "tests/fixtures/transformation/paths/paths-security.expected.json"
},
{
name: "Paths (Extensions)",
input: "tests/fixtures/transformation/paths/paths-with-extensions.input.json",
expected: "tests/fixtures/transformation/paths/paths-with-extensions.expected.json"
},
{
name: "Paths (POST+FormData)",
input: "tests/fixtures/transformation/paths/paths-post-with-formData.input.json",
expected: "tests/fixtures/transformation/paths/paths-post-with-formData.expected.json"
},
{
name: "Paths (POST+FormData+Multi)",
input: "tests/fixtures/transformation/paths/paths-post-with-formData-multi.input.json",
expected: "tests/fixtures/transformation/paths/paths-post-with-formData-multi.expected.json"
},
{
name: "Paths (GET+Schemes)",
input: "tests/fixtures/transformation/paths/paths-get-with-schemes.input.json",
expected: "tests/fixtures/transformation/paths/paths-get-with-schemes.expected.json"
},
/** Responses Tests **/
/** *************** **/
{
name: "Responses (Spec Examples)",
input: "tests/fixtures/transformation/responses/response-spec-examples.input.json",
expected: "tests/fixtures/transformation/responses/response-spec-examples.expected.json"
},
{
name: "Responses (Example 1)",
input: "tests/fixtures/transformation/responses/spec-example-1.input.json",
expected: "tests/fixtures/transformation/responses/spec-example-1.expected.json"
},
{
name: "Responses (Array Param)",
input: "tests/fixtures/transformation/responses/response-array-param.input.json",
expected: "tests/fixtures/transformation/responses/response-array-param.expected.json"
},
/** Definition Tests **/
/** **************** **/
{
name: "Definitions (JSON Schema::basic)",
input: "tests/fixtures/transformation/definitions/json-schema-basic.input.json",
expected: "tests/fixtures/transformation/definitions/json-schema-basic.expected.json"
},
{
name: "Definitions (JSON Schema::fstab)",
input: "tests/fixtures/transformation/definitions/json-schema-fstab.input.json",
expected: "tests/fixtures/transformation/definitions/json-schema-fstab.expected.json"
},
{
name: "Definitions (JSON Schema::products)",
input: "tests/fixtures/transformation/definitions/json-schema-products.input.json",
expected: "tests/fixtures/transformation/definitions/json-schema-products.expected.json"
},
{
name: "Definitions (Primitive)",
input: "tests/fixtures/transformation/definitions/primitive.input.json",
expected: "tests/fixtures/transformation/definitions/primitive.expected.json"
},
{
name: "Definitions (Additional Props)",
input: "tests/fixtures/transformation/definitions/schema-with-additionalProperties.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-additionalProperties.expected.json"
},
{
name: "Definitions (All Of)",
input: "tests/fixtures/transformation/definitions/schema-with-allOf.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-allOf.expected.json"
},
{
name: "Definitions (Composition)",
input: "tests/fixtures/transformation/definitions/schema-with-composition.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-composition.expected.json"
},
{
name: "Definitions (Example)",
input: "tests/fixtures/transformation/definitions/schema-with-example.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-example.expected.json"
},
{
name: "Definitions (Extension)",
input: "tests/fixtures/transformation/definitions/schema-with-extension.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-extension.expected.json"
},
{
name: "Definitions (External Docs)",
input: "tests/fixtures/transformation/definitions/schema-with-externalDocs.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-externalDocs.expected.json"
},
{
name: "Definitions (Meta Data)",
input: "tests/fixtures/transformation/definitions/schema-with-metaData.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-metaData.expected.json"
},
{
name: "Definitions (Polymorphism)",
input: "tests/fixtures/transformation/definitions/schema-with-polymorphism.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-polymorphism.expected.json"
},
{
name: "Definitions (XML)",
input: "tests/fixtures/transformation/definitions/schema-with-xml.input.json",
expected: "tests/fixtures/transformation/definitions/schema-with-xml.expected.json"
},
{
name: "Definitions (Spec Example 1)",
input: "tests/fixtures/transformation/definitions/spec-example-1.input.json",
expected: "tests/fixtures/transformation/definitions/spec-example-1.expected.json"
},
/** Parameters Tests **/
/** **************** **/
{
name: "Parameters (Single Array)",
input: "tests/fixtures/transformation/parameters/single-array-param.input.json",
expected: "tests/fixtures/transformation/parameters/single-array-param.expected.json"
},
{
name: "Parameters (Array)",
input: "tests/fixtures/transformation/parameters/array-param.input.json",
expected: "tests/fixtures/transformation/parameters/array-param.expected.json"
},
{
name: "Parameters (Spec Example)",
input: "tests/fixtures/transformation/parameters/spec-example-1.input.json",
expected: "tests/fixtures/transformation/parameters/spec-example-1.expected.json"
},
{
name: "Parameters (Body Param)",
input: "tests/fixtures/transformation/parameters/body-param.input.json",
expected: "tests/fixtures/transformation/parameters/body-param.expected.json"
},
{
name: "Parameters (File)",
input: "tests/fixtures/transformation/parameters/file-param.input.json",
expected: "tests/fixtures/transformation/parameters/file-param.expected.json"
},
/** Security Schemes **/
/** **************** **/
{
name: "Security Schemes (All)",
input: "tests/fixtures/transformation/security/security-allSchemes.input.json",
expected: "tests/fixtures/transformation/security/security-allSchemes.expected.json"
},
/** Reference Tests **/
/** *************** **/
{
name: "References (Schema)",
input: "tests/fixtures/transformation/references/schema-reference.input.json",
expected: "tests/fixtures/transformation/references/schema-reference.expected.json"
},
{
name: "References (Response)",
input: "tests/fixtures/transformation/references/response-reference.input.json",
expected: "tests/fixtures/transformation/references/response-reference.expected.json"
},
{
name: "References (Parameter)",
input: "tests/fixtures/transformation/references/parameter-reference.input.json",
expected: "tests/fixtures/transformation/references/parameter-reference.expected.json"
},
{
name: "References (Body Parameter)",
input: "tests/fixtures/transformation/references/bodyParam-reference.input.json",
expected: "tests/fixtures/transformation/references/bodyParam-reference.expected.json",
},
{
name: "References (Form Data Parameter)",
input: "tests/fixtures/transformation/references/formDataParam-reference.input.json",
expected: "tests/fixtures/transformation/references/formDataParam-reference.expected.json"
},
];
let library: OasLibraryUtils;
beforeEach(() => {
library = new OasLibraryUtils();
});
// All tests in the list above.
TESTS.forEach( spec => {
it(spec.name, () => {
if (spec.debug) {
console.info("******* Running input: " + spec.input);
}
let inputJso: any = readJSON(spec.input);
let expectedJso: any = readJSON(spec.expected);
if (!inputJso && spec.debug) {
console.error("Failed to load input: " + spec.input);
}
if (!expectedJso && spec.debug) {
console.error("Failed to load expected: " + spec.expected);
}
expect(inputJso).toBeTruthy();
expect(expectedJso).toBeTruthy();
let input: Oas20Document = library.createDocument(inputJso) as Oas20Document;
let actual: Oas30Document = library.transformDocument(input);
let actualJso: any = library.writeNode(actual);
if (spec.debug) {
console.info("------- INPUT --------\n " + JSON.stringify(inputJso, null, 2) + "\n-------------------");
console.info("------- ACTUAL --------\n " + JSON.stringify(actualJso, null, 2) + "\n-------------------");
console.info("------- EXPECTED --------\n " + JSON.stringify(expectedJso, null, 2) + "\n-------------------");
}
expect(actualJso).toEqual(expectedJso);
});
});
}); | the_stack |
import { PackageInspectorBase } from './PackageInspectorBase';
import { injectable, inject } from 'inversify';
import { Types } from '../../types';
import { IFileInspector } from '../IFileInspector';
import * as TOML from '@iarna/toml';
import { DependencyType, Package, PackageVersion } from '../IPackageInspector';
const isRecord = (v: unknown): v is Record<string, unknown> => {
return typeof v === 'object' && v !== null;
};
const isString = (v: unknown): v is string => {
return typeof v === 'string';
};
const isOptString = (v: unknown): v is string | undefined => {
return typeof v === 'string' || v === undefined;
};
const isOptBool = (v: unknown): v is boolean | undefined => {
return typeof v === 'boolean' || v === undefined;
};
const isOptStringArray = (v: unknown): v is string[] | undefined => {
return v === undefined || (Array.isArray(v) && v.every((e) => typeof e === 'string'));
};
/**
* Similar to `lodash.conformsTo` but runs the check on `undefined` instead of failing.
*/
const conformsOptional = (check: Record<string, (v: unknown) => boolean>, value: Record<string, unknown>): boolean => {
return Object.keys(check).every((key) => check[key](value[key]));
};
@injectable()
export class RustPackageInspector extends PackageInspectorBase {
private readonly fileInspector: IFileInspector;
cargoLock?: CargoLock;
cargoManifest?: CargoManifest | CargoWorkspaceManifest;
constructor(@inject(Types.IFileInspector) fileInspector: IFileInspector) {
super();
this.fileInspector = fileInspector;
}
async init(): Promise<void> {
try {
this.debug('RustPackageInspector init started');
let cargoLockString = undefined;
try {
cargoLockString = await this.fileInspector.readFile('Cargo.lock');
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
if (cargoLockString !== undefined) {
const cargoLockToml = TOML.parse(cargoLockString);
this.cargoLock = RustPackageInspector.parseLock(cargoLockToml);
}
let cargoManifestString = undefined;
try {
cargoManifestString = await this.fileInspector.readFile('Cargo.toml');
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
if (cargoManifestString !== undefined) {
const cargoManifestToml = TOML.parse(cargoManifestString);
if ('workspace' in cargoManifestToml) {
this.cargoManifest = {
workspace: RustPackageInspector.parseWorkspace(cargoManifestToml['workspace']),
};
this.packages = [];
} else {
this.cargoManifest = {
package: RustPackageInspector.parsePackage(cargoManifestToml['package']),
...RustPackageInspector.parseDependencySet(cargoManifestToml),
target: RustPackageInspector.parseTarget(cargoManifestToml['target']),
bin: RustPackageInspector.parseBin(cargoManifestToml['bin']),
profile: cargoManifestToml['profile'],
};
this.packages = RustPackageInspector.addPackages(this.cargoManifest, this.cargoLock);
}
}
this.debug(this.cargoLock);
this.debug(this.cargoManifest);
this.debug('RustPackageInspector init ended');
} catch (e) {
this.packages = undefined;
this.debug(e);
console.error(e);
}
}
hasLockfile(): boolean | undefined {
return this.cargoLock !== undefined;
}
private static parseWorkspace(value: unknown): CargoWorkspaceManifest['workspace'] {
if (isRecord(value)) {
const members = value['members'];
if (Array.isArray(members) && members.every((m) => typeof m === 'string')) {
return {
members,
};
}
}
throw new Error('Could not parse Cargo.toml workspace');
}
private static parseDependency(key: string, value: unknown): ManifestDependency {
if (typeof value === 'string') {
return {
name: key,
version: value,
};
}
if (isRecord(value)) {
if (
conformsOptional(
{
version: isOptString,
path: isOptString,
git: isOptString,
branch: isOptString,
package: isOptString,
optional: isOptBool,
'default-features': isOptBool,
features: isOptStringArray,
registry: isOptString,
},
value,
)
) {
// Safe because we just checked that it conforms
const v = (value as unknown) as ManifestDependency;
v.name = key;
return v;
}
}
throw new Error(`Could not parse Cargo.toml dependency "${key}"`);
}
private static parseDependencies(values: unknown): ReadonlyArray<ManifestDependency> {
const result: ManifestDependency[] = [];
if (values === undefined) {
return result;
}
if (isRecord(values)) {
for (const key of Object.keys(values)) {
result.push(RustPackageInspector.parseDependency(key, values[key]));
}
return result;
}
throw new Error('Could not parse Cargo.toml dependencies array');
}
private static parseDependencySet(obj: Record<string, unknown>): DependecySet {
return {
dependencies: RustPackageInspector.parseDependencies(obj['dependencies']),
'dev-dependencies': RustPackageInspector.parseDependencies(obj['dev-dependencies']),
'build-dependencies': RustPackageInspector.parseDependencies(obj['build-dependencies']),
};
}
private static parseTarget(value: unknown): CargoManifest['target'] {
if (value === undefined) {
return {};
}
if (isRecord(value)) {
const result: CargoManifest['target'] = {};
for (const key of Object.keys(value)) {
const target = value[key];
if (isRecord(target)) {
result[key] = RustPackageInspector.parseDependencySet(target);
}
}
return result;
}
console.error(value);
throw new Error('Could not parse Cargo.toml target table');
}
private static parseBinaryInfo(value: unknown): BinaryInfo {
if (isRecord(value)) {
if (
conformsOptional(
{
name: isString,
path: isString,
},
value,
)
) {
// Safe because we just checked conformity
return (value as unknown) as BinaryInfo;
}
}
throw new Error('Could not parse Cargo.toml bin array entry');
}
private static parseBin(value: unknown): CargoManifest['bin'] {
if (value === undefined) {
return [];
}
if (Array.isArray(value)) {
return value.map((e) => RustPackageInspector.parseBinaryInfo(e));
}
throw new Error('Could not parse Cargo.toml bin array');
}
private static parsePackage(value: unknown): CargoManifest['package'] {
if (isRecord(value)) {
if (
conformsOptional(
{
name: isString,
version: isString,
authors: isOptStringArray,
edition: (v) => v === '2015' || v === '2018',
description: isOptString,
documentation: isOptString,
readme: isOptString,
homepage: isOptString,
repository: isOptString,
license: isOptString,
'license-file': isOptString,
keywords: isOptStringArray,
categories: isOptStringArray,
workspace: isOptString,
build: isOptString,
links: isOptString,
exclude: isOptStringArray,
include: isOptStringArray,
publish: (v) => typeof v === 'boolean' || isOptStringArray(v),
metadata: (v) => v === undefined || isRecord(v),
'default-run': isOptString,
},
value,
)
) {
return value as CargoManifest['package'];
}
}
throw new Error('Could not parse Cargo.toml package table');
}
private static parseLockPackage(value: unknown): CargoLockPackage {
if (isRecord(value)) {
if (
conformsOptional(
{
name: isString,
version: isString,
source: isOptString,
checksum: isOptString,
dependencies: isOptStringArray,
},
value,
)
) {
return (value as unknown) as CargoLockPackage;
}
}
throw new Error('Could not parse Cargo.lock package');
}
private static parseLock(value: unknown): CargoLock {
if (isRecord(value)) {
if (Array.isArray(value['package'])) {
const result: {
package: CargoLockPackage[];
} = {
package: [],
};
result.package.push(...value['package'].map((p) => RustPackageInspector.parseLockPackage(p)));
return result;
}
}
throw new Error('Could not parse Cargo.lock');
}
private static parseSemver(version: string | undefined): PackageVersion {
let result = undefined;
if (version !== undefined) {
result = PackageInspectorBase.semverToPackageVersion(version);
}
return (
result ?? {
value: '0.0.0',
major: '0',
minor: '0',
patch: '0',
}
);
}
private static addPackages(manifest: CargoManifest, lockFile?: CargoLock): Package[] {
const parseDep = (type: DependencyType, dep: ManifestDependency) => {
const name = dep.package ?? dep.name;
const version = RustPackageInspector.parseSemver(dep.version);
const lockVersion =
lockFile === undefined ? version : RustPackageInspector.parseSemver(lockFile.package.find((p) => p.name === name)?.version);
return {
dependencyType: type,
name,
requestedVersion: version,
lockfileVersion: lockVersion,
};
};
const parseRuntimeDep = parseDep.bind(undefined, DependencyType.Runtime);
const parseDevDep = parseDep.bind(undefined, DependencyType.Dev);
const result: Package[] = [];
result.push(
...manifest.dependencies.map(parseRuntimeDep),
...manifest['dev-dependencies'].map(parseDevDep),
// ...manifest["build-dependencies"].map(), // TODO
...Object.values(manifest.target ?? {}).flatMap((target) =>
target.dependencies.map(parseRuntimeDep).concat(
...target['dev-dependencies'].map(parseDevDep),
// ...target["build-dependencies"].map() // TODO
),
),
);
return result;
}
}
export interface ManifestDependency {
name: string;
version?: string;
path?: string;
git?: string;
branch?: string;
package?: string;
optional?: boolean;
'default-features'?: boolean;
features?: string[];
registry?: string;
}
export interface BinaryInfo {
name: string;
path: string;
}
export interface DependecySet {
dependencies: ReadonlyArray<ManifestDependency>;
'dev-dependencies': ReadonlyArray<ManifestDependency>;
'build-dependencies': ReadonlyArray<ManifestDependency>;
}
// https://doc.rust-lang.org/cargo/reference/manifest.html
export interface CargoManifest extends DependecySet {
package: {
name: string;
version: string;
authors?: string[];
edition?: '2015' | '2018';
description?: string;
documentation?: string;
readme?: string;
homepage?: string;
repository?: string;
license?: string;
'license-file'?: string;
keywords?: string[];
categories?: string[];
workspace?: string;
build?: string;
links?: string;
exclude?: string[];
include?: string[];
publish?: boolean | string[];
metadata?: Record<string, unknown>;
'default-run'?: string;
};
bin: ReadonlyArray<BinaryInfo>;
target: Record<string, DependecySet>;
profile?: unknown;
}
export interface CargoWorkspaceManifest {
workspace: {
members: string[];
};
}
export interface CargoLockPackage {
name: string;
version: string;
source?: string;
checksum?: string;
dependencies?: string[];
}
export interface CargoLock {
package: ReadonlyArray<CargoLockPackage>;
} | the_stack |
import {isES2015Class, getFunctionName, getTypeOf} from 'core-helpers';
import compact from 'lodash/compact';
import type {Component, ComponentMixin} from './component';
/**
* Returns whether the specified value is a component class.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isComponentClass(value: any): value is typeof Component {
return typeof value?.isComponent === 'function';
}
/**
* Returns whether the specified value is a component instance.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isComponentInstance(value: any): value is Component {
return typeof value?.constructor?.isComponent === 'function';
}
/**
* Returns whether the specified value is a component class or instance.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isComponentClassOrInstance(value: any): value is typeof Component | Component {
return (
typeof value?.isComponent === 'function' ||
typeof value?.constructor?.isComponent === 'function'
);
}
/**
* Throws an error if the specified value is not a component class.
*
* @param value A value of any type.
*
* @category Utilities
*/
export function assertIsComponentClass(value: any): asserts value is typeof Component {
if (!isComponentClass(value)) {
throw new Error(
`Expected a component class, but received a value of type '${getTypeOf(value)}'`
);
}
}
/**
* Throws an error if the specified value is not a component instance.
*
* @param value A value of any type.
*
* @category Utilities
*/
export function assertIsComponentInstance(value: any): asserts value is Component {
if (!isComponentInstance(value)) {
throw new Error(
`Expected a component instance, but received a value of type '${getTypeOf(value)}'`
);
}
}
/**
* Throws an error if the specified value is not a component class or instance.
*
* @param value A value of any type.
*
* @category Utilities
*/
export function assertIsComponentClassOrInstance(
value: any
): asserts value is typeof Component | Component {
if (!isComponentClassOrInstance(value)) {
throw new Error(
`Expected a component class or instance, but received a value of type '${getTypeOf(value)}'`
);
}
}
/**
* Ensures that the specified component is a class. If you specify a component instance (or prototype), the class of the component is returned. If you specify a component class, it is returned as is.
*
* @param component A component class or instance.
*
* @returns A component class.
*
* @example
* ```
* ensureComponentClass(movie) => Movie
* ensureComponentClass(Movie.prototype) => Movie
* ensureComponentClass(Movie) => Movie
* ```
*
* @category Utilities
*/
export function ensureComponentClass(component: any) {
if (isComponentClass(component)) {
return component;
}
if (isComponentInstance(component)) {
return component.constructor as typeof Component;
}
throw new Error(
`Expected a component class or instance, but received a value of type '${getTypeOf(component)}'`
);
}
/**
* Ensures that the specified component is an instance (or prototype). If you specify a component class, the component prototype is returned. If you specify a component instance (or prototype), it is returned as is.
*
* @param component A component class or instance.
*
* @returns A component instance (or prototype).
*
* @example
* ```
* ensureComponentInstance(Movie) => Movie.prototype
* ensureComponentInstance(Movie.prototype) => Movie.prototype
* ensureComponentInstance(movie) => movie
* ```
*
* @category Utilities
*/
export function ensureComponentInstance(component: any) {
if (isComponentClass(component)) {
return component.prototype;
}
if (isComponentInstance(component)) {
return component;
}
throw new Error(
`Expected a component class or instance, but received a value of type '${getTypeOf(component)}'`
);
}
const COMPONENT_NAME_PATTERN = /^[A-Z][A-Za-z0-9_]*$/;
/**
* Returns whether the specified string is a valid component name. The rule is the same as for typical JavaScript class names.
*
* @param name The string to check.
*
* @returns A boolean.
*
* @example
* ```
* isComponentName('Movie') => true
* isComponentName('Movie123') => true
* isComponentName('Awesome_Movie') => true
* isComponentName('123Movie') => false
* isComponentName('Awesome-Movie') => false
* isComponentName('movie') => false
* ```
*
* @category Utilities
*/
export function isComponentName(name: string) {
return COMPONENT_NAME_PATTERN.test(name);
}
/**
* Throws an error if the specified string is not a valid component name.
*
* @param name The string to check.
*
* @category Utilities
*/
export function assertIsComponentName(name: string) {
if (name === '') {
throw new Error('A component name cannot be empty');
}
if (!isComponentName(name)) {
throw new Error(`The specified component name ('${name}') is invalid`);
}
}
/**
* Transforms a component class type into a component name.
*
* @param name A string representing a component class type.
*
* @returns A component name.
*
* @example
* ```
* getComponentNameFromComponentClassType('typeof Movie') => 'Movie'
* ```
*
* @category Utilities
*/
export function getComponentNameFromComponentClassType(type: string) {
assertIsComponentType(type, {allowInstances: false});
return type.slice('typeof '.length);
}
/**
* Transforms a component instance type into a component name.
*
* @param name A string representing a component instance type.
*
* @returns A component name.
*
* @example
* ```
* getComponentNameFromComponentInstanceType('Movie') => 'Movie'
* ```
*
* @category Utilities
*/
export function getComponentNameFromComponentInstanceType(type: string) {
assertIsComponentType(type, {allowClasses: false});
return type;
}
const COMPONENT_CLASS_TYPE_PATTERN = /^typeof [A-Z][A-Za-z0-9_]*$/;
const COMPONENT_INSTANCE_TYPE_PATTERN = /^[A-Z][A-Za-z0-9_]*$/;
/**
* Returns whether the specified string is a valid component type.
*
* @param name The string to check.
* @param [options.allowClasses] A boolean specifying whether component class types are allowed (default: `true`).
* @param [options.allowInstances] A boolean specifying whether component instance types are allowed (default: `true`).
*
* @returns A boolean.
*
* @example
* ```
* isComponentType('typeof Movie') => true
* isComponentType('Movie') => true
* isComponentType('typeof Awesome-Movie') => false
* isComponentType('movie') => false
* isComponentType('typeof Movie', {allowClasses: false}) => false
* isComponentType('Movie', {allowInstances: false}) => false
* ```
*
* @category Utilities
*/
export function isComponentType(type: string, {allowClasses = true, allowInstances = true} = {}) {
if (allowClasses && COMPONENT_CLASS_TYPE_PATTERN.test(type)) {
return 'componentClassType';
}
if (allowInstances && COMPONENT_INSTANCE_TYPE_PATTERN.test(type)) {
return 'componentInstanceType';
}
return false;
}
/**
* Throws an error if the specified string is not a valid component type.
*
* @param name The string to check.
* @param [options.allowClasses] A boolean specifying whether component class types are allowed (default: `true`).
* @param [options.allowInstances] A boolean specifying whether component instance types are allowed (default: `true`).
*
* @category Utilities
*/
export function assertIsComponentType(
type: string,
{allowClasses = true, allowInstances = true} = {}
) {
if (type === '') {
throw new Error('A component type cannot be empty');
}
const isComponentTypeResult = isComponentType(type, {allowClasses, allowInstances});
if (isComponentTypeResult === false) {
throw new Error(`The specified component type ('${type}') is invalid`);
}
return isComponentTypeResult;
}
/**
* Transforms a component name into a component class type.
*
* @param name A component name.
*
* @returns A component class type.
*
* @example
* ```
* getComponentClassTypeFromComponentName('Movie') => 'typeof Movie'
* ```
*
* @category Utilities
*/
export function getComponentClassTypeFromComponentName(name: string) {
assertIsComponentName(name);
return `typeof ${name}`;
}
/**
* Transforms a component name into a component instance type.
*
* @param name A component name.
*
* @returns A component instance type.
*
* @example
* ```
* getComponentInstanceTypeFromComponentName('Movie') => 'Movie'
* ```
*
* @category Utilities
*/
export function getComponentInstanceTypeFromComponentName(name: string) {
assertIsComponentName(name);
return name;
}
type ComponentMap = {[name: string]: typeof Component};
export function createComponentMap(components: typeof Component[] = []) {
const componentMap: ComponentMap = Object.create(null);
for (const component of components) {
assertIsComponentClass(component);
componentMap[component.getComponentName()] = component;
}
return componentMap;
}
export function getComponentFromComponentMap(componentMap: ComponentMap, name: string) {
assertIsComponentName(name);
const component = componentMap[name];
if (component === undefined) {
throw new Error(`The component '${name}' is unknown`);
}
return component;
}
export function isComponentMixin(value: any): value is ComponentMixin {
return typeof value === 'function' && getFunctionName(value) !== '' && !isES2015Class(value);
}
export function assertIsComponentMixin(value: any): asserts value is ComponentMixin {
if (!isComponentMixin(value)) {
throw new Error(
`Expected a component mixin, but received a value of type '${getTypeOf(value)}'`
);
}
}
export function composeDescription(description: string[]) {
let composedDescription = compact(description).join(', ');
if (composedDescription !== '') {
composedDescription = ` (${composedDescription})`;
}
return composedDescription;
}
export function joinAttributePath(path: [string?, string?]) {
const compactedPath = compact(path);
if (compactedPath.length === 0) {
return '';
}
if (compactedPath.length === 1) {
return compactedPath[0];
}
const [first, second] = compactedPath;
if (second.startsWith('[')) {
return `${first}${second}`;
}
return `${first}.${second}`;
} | the_stack |
import { Component, Input, OnInit } from '@angular/core';
import { LockRepositoryPolicy, SubmissionPenaltyPolicy, SubmissionPolicyType } from 'app/entities/submission-policy.model';
import { ProgrammingExercise } from 'app/entities/programming-exercise.model';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'jhi-submission-policy-update',
template: `
<div class="form-group-narrow mb-3">
<label class="label-narrow" jhiTranslate="artemisApp.programmingExercise.submissionPolicy.title" for="field_submissionPolicy">Submission Policy</label>
<select
#policy
required
class="form-select"
[ngModel]="selectedSubmissionPolicyType"
(ngModelChange)="policy.value = onSubmissionPolicyTypeChanged($event)"
name="submissionPolicyType"
id="field_submissionPolicy"
[disabled]="!editable"
>
<option value="none">{{ 'artemisApp.programmingExercise.submissionPolicy.none.optionLabel' | artemisTranslate }}</option>
<option value="lock_repository">{{ 'artemisApp.programmingExercise.submissionPolicy.lockRepository.optionLabel' | artemisTranslate }}</option>
<option value="submission_penalty">{{ 'artemisApp.programmingExercise.submissionPolicy.submissionPenalty.optionLabel' | artemisTranslate }}</option>
</select>
</div>
<form [formGroup]="form" *ngIf="!isNonePolicy">
<div class="row mb-3">
<div class="col">
<ng-container>
<label class="label-narrow" jhiTranslate="artemisApp.programmingExercise.submissionPolicy.submissionLimitTitle" for="field_submissionLimitExceededPenalty"
>Submission Limit</label
>
<jhi-help-icon placement="top" text="artemisApp.programmingExercise.submissionPolicy.submissionLimitDescription"></jhi-help-icon>
<div class="input-group">
<input
required
type="number"
formControlName="submissionLimit"
class="form-control"
step="1"
name="submissionLimit"
id="field_submissionLimit"
(input)="updateSubmissionLimit()"
/>
</div>
<ng-container *ngFor="let e of submissionLimitControl.errors! | keyvalue">
<div *ngIf="submissionLimitControl.invalid && (submissionLimitControl.dirty || submissionLimitControl.touched)" class="alert alert-danger">
<div [jhiTranslate]="'artemisApp.programmingExercise.submissionPolicy.submissionLimitWarning' + '.' + e.key"></div>
</div>
</ng-container>
</ng-container>
</div>
<div class="col">
<ng-container *ngIf="this.isSubmissionPenaltyPolicy">
<label
class="label-narrow"
jhiTranslate="artemisApp.programmingExercise.submissionPolicy.submissionPenalty.penaltyInputFieldTitle"
for="field_submissionLimitExceededPenalty"
>Penalty after Exceeding Submission Limit</label
>
<jhi-help-icon placement="top" text="artemisApp.programmingExercise.submissionPolicy.submissionPenalty.exceedingLimitDescription"></jhi-help-icon>
<div class="input-group">
<input
required
type="number"
class="form-control"
formControlName="exceedingPenalty"
name="submissionLimitExceededPenalty"
id="field_submissionLimitExceededPenalty"
(input)="updateExceedingPenalty()"
/>
</div>
<ng-container *ngFor="let e of exceedingPenaltyControl.errors! | keyvalue">
<div *ngIf="exceedingPenaltyControl.invalid && (exceedingPenaltyControl.dirty || exceedingPenaltyControl.touched)" class="alert alert-danger">
<div [jhiTranslate]="'artemisApp.programmingExercise.submissionPolicy.submissionPenalty.penaltyInputFieldValidationWarning' + '.' + e.key"></div>
</div>
</ng-container>
</ng-container>
</div>
</div>
</form>
`,
styleUrls: ['../../programming/manage/programming-exercise-form.scss'],
})
export class SubmissionPolicyUpdateComponent implements OnInit {
@Input() programmingExercise: ProgrammingExercise;
@Input() editable: boolean;
form: FormGroup;
selectedSubmissionPolicyType: SubmissionPolicyType;
isSubmissionPenaltyPolicy: boolean;
isLockRepositoryPolicy: boolean;
isNonePolicy: boolean;
// This is used to ensure that only integers [1-500] can be used as input for the submission limit.
submissionLimitPattern = '^([1-9]|([1-9][0-9])|([1-4][0-9][0-9])|500)$';
submissionLimitControl: FormControl;
exceedingPenaltyControl: FormControl;
// penalty can be any (point) number greater than 0
exceedingPenaltyPattern = RegExp('^0*[1-9][0-9]*(\\.[0-9]+)?|0+\\.[0-9]*[1-9][0-9]*$');
ngOnInit(): void {
this.onSubmissionPolicyTypeChanged(this.programmingExercise.submissionPolicy?.type ?? SubmissionPolicyType.NONE);
this.form = new FormGroup({
submissionLimit: new FormControl({ value: this.programmingExercise.submissionPolicy?.submissionLimit, disabled: !this.editable }, [
Validators.pattern(this.submissionLimitPattern),
Validators.required,
]),
exceedingPenalty: new FormControl({ value: this.programmingExercise.submissionPolicy?.exceedingPenalty, disabled: !this.editable }, [
Validators.pattern(this.exceedingPenaltyPattern),
Validators.required,
]),
});
this.submissionLimitControl = this.form.get('submissionLimit')! as FormControl;
this.exceedingPenaltyControl = this.form.get('exceedingPenalty')! as FormControl;
}
private setAuxiliaryBooleansOnSubmissionPolicyChange(submissionPolicyType: SubmissionPolicyType) {
this.isNonePolicy = this.isLockRepositoryPolicy = this.isSubmissionPenaltyPolicy = false;
switch (submissionPolicyType) {
case SubmissionPolicyType.NONE:
this.isNonePolicy = true;
break;
case SubmissionPolicyType.LOCK_REPOSITORY:
this.isLockRepositoryPolicy = true;
break;
case SubmissionPolicyType.SUBMISSION_PENALTY:
this.isSubmissionPenaltyPolicy = true;
break;
}
this.selectedSubmissionPolicyType = submissionPolicyType;
}
onSubmissionPolicyTypeChanged(submissionPolicyType: SubmissionPolicyType) {
const previousSubmissionPolicyType = this.programmingExercise?.submissionPolicy?.type ?? SubmissionPolicyType.NONE;
if (submissionPolicyType === SubmissionPolicyType.NONE) {
if (previousSubmissionPolicyType !== SubmissionPolicyType.NONE) {
this.programmingExercise.submissionPolicy!.type = SubmissionPolicyType.NONE;
} else {
this.programmingExercise.submissionPolicy = undefined;
}
} else if (submissionPolicyType === SubmissionPolicyType.LOCK_REPOSITORY) {
const newPolicy = new LockRepositoryPolicy();
if (this.programmingExercise.submissionPolicy) {
newPolicy.id = this.programmingExercise.submissionPolicy.id;
newPolicy.active = this.programmingExercise.submissionPolicy.active;
newPolicy.submissionLimit = this.programmingExercise.submissionPolicy.submissionLimit;
}
this.programmingExercise.submissionPolicy = newPolicy;
} else if (submissionPolicyType === SubmissionPolicyType.SUBMISSION_PENALTY) {
const newPolicy = new SubmissionPenaltyPolicy();
if (this.programmingExercise.submissionPolicy) {
newPolicy.id = this.programmingExercise.submissionPolicy.id;
newPolicy.active = this.programmingExercise.submissionPolicy.active;
newPolicy.submissionLimit = this.programmingExercise.submissionPolicy!.submissionLimit;
if (this.programmingExercise.submissionPolicy?.exceedingPenalty) {
newPolicy.exceedingPenalty = this.programmingExercise.submissionPolicy?.exceedingPenalty;
} else if (this.exceedingPenaltyControl) {
// restore value when penalty has been set previously and was valid
if (this.exceedingPenaltyControl.invalid) {
this.exceedingPenaltyControl.setValue(undefined);
} else {
newPolicy.exceedingPenalty = this.exceedingPenaltyControl.value as number;
}
}
}
this.programmingExercise.submissionPolicy = newPolicy;
}
this.setAuxiliaryBooleansOnSubmissionPolicyChange(submissionPolicyType);
return submissionPolicyType!;
}
/**
* Returns whether the submission policy form is invalid.
*
* @returns {boolean} true if the form is invalid, false if the form is valid
*/
get invalid(): boolean {
const type = this.programmingExercise?.submissionPolicy?.type;
if (!this.form || !type || type === SubmissionPolicyType.NONE) {
return false;
}
return this.submissionLimitControl.invalid || (type === SubmissionPolicyType.SUBMISSION_PENALTY && this.exceedingPenaltyControl.invalid);
}
/**
* Ensures synchronization between the submission policy model and the input controller, since
* using ngModel with reactive forms has been deprecated in Angular v6
*/
updateSubmissionLimit() {
this.programmingExercise!.submissionPolicy!.submissionLimit = this.submissionLimitControl.value as number;
}
/**
* Ensures synchronization between the submission policy model and the input controller, since
* using ngModel with reactive forms has been deprecated in Angular v6
*/
updateExceedingPenalty() {
this.programmingExercise!.submissionPolicy!.exceedingPenalty = this.exceedingPenaltyControl.value as number;
}
} | the_stack |
import { getVoidLogger } from '@backstage/backend-common';
import {
Entity,
CompoundEntityRef,
DEFAULT_NAMESPACE,
} from '@backstage/catalog-model';
import { ConfigReader } from '@backstage/config';
import express from 'express';
import request from 'supertest';
import mockFs from 'mock-fs';
import fs from 'fs-extra';
import path from 'path';
import { OpenStackSwiftPublish } from './openStackSwift';
import { PublisherBase, TechDocsMetadata } from './types';
import { storageRootDir } from '../../testUtils/StorageFilesMock';
import { Stream, Readable } from 'stream';
jest.mock('@trendyol-js/openstack-swift-sdk', () => {
const {
ContainerMetaResponse,
DownloadResponse,
NotFound,
ObjectMetaResponse,
UploadResponse,
}: typeof import('@trendyol-js/openstack-swift-sdk') = jest.requireActual(
'@trendyol-js/openstack-swift-sdk',
);
const checkFileExists = async (Key: string): Promise<boolean> => {
// Key will always have / as file separator irrespective of OS since cloud providers expects /.
// Normalize Key to OS specific path before checking if file exists.
const filePath = path.join(storageRootDir, Key);
try {
await fs.access(filePath, fs.constants.F_OK);
return true;
} catch (err) {
return false;
}
};
const streamToBuffer = (stream: Stream | Readable): Promise<Buffer> => {
return new Promise((resolve, reject) => {
try {
const chunks: any[] = [];
stream.on('data', chunk => chunks.push(chunk));
stream.on('error', reject);
stream.on('end', () => resolve(Buffer.concat(chunks)));
} catch (e) {
throw new Error(`Unable to parse the response data ${e.message}`);
}
});
};
return {
__esModule: true,
SwiftClient: class {
async getMetadata(_containerName: string, file: string) {
const fileExists = await checkFileExists(file);
if (fileExists) {
return new ObjectMetaResponse({
fullPath: file,
});
}
return new NotFound();
}
async getContainerMetadata(containerName: string) {
if (containerName === 'mock') {
return new ContainerMetaResponse({
size: 10,
});
}
return new NotFound();
}
async upload(
_containerName: string,
destination: string,
stream: Readable,
) {
try {
const filePath = path.join(storageRootDir, destination);
const fileBuffer = await streamToBuffer(stream);
await fs.writeFile(filePath, fileBuffer);
const fileExists = await checkFileExists(destination);
if (fileExists) {
return new UploadResponse(filePath);
}
const errorMessage = `Unable to upload file(s) to OpenStack Swift.`;
throw new Error(errorMessage);
} catch (error) {
const errorMessage = `Unable to upload file(s) to OpenStack Swift. ${error}`;
throw new Error(errorMessage);
}
}
async download(_containerName: string, file: string) {
const filePath = path.join(storageRootDir, file);
const fileExists = await checkFileExists(file);
if (!fileExists) {
return new NotFound();
}
return new DownloadResponse([], fs.createReadStream(filePath));
}
},
};
});
const createMockEntity = (annotations = {}): Entity => {
return {
apiVersion: 'version',
kind: 'TestKind',
metadata: {
name: 'test-component-name',
namespace: 'test-namespace',
annotations: {
...annotations,
},
},
};
};
const createMockEntityName = (): CompoundEntityRef => ({
kind: 'TestKind',
name: 'test-component-name',
namespace: 'test-namespace',
});
const getEntityRootDir = (entity: Entity) => {
const {
kind,
metadata: { namespace, name },
} = entity;
return path.join(storageRootDir, namespace || DEFAULT_NAMESPACE, kind, name);
};
const getPosixEntityRootDir = (entity: Entity) => {
const {
kind,
metadata: { namespace, name },
} = entity;
return path.posix.join(
'/rootDir',
namespace || DEFAULT_NAMESPACE,
kind,
name,
);
};
const logger = getVoidLogger();
let publisher: PublisherBase;
beforeEach(() => {
mockFs.restore();
const mockConfig = new ConfigReader({
techdocs: {
publisher: {
type: 'openStackSwift',
openStackSwift: {
credentials: {
id: 'mockid',
secret: 'verystrongsecret',
},
authUrl: 'mockauthurl',
swiftUrl: 'mockSwiftUrl',
containerName: 'mock',
},
},
},
});
publisher = OpenStackSwiftPublish.fromConfig(mockConfig, logger);
});
describe('OpenStackSwiftPublish', () => {
describe('getReadiness', () => {
it('should validate correct config', async () => {
expect(await publisher.getReadiness()).toEqual({
isAvailable: true,
});
});
it('should reject incorrect config', async () => {
const mockConfig = new ConfigReader({
techdocs: {
publisher: {
type: 'openStackSwift',
openStackSwift: {
credentials: {
id: 'mockId',
secret: 'mockSecret',
},
authUrl: 'mockauthurl',
swiftUrl: 'mockSwiftUrl',
containerName: 'errorBucket',
},
},
},
});
const errorPublisher = OpenStackSwiftPublish.fromConfig(
mockConfig,
logger,
);
expect(await errorPublisher.getReadiness()).toEqual({
isAvailable: false,
});
});
});
describe('publish', () => {
beforeEach(() => {
const entity = createMockEntity();
const entityRootDir = getEntityRootDir(entity);
mockFs({
[entityRootDir]: {
'index.html': '',
'404.html': '',
assets: {
'main.css': '',
},
},
});
});
afterEach(() => {
mockFs.restore();
});
it('should publish a directory', async () => {
const entity = createMockEntity();
const entityRootDir = getEntityRootDir(entity);
expect(
await publisher.publish({
entity,
directory: entityRootDir,
}),
).toMatchObject({
objects: expect.arrayContaining([
'test-namespace/TestKind/test-component-name/404.html',
`test-namespace/TestKind/test-component-name/index.html`,
`test-namespace/TestKind/test-component-name/assets/main.css`,
]),
});
});
it('should fail to publish a directory', async () => {
const wrongPathToGeneratedDirectory = path.join(
storageRootDir,
'wrong',
'path',
'to',
'generatedDirectory',
);
const entity = createMockEntity();
await expect(
publisher.publish({
entity,
directory: wrongPathToGeneratedDirectory,
}),
).rejects.toThrowError();
const fails = publisher.publish({
entity,
directory: wrongPathToGeneratedDirectory,
});
// Can not do exact error message match due to mockFs adding unexpected characters in the path when throwing the error
// Issue reported https://github.com/tschaub/mock-fs/issues/118
await expect(fails).rejects.toMatchObject({
message: expect.stringContaining(
`Unable to upload file(s) to OpenStack Swift. Error: Failed to read template directory: ENOENT, no such file or directory`,
),
});
await expect(fails).rejects.toMatchObject({
message: expect.stringContaining(wrongPathToGeneratedDirectory),
});
mockFs.restore();
});
});
describe('hasDocsBeenGenerated', () => {
it('should return true if docs has been generated', async () => {
const entity = createMockEntity();
const entityRootDir = getEntityRootDir(entity);
mockFs({
[entityRootDir]: {
'index.html': 'file-content',
},
});
expect(await publisher.hasDocsBeenGenerated(entity)).toBe(true);
mockFs.restore();
});
it('should return false if docs has not been generated', async () => {
const entity = createMockEntity();
expect(await publisher.hasDocsBeenGenerated(entity)).toBe(false);
});
});
describe('fetchTechDocsMetadata', () => {
it('should return tech docs metadata', async () => {
const entityNameMock = createMockEntityName();
const entity = createMockEntity();
const entityRootDir = getEntityRootDir(entity);
mockFs({
[entityRootDir]: {
'techdocs_metadata.json':
'{"site_name": "backstage", "site_description": "site_content", "etag": "etag", "build_timestamp": 612741599}',
},
});
const expectedMetadata: TechDocsMetadata = {
site_name: 'backstage',
site_description: 'site_content',
etag: 'etag',
build_timestamp: 612741599,
};
expect(
await publisher.fetchTechDocsMetadata(entityNameMock),
).toStrictEqual(expectedMetadata);
mockFs.restore();
});
it('should return tech docs metadata when json encoded with single quotes', async () => {
const entityNameMock = createMockEntityName();
const entity = createMockEntity();
const entityRootDir = getEntityRootDir(entity);
mockFs({
[entityRootDir]: {
'techdocs_metadata.json': `{'site_name': 'backstage', 'site_description': 'site_content', 'etag': 'etag', 'build_timestamp': 612741599}`,
},
});
const expectedMetadata: TechDocsMetadata = {
site_name: 'backstage',
site_description: 'site_content',
etag: 'etag',
build_timestamp: 612741599,
};
expect(
await publisher.fetchTechDocsMetadata(entityNameMock),
).toStrictEqual(expectedMetadata);
mockFs.restore();
});
it('should return an error if the techdocs_metadata.json file is not present', async () => {
const entityNameMock = createMockEntityName();
const entity = createMockEntity();
const entityRootDir = getPosixEntityRootDir(entity);
const fails = publisher.fetchTechDocsMetadata(entityNameMock);
await expect(fails).rejects.toMatchObject({
message: `TechDocs metadata fetch failed, The file ${path.posix.join(
entityRootDir,
'techdocs_metadata.json',
)} does not exist !`,
});
});
});
describe('docsRouter', () => {
let app: express.Express;
const entity = createMockEntity();
const entityRootDir = getEntityRootDir(entity);
beforeEach(() => {
app = express().use(publisher.docsRouter());
mockFs.restore();
mockFs({
[entityRootDir]: {
html: {
'unsafe.html': '<html></html>',
},
img: {
'unsafe.svg': '<svg></svg>',
'with spaces.png': 'found it',
},
'some folder': {
'also with spaces.js': 'found it too',
},
},
});
});
afterEach(() => {
mockFs.restore();
});
it('should pass expected object path to bucket', async () => {
const {
kind,
metadata: { namespace, name },
} = entity;
// Ensures leading slash is trimmed and encoded path is decoded.
const pngResponse = await request(app).get(
`/${namespace}/${kind}/${name}/img/with%20spaces.png`,
);
expect(Buffer.from(pngResponse.body).toString('utf8')).toEqual(
'found it',
);
const jsResponse = await request(app).get(
`/${namespace}/${kind}/${name}/some%20folder/also%20with%20spaces.js`,
);
expect(jsResponse.text).toEqual('found it too');
});
it('should pass text/plain content-type for unsafe types', async () => {
const {
kind,
metadata: { namespace, name },
} = entity;
const htmlResponse = await request(app).get(
`/${namespace}/${kind}/${name}/html/unsafe.html`,
);
expect(htmlResponse.text).toEqual('<html></html>');
expect(htmlResponse.header).toMatchObject({
'content-type': 'text/plain; charset=utf-8',
});
const svgResponse = await request(app).get(
`/${namespace}/${kind}/${name}/img/unsafe.svg`,
);
expect(svgResponse.text).toEqual('<svg></svg>');
expect(svgResponse.header).toMatchObject({
'content-type': 'text/plain; charset=utf-8',
});
});
it('should return 404 if file is not found', async () => {
const {
kind,
metadata: { namespace, name },
} = entity;
const response = await request(app).get(
`/${namespace}/${kind}/${name}/not-found.html`,
);
expect(response.status).toBe(404);
expect(Buffer.from(response.text).toString('utf8')).toEqual(
'File Not Found',
);
});
});
}); | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="en_US">
<context>
<name>CompileWindow</name>
<message>
<location filename="../compilewindow.ui" line="14"/>
<source>Compile Script</source>
<translation></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="32"/>
<source><html><head/><body><p>Type (<a href="https://wiki.bablosoft.com/doku.php?id=how_to_protect_your_script"><span style=" text-decoration: underline; color:#eeeeee;">Manual</span></a>)</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="44"/>
<source>No protection</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="54"/>
<source>Private script, user must enter password before launch</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="61"/>
<source>Private script, enter password for user</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="70"/>
<source>Name</source>
<translation></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="84"/>
<source>Version</source>
<translation></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="148"/>
<source>Username</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="158"/>
<source>Password</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="168"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="175"/>
<source>Hide browsers. Only for premium users.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../compilewindow.ui" line="103"/>
<location filename="../compilewindow.ui" line="120"/>
<source>.</source>
<translation></translation>
</message>
<message>
<source>Script Name</source>
<translation type="vanished">Название скрипта</translation>
</message>
</context>
<context>
<name>DatabaseStateDialog</name>
<message>
<location filename="../databasestatedialog.ui" line="14"/>
<source>Database State</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="44"/>
<source>Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="55"/>
<source>WorkNotWorkButton</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="62"/>
<source>WorkNotWorkLabel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="75"/>
<source>EditDatabaseSchema</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="101"/>
<source>DeleteDatabase</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="116"/>
<source>Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="128"/>
<source>Data Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="155"/>
<source>Connection Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="174"/>
<source>Local (recomended)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="179"/>
<source>Remote</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="203"/>
<location filename="../databasestatedialog.ui" line="211"/>
<source>Database Id</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="224"/>
<source>Not Valid</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="236"/>
<source>Set this identifier to use one database in several projects</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="249"/>
<location filename="../databasestatedialog.ui" line="255"/>
<source>Database location</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="291"/>
<source>Relevance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="300"/>
<source>RelevanceRelevant</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="307"/>
<source>RelevanceRelevantLabel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="320"/>
<source>RestartProcess</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="343"/>
<source>Remote Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="351"/>
<source>Server</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="361"/>
<source>Port</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="371"/>
<source>Login</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="381"/>
<source>Password</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="393"/>
<source><html><head/><body><p><a href="https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/"><span style=" text-decoration: underline; color:#ffffff;">Install database on linux server</span></a></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="403"/>
<source><html><head/><body><p><a href="https://www.mkyong.com/mongodb/mongodb-allow-remote-access/"><span style=" text-decoration: underline; color:#ffffff;">Allow remote access to database</span></a></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="450"/>
<source>Save</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.ui" line="467"/>
<source>Close</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="130"/>
<source>Changes will take effect only after restart</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="132"/>
<location filename="../databasestatedialog.cpp" line="142"/>
<source>Restart process</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="141"/>
<source>No need to restart</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="181"/>
<source>Database works</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="182"/>
<source>Edit database schema</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="183"/>
<location filename="../databasestatedialog.cpp" line="194"/>
<source>Delete database</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="192"/>
<source>Database does not work</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="193"/>
<source>Create database</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="215"/>
<source>Restart</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="219"/>
<source>Changes will take effect only after restart.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../databasestatedialog.cpp" line="262"/>
<source>Are you sure, that you want to delete database?</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<source><html><head/><body><p><img src=":/studio/images/question.png"/> After script will launch, this section will contain list of browsers.</p></body></html></source>
<translation type="vanished"><html><head/><body><p><img src=":/studio/images/question.png"/> After script will launch, this section will contain list of browsers.</p></body></html></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="193"/>
<source>TextLabel</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="246"/>
<source>Project</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="250"/>
<source>Settings</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="274"/>
<source>Build</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="282"/>
<source>Help</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="289"/>
<source>Reports</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="322"/>
<source>toolBar</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="370"/>
<source>Data</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="507"/>
<source> + Create New Resource</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="563"/>
<source>Script</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="600"/>
<source>Log</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="646"/>
<source>Result</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="63"/>
<source><html><head/><body><p><img src=":/studio/images/question.png"/> Hit record button to create or edit script.</p></body></html></source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="123"/>
<location filename="../mainwindow.ui" line="866"/>
<source>Record</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="296"/>
<source>Tools</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="303"/>
<source>Interface</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="467"/>
<source><html><head/><body><p><img src=":/engine/images/question.png"/> Add all data, which script will use: files, text controls, database connection.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="677"/>
<source>New</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="680"/>
<source>Ctrl+N</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="689"/>
<source>Open</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="692"/>
<source>Ctrl+O</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="701"/>
<source>Save</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="704"/>
<source>Ctrl+S</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="709"/>
<source>Exit</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="712"/>
<source>Ctrl+Q</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="721"/>
<source>Compile</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="724"/>
<source>Ctrl+F5</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="733"/>
<source>Run</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="736"/>
<source>F5</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="745"/>
<location filename="../mainwindow.cpp" line="860"/>
<source>Stop</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="754"/>
<source>Save As</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="759"/>
<source>test</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="768"/>
<source>About Engine</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="773"/>
<source>About Qt</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="782"/>
<source>Documentation</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="791"/>
<source>Localization</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="800"/>
<source>Interface Language</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="809"/>
<source>Script Report</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="830"/>
<location filename="../mainwindow.ui" line="833"/>
<source>Resources Report</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="838"/>
<source>Show</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="847"/>
<location filename="../mainwindow.cpp" line="1875"/>
<source>Show Database</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="852"/>
<source>Edit Schema</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="857"/>
<source>Delete Schema</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="875"/>
<source>Module Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="884"/>
<source>Regular Expression Constructor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="893"/>
<source>Fingerprint Switcher</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="898"/>
<location filename="../mainwindow.ui" line="901"/>
<source>Restore Original</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.ui" line="818"/>
<source>Log Location Chooser</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="1845"/>
<source>All log</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="639"/>
<location filename="../mainwindow.cpp" line="962"/>
<source>Error saving file</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="639"/>
<location filename="../mainwindow.cpp" line="962"/>
<source>Error saving file : %1</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="680"/>
<source>Application is still running</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="680"/>
<source>Use exit menu item to shut it down</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="729"/>
<source>Open Project</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="729"/>
<location filename="../mainwindow.cpp" line="973"/>
<location filename="../mainwindow.cpp" line="992"/>
<source>Project Files (*.xml);;All Files (*.*)</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="763"/>
<source>Error loading file</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="763"/>
<source>Error loading file : %1</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="857"/>
<source>Stop instant</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="857"/>
<source>Wait each thread</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="860"/>
<source>Stop type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="973"/>
<source>Save Project</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="992"/>
<source>Create Project</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="1139"/>
<source>Captcha (%1)</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="1562"/>
<source>Running ...</source>
<translation></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="1846"/>
<source>Clear log</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="1877"/>
<source> (Need Restart)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../main.cpp" line="162"/>
<source>BrowserAutomationStudio is already running, do you want to start another instance?</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>RecentsWidget</name>
<message>
<location filename="../recentswidget.ui" line="14"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS> | the_stack |
import {
ContractTransaction,
ContractInterface,
BytesLike as Arrayish,
BigNumber,
BigNumberish,
} from 'ethers';
import { EthersContractContextV5 } from 'ethereum-abi-types-generator';
export type ContractContext = EthersContractContextV5<
Issue14Take2,
Issue14Take2MethodNames,
Issue14Take2EventsContext,
Issue14Take2Events
>;
export declare type EventFilter = {
address?: string;
topics?: Array<string>;
fromBlock?: string | number;
toBlock?: string | number;
};
export interface ContractTransactionOverrides {
/**
* The maximum units of gas for the transaction to use
*/
gasLimit?: number;
/**
* The price (in wei) per unit of gas
*/
gasPrice?: BigNumber | string | number | Promise<any>;
/**
* The nonce to use in the transaction
*/
nonce?: number;
/**
* The amount to send with the transaction (i.e. msg.value)
*/
value?: BigNumber | string | number | Promise<any>;
/**
* The chain ID (or network ID) to use
*/
chainId?: number;
}
export interface ContractCallOverrides {
/**
* The address to execute the call as
*/
from?: string;
/**
* The maximum units of gas for the transaction to use
*/
gasLimit?: number;
}
export type Issue14Take2Events = 'OwnershipTransferred' | 'Traveled';
export interface Issue14Take2EventsContext {
OwnershipTransferred(...parameters: any): EventFilter;
Traveled(...parameters: any): EventFilter;
}
export type Issue14Take2MethodNames =
| 'new'
| 'defaultRotationSpeed'
| 'feeReceiver'
| 'gateway'
| 'isModule'
| 'modules'
| 'mustManager'
| 'owner'
| 'portalStore'
| 'portalTravelArea'
| 'renounceOwnership'
| 'solarSystemStore'
| 'transferOwnership'
| 'updateModule'
| 'updateModules'
| 'updateSolarSystemStore'
| 'updatePortalStore'
| 'updateDefaultRotationSpeed'
| 'updatePortalTravelArea'
| 'updateMustManager'
| 'updateGateway'
| 'updateFeeReceiver'
| 'removePortal'
| 'getPortal'
| 'getPortals'
| 'getMinerLastDestination'
| 'getMinersLastDestination'
| 'addPortal'
| 'updatePortal'
| 'travel';
export interface CenterResponse {
x: BigNumber;
0: BigNumber;
y: BigNumber;
1: BigNumber;
}
export interface LastResponse {
distance: number;
0: number;
angle: BigNumber;
1: BigNumber;
}
export interface System1OrbitResponse {
center: CenterResponse;
0: System1OrbitResponse;
last: LastResponse;
1: System1OrbitResponse;
}
export interface System2OrbitResponse {
center: CenterResponse;
0: System2OrbitResponse;
last: LastResponse;
1: System2OrbitResponse;
}
export interface PortalResponse {
id: BigNumber;
0: BigNumber;
system1Id: BigNumber;
1: BigNumber;
system2Id: BigNumber;
2: BigNumber;
fees: BigNumber;
3: BigNumber;
system1Orbit: System1OrbitResponse;
4: System1OrbitResponse;
system2Orbit: System2OrbitResponse;
5: System2OrbitResponse;
}
export interface Issue14Take2 {
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: constructor
* @param pStore Type: address, Indexed: false
* @param ssStore Type: address, Indexed: false
* @param mManager Type: address, Indexed: false
* @param gtw Type: address, Indexed: false
*/
'new'(
pStore: string,
ssStore: string,
mManager: string,
gtw: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
defaultRotationSpeed(overrides?: ContractCallOverrides): Promise<number>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
feeReceiver(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
gateway(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param module Type: address, Indexed: false
*/
isModule(module: string, overrides?: ContractCallOverrides): Promise<boolean>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
modules(overrides?: ContractCallOverrides): Promise<string[]>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
mustManager(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
owner(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
portalStore(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
portalTravelArea(overrides?: ContractCallOverrides): Promise<number>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
*/
renounceOwnership(
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
solarSystemStore(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newOwner Type: address, Indexed: false
*/
transferOwnership(
newOwner: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newModule Type: address, Indexed: false
*/
updateModule(
newModule: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newModules Type: address[], Indexed: false
*/
updateModules(
newModules: string[],
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newStore Type: address, Indexed: false
*/
updateSolarSystemStore(
newStore: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newStore Type: address, Indexed: false
*/
updatePortalStore(
newStore: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param speed Type: int32, Indexed: false
*/
updateDefaultRotationSpeed(
speed: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param area Type: uint8, Indexed: false
*/
updatePortalTravelArea(
area: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newMustManager Type: address, Indexed: false
*/
updateMustManager(
newMustManager: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newGateway Type: address, Indexed: false
*/
updateGateway(
newGateway: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param newFeeReceiver Type: address, Indexed: false
*/
updateFeeReceiver(
newFeeReceiver: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param portalId Type: uint256, Indexed: false
*/
removePortal(
portalId: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param portalId Type: uint256, Indexed: false
*/
getPortal(
portalId: BigNumberish,
overrides?: ContractCallOverrides
): Promise<PortalResponse>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
*/
getPortals(overrides?: ContractCallOverrides): Promise<PortalResponse[]>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param minerId Type: uint256, Indexed: false
*/
getMinerLastDestination(
minerId: BigNumberish,
overrides?: ContractCallOverrides
): Promise<BigNumber>;
/**
* Payable: false
* Constant: true
* StateMutability: view
* Type: function
* @param minerIds Type: uint256[], Indexed: false
*/
getMinersLastDestination(
minerIds: BigNumberish[],
overrides?: ContractCallOverrides
): Promise<BigNumber[]>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param system1Id Type: uint256, Indexed: false
* @param system2Id Type: uint256, Indexed: false
* @param fees Type: uint256, Indexed: false
* @param system1DistanceToCenter Type: uint32, Indexed: false
* @param system2DistanceToCenter Type: uint32, Indexed: false
* @param system1Angle Type: int128, Indexed: false
* @param system2Angle Type: int128, Indexed: false
* @param rotationSpeed Type: int32, Indexed: false
*/
addPortal(
system1Id: BigNumberish,
system2Id: BigNumberish,
fees: BigNumberish,
system1DistanceToCenter: BigNumberish,
system2DistanceToCenter: BigNumberish,
system1Angle: BigNumberish,
system2Angle: BigNumberish,
rotationSpeed: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param portalId Type: uint256, Indexed: false
* @param system1Id Type: uint256, Indexed: false
* @param system2Id Type: uint256, Indexed: false
* @param fees Type: uint256, Indexed: false
* @param system1DistanceToCenter Type: uint32, Indexed: false
* @param system2DistanceToCenter Type: uint32, Indexed: false
* @param system1Angle Type: int128, Indexed: false
* @param system2Angle Type: int128, Indexed: false
* @param rotationSpeed Type: int32, Indexed: false
*/
updatePortal(
portalId: BigNumberish,
system1Id: BigNumberish,
system2Id: BigNumberish,
fees: BigNumberish,
system1DistanceToCenter: BigNumberish,
system2DistanceToCenter: BigNumberish,
system1Angle: BigNumberish,
system2Angle: BigNumberish,
rotationSpeed: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: nonpayable
* Type: function
* @param minerId Type: uint256, Indexed: false
* @param portalId Type: uint256, Indexed: false
* @param fromSystemId Type: uint256, Indexed: false
* @param toSystemId Type: uint256, Indexed: false
* @param time Type: uint256, Indexed: false
*/
travel(
minerId: BigNumberish,
portalId: BigNumberish,
fromSystemId: BigNumberish,
toSystemId: BigNumberish,
time: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
} | the_stack |
import { PageActionPartial } from "./actions";
import {
DELETE_CONTENT,
DeleteContentAction,
INSERT_CONTENT,
InsertContentAction,
REPLACE_CONTENT,
ReplaceContentAction,
} from "./contentTree/actions";
import { SENTINEL_CONTENT } from "./contentTree/tree";
import { Color, PageContent, StatePages } from "./pageModel";
import pageReducer from "./reducer";
import { SENTINEL_STRUCTURE } from "./structureTree/tree";
import { SENTINEL_INDEX } from "./tree/tree";
import { TagType } from "./structureTree/structureModel";
import { deleteStructure } from "./structureTree/actions";
export const getStartPage = (): PageContent => ({
buffers: [
{
content:
"Do not go gentle into that good night,\nOld age should burn and rave at close of shop;\n" +
"Todo: Add the end of this stanza",
isReadOnly: true,
lineStarts: [0, 39, 86],
},
{
content: "vdayRave, rave against the dying of the lightgg.",
isReadOnly: false,
lineStarts: [0],
},
],
content: {
nodes: [
SENTINEL_CONTENT,
{
// 1
bufferIndex: 0,
color: Color.Red,
end: { column: 26, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 65,
lineFeedCount: 1,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 0, line: 0 },
},
{
// 2
bufferIndex: 1,
color: Color.Black,
end: { column: 1, line: 0 },
left: 1,
leftCharCount: 65,
leftLineFeedCount: 1,
length: 1,
lineFeedCount: 0,
parent: 4,
right: 3,
start: { column: 0, line: 0 },
},
{
// 3
bufferIndex: 0,
color: Color.Red,
end: { column: 41, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 14,
lineFeedCount: 0,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 27, line: 1 },
},
{
// 4
bufferIndex: 1,
color: Color.Red,
end: { column: 4, line: 0 },
left: 2,
leftCharCount: 80,
leftLineFeedCount: 1,
length: 3,
lineFeedCount: 0,
parent: 6,
right: 5,
start: { column: 1, line: 0 },
},
{
// 5
bufferIndex: 0,
color: Color.Black,
end: { column: 47, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 2,
lineFeedCount: 1,
parent: 4,
right: SENTINEL_INDEX,
start: { column: 45, line: 1 },
},
{
// 6
bufferIndex: 1,
color: Color.Black,
end: { column: 6, line: 0 },
left: 4,
leftCharCount: 85,
leftLineFeedCount: 2,
length: 2,
lineFeedCount: 0,
parent: SENTINEL_INDEX,
right: 8,
start: { column: 4, line: 0 },
},
{
// 7
bufferIndex: 1,
color: Color.Black,
end: { column: 46, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 8,
right: SENTINEL_INDEX,
start: { column: 45, line: 0 },
},
{
// 8
bufferIndex: 1,
color: Color.Red,
end: { column: 12, line: 0 },
left: 7,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 5,
lineFeedCount: 0,
parent: 6,
right: 10,
start: { column: 7, line: 0 },
},
{
// 9
bufferIndex: 1,
color: Color.Red,
end: { column: 47, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 10,
right: SENTINEL_INDEX,
start: { column: 46, line: 0 },
},
{
// 10
bufferIndex: 1,
color: Color.Black,
end: { column: 45, line: 0 },
left: 9,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 32,
lineFeedCount: 0,
parent: 8,
right: 11,
start: { column: 13, line: 0 },
},
{
// 11
bufferIndex: 1,
color: Color.Red,
end: { column: 48, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 10,
right: SENTINEL_INDEX,
start: { column: 47, line: 0 },
},
],
root: 6,
},
previouslyInsertedContentNodeIndex: null,
previouslyInsertedContentNodeOffset: null,
structure: { nodes: [SENTINEL_STRUCTURE], root: SENTINEL_INDEX },
});
const PAGE_ID = "pageId";
describe("page/reducer", (): void => {
const getState = (): StatePages => {
const state: StatePages = {
[PAGE_ID]: getStartPage(),
};
return state;
};
test("Invalid action types returns the state with no changes", (): void => {
const action: PageActionPartial = { pageId: "", type: "HELLO_WORLD" };
const state = getState();
expect(pageReducer(state, action)).toBe(state);
expect(pageReducer(state, action)).toStrictEqual(state);
});
test("Invalid page id", (): void => {
const action: PageActionPartial = { pageId: "", type: INSERT_CONTENT };
const state = getState();
expect(pageReducer(state, action)).toBe(state);
expect(pageReducer(state, action)).toStrictEqual(state);
});
test("Insertion", (): void => {
const action: InsertContentAction = {
content: "Hello world",
globalOffset: 127,
nodeIndex: SENTINEL_INDEX,
pageId: PAGE_ID,
type: INSERT_CONTENT,
};
const expectedPage: PageContent = {
buffers: [
{
content:
"Do not go gentle into that good night,\nOld age should burn and rave at close of shop;\n" +
"Todo: Add the end of this stanza",
isReadOnly: true,
lineStarts: [0, 39, 86],
},
{
content:
"vdayRave, rave against the dying of the lightgg.Hello world",
isReadOnly: false,
lineStarts: [0],
},
],
content: {
nodes: [
SENTINEL_CONTENT,
{
// 1
bufferIndex: 0,
color: Color.Red,
end: { column: 26, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 65,
lineFeedCount: 1,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 0, line: 0 },
},
{
// 2
bufferIndex: 1,
color: Color.Black,
end: { column: 1, line: 0 },
left: 1,
leftCharCount: 65,
leftLineFeedCount: 1,
length: 1,
lineFeedCount: 0,
parent: 4,
right: 3,
start: { column: 0, line: 0 },
},
{
// 3
bufferIndex: 0,
color: Color.Red,
end: { column: 41, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 14,
lineFeedCount: 0,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 27, line: 1 },
},
{
// 4
bufferIndex: 1,
color: Color.Black,
end: { column: 4, line: 0 },
left: 2,
leftCharCount: 80,
leftLineFeedCount: 1,
length: 3,
lineFeedCount: 0,
parent: 6,
right: 5,
start: { column: 1, line: 0 },
},
{
// 5
bufferIndex: 0,
color: Color.Black,
end: { column: 47, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 2,
lineFeedCount: 1,
parent: 4,
right: SENTINEL_INDEX,
start: { column: 45, line: 1 },
},
{
// 6
bufferIndex: 1,
color: Color.Black,
end: { column: 6, line: 0 },
left: 4,
leftCharCount: 85,
leftLineFeedCount: 2,
length: 2,
lineFeedCount: 0,
parent: SENTINEL_INDEX,
right: 8,
start: { column: 4, line: 0 },
},
{
// 7
bufferIndex: 1,
color: Color.Black,
end: { column: 46, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 8,
right: SENTINEL_INDEX,
start: { column: 45, line: 0 },
},
{
// 8
bufferIndex: 1,
color: Color.Black,
end: { column: 12, line: 0 },
left: 7,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 5,
lineFeedCount: 0,
parent: 6,
right: 10,
start: { column: 7, line: 0 },
},
{
// 9
bufferIndex: 1,
color: Color.Black,
end: { column: 47, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 10,
right: SENTINEL_INDEX,
start: { column: 46, line: 0 },
},
{
// 10
bufferIndex: 1,
color: Color.Red,
end: { column: 45, line: 0 },
left: 9,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 32,
lineFeedCount: 0,
parent: 8,
right: 11,
start: { column: 13, line: 0 },
},
{
// 11
bufferIndex: 1,
color: Color.Black,
end: { column: 48, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 10,
right: 12,
start: { column: 47, line: 0 },
},
{
// 12
bufferIndex: 1,
color: Color.Red,
end: { column: 59, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 11,
lineFeedCount: 0,
parent: 11,
right: SENTINEL_INDEX,
start: { column: 48, line: 0 },
},
],
root: 6,
},
previouslyInsertedContentNodeIndex: 12,
previouslyInsertedContentNodeOffset: 127,
structure: { nodes: [SENTINEL_STRUCTURE], root: SENTINEL_INDEX },
};
const state = getState();
const result = pageReducer(state, action);
const expectedState: StatePages = {
...state,
[PAGE_ID]: expectedPage,
};
expect(result).toStrictEqual(expectedState);
expect(result).not.toBe(state);
});
test("Deletion", (): void => {
const action: DeleteContentAction = {
contentLocations: {
end: {
contentOffset: 127,
structureNodeIndex: SENTINEL_INDEX,
},
start: {
contentOffset: 126,
structureNodeIndex: SENTINEL_INDEX,
},
},
pageId: PAGE_ID,
type: DELETE_CONTENT,
};
const state = getState();
const result = pageReducer(state, action);
const expectedPage: PageContent = {
buffers: [
{
content:
"Do not go gentle into that good night,\nOld age should burn and rave at close of shop;\n" +
"Todo: Add the end of this stanza",
isReadOnly: true,
lineStarts: [0, 39, 86],
},
{
content: "vdayRave, rave against the dying of the lightgg.",
isReadOnly: false,
lineStarts: [0],
},
],
content: {
nodes: [
SENTINEL_CONTENT,
{
// 1
bufferIndex: 0,
color: Color.Red,
end: { column: 26, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 65,
lineFeedCount: 1,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 0, line: 0 },
},
{
// 2
bufferIndex: 1,
color: Color.Black,
end: { column: 1, line: 0 },
left: 1,
leftCharCount: 65,
leftLineFeedCount: 1,
length: 1,
lineFeedCount: 0,
parent: 4,
right: 3,
start: { column: 0, line: 0 },
},
{
// 3
bufferIndex: 0,
color: Color.Red,
end: { column: 41, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 14,
lineFeedCount: 0,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 27, line: 1 },
},
{
// 4
bufferIndex: 1,
color: Color.Red,
end: { column: 4, line: 0 },
left: 2,
leftCharCount: 80,
leftLineFeedCount: 1,
length: 3,
lineFeedCount: 0,
parent: 6,
right: 5,
start: { column: 1, line: 0 },
},
{
// 5
bufferIndex: 0,
color: Color.Black,
end: { column: 47, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 2,
lineFeedCount: 1,
parent: 4,
right: SENTINEL_INDEX,
start: { column: 45, line: 1 },
},
{
// 6
bufferIndex: 1,
color: Color.Black,
end: { column: 6, line: 0 },
left: 4,
leftCharCount: 85,
leftLineFeedCount: 2,
length: 2,
lineFeedCount: 0,
parent: SENTINEL_INDEX,
right: 8,
start: { column: 4, line: 0 },
},
{
// 7
bufferIndex: 1,
color: Color.Black,
end: { column: 46, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 8,
right: SENTINEL_INDEX,
start: { column: 45, line: 0 },
},
{
// 8
bufferIndex: 1,
color: Color.Red,
end: { column: 12, line: 0 },
left: 7,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 5,
lineFeedCount: 0,
parent: 6,
right: 10,
start: { column: 7, line: 0 },
},
{
// 9
bufferIndex: 1,
color: Color.Red,
end: { column: 47, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 10,
right: SENTINEL_INDEX,
start: { column: 46, line: 0 },
},
{
// 10
bufferIndex: 1,
color: Color.Black,
end: { column: 45, line: 0 },
left: 9,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 32,
lineFeedCount: 0,
parent: 8,
right: SENTINEL_INDEX,
start: { column: 13, line: 0 },
},
{
// 11
bufferIndex: 1,
color: Color.Black,
end: { column: 48, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: SENTINEL_INDEX,
right: SENTINEL_INDEX,
start: { column: 47, line: 0 },
},
],
root: 6,
},
previouslyInsertedContentNodeIndex: null,
previouslyInsertedContentNodeOffset: null,
structure: { nodes: [SENTINEL_STRUCTURE], root: SENTINEL_INDEX },
};
const expectedState: StatePages = {
...state,
[PAGE_ID]: expectedPage,
};
expect(result).toStrictEqual(expectedState);
expect(result).not.toBe(state);
});
test("Replacement", (): void => {
const action: ReplaceContentAction = {
content: "Hello world",
contentLocations: {
end: {
contentOffset: 127,
structureNodeIndex: SENTINEL_INDEX,
},
start: {
contentOffset: 126,
structureNodeIndex: SENTINEL_INDEX,
},
},
pageId: PAGE_ID,
type: REPLACE_CONTENT,
};
const state = getState();
const result = pageReducer(state, action);
const expectedPage: PageContent = {
buffers: [
{
content:
"Do not go gentle into that good night,\nOld age should burn and rave at close of shop;\n" +
"Todo: Add the end of this stanza",
isReadOnly: true,
lineStarts: [0, 39, 86],
},
{
content:
"vdayRave, rave against the dying of the lightgg.Hello world",
isReadOnly: false,
lineStarts: [0],
},
],
content: {
nodes: [
SENTINEL_CONTENT,
{
// 1
bufferIndex: 0,
color: Color.Red,
end: { column: 26, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 65,
lineFeedCount: 1,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 0, line: 0 },
},
{
// 2
bufferIndex: 1,
color: Color.Black,
end: { column: 1, line: 0 },
left: 1,
leftCharCount: 65,
leftLineFeedCount: 1,
length: 1,
lineFeedCount: 0,
parent: 4,
right: 3,
start: { column: 0, line: 0 },
},
{
// 3
bufferIndex: 0,
color: Color.Red,
end: { column: 41, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 14,
lineFeedCount: 0,
parent: 2,
right: SENTINEL_INDEX,
start: { column: 27, line: 1 },
},
{
// 4
bufferIndex: 1,
color: Color.Red,
end: { column: 4, line: 0 },
left: 2,
leftCharCount: 80,
leftLineFeedCount: 1,
length: 3,
lineFeedCount: 0,
parent: 6,
right: 5,
start: { column: 1, line: 0 },
},
{
// 5
bufferIndex: 0,
color: Color.Black,
end: { column: 47, line: 1 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 2,
lineFeedCount: 1,
parent: 4,
right: SENTINEL_INDEX,
start: { column: 45, line: 1 },
},
{
// 6
bufferIndex: 1,
color: Color.Black,
end: { column: 6, line: 0 },
left: 4,
leftCharCount: 85,
leftLineFeedCount: 2,
length: 2,
lineFeedCount: 0,
parent: SENTINEL_INDEX,
right: 8,
start: { column: 4, line: 0 },
},
{
// 7
bufferIndex: 1,
color: Color.Black,
end: { column: 46, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 8,
right: SENTINEL_INDEX,
start: { column: 45, line: 0 },
},
{
// 8
bufferIndex: 1,
color: Color.Red,
end: { column: 12, line: 0 },
left: 7,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 5,
lineFeedCount: 0,
parent: 6,
right: 10,
start: { column: 7, line: 0 },
},
{
// 9
bufferIndex: 1,
color: Color.Red,
end: { column: 47, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: 10,
right: SENTINEL_INDEX,
start: { column: 46, line: 0 },
},
{
// 10
bufferIndex: 1,
color: Color.Black,
end: { column: 45, line: 0 },
left: 9,
leftCharCount: 1,
leftLineFeedCount: 0,
length: 32,
lineFeedCount: 0,
parent: 8,
right: 12,
start: { column: 13, line: 0 },
},
{
// 11
bufferIndex: 1,
color: Color.Black,
end: { column: 48, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 1,
lineFeedCount: 0,
parent: SENTINEL_INDEX,
right: SENTINEL_INDEX,
start: { column: 47, line: 0 },
},
{
// 12
bufferIndex: 1,
color: Color.Red,
end: { column: 59, line: 0 },
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: 11,
lineFeedCount: 0,
parent: 10,
right: SENTINEL_INDEX,
start: { column: 48, line: 0 },
},
],
root: 6,
},
previouslyInsertedContentNodeIndex: 12,
previouslyInsertedContentNodeOffset: 126,
structure: { nodes: [SENTINEL_STRUCTURE], root: SENTINEL_INDEX },
};
const expectedState: StatePages = {
...state,
[PAGE_ID]: expectedPage,
};
expect(result).toStrictEqual(expectedState);
expect(result).not.toBe(state);
});
test("Delete structure node", (): void => {
const page: PageContent = {
buffers: [],
content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX },
previouslyInsertedContentNodeIndex: null,
previouslyInsertedContentNodeOffset: null,
structure: {
nodes: [
SENTINEL_STRUCTURE,
{
// 1
color: Color.Black,
id: "helloWorld",
left: SENTINEL_INDEX,
leftSubTreeLength: 0,
length: 0,
parent: SENTINEL_INDEX,
right: SENTINEL_INDEX,
tag: "p",
tagType: TagType.StartEndTag,
},
],
root: 1,
},
};
const state: StatePages = {
pageId: page,
};
const expectedPage: PageContent = {
buffers: [],
content: { nodes: [SENTINEL_CONTENT], root: SENTINEL_INDEX },
previouslyInsertedContentNodeIndex: null,
previouslyInsertedContentNodeOffset: null,
structure: {
nodes: [
SENTINEL_STRUCTURE,
{
// 1
color: Color.Black,
id: "helloWorld",
left: SENTINEL_INDEX,
leftSubTreeLength: 0,
length: 0,
parent: SENTINEL_INDEX,
right: SENTINEL_INDEX,
tag: "p",
tagType: TagType.StartEndTag,
},
],
root: SENTINEL_INDEX,
},
};
const expectedState: StatePages = {
pageId: expectedPage,
};
const action = deleteStructure("pageId", 1);
const result = pageReducer(state, action);
expect(result).toStrictEqual(expectedState);
});
}); | the_stack |
import { NestedFormData } from '../../../src/components/form';
import * as form from '../../../src/containers/SidePanel/OptionsPanel/constants';
import { SampleData } from '../../../src/containers/ImportWizardModal/SampleData';
import {
GraphSelectors,
ColorFixed,
ColorLegend,
EdgeStyleOptions,
EdgeWidthFixed,
EdgeWidthProperty,
Edge,
} from '../../../src/redux/graph';
import { EdgePattern, mapEdgePattern } from '../../../src/utils/shape-utils';
import { DEFAULT_EDGE_STYLE } from '../../../src/constants/graph-shapes';
describe('Edge Style Filter', () => {
const graphinEl = 'Graphin2';
const findDefaultFromForm = (
form: NestedFormData,
layout: string,
controllerName: string,
) => {
return form[layout].find((value: any) => value.id === controllerName);
};
const getEdgeStyleFromReduxStore = (): Promise<EdgeStyleOptions> => {
return new Promise((resolve) => {
cy.getReact('Provider$1')
.getProps('store')
.then((store) => {
const globalStore = store.getState();
const { edgeStyle } = GraphSelectors.getGraph(
globalStore,
).styleOptions;
return resolve(edgeStyle);
});
});
};
before(() => {
cy.visit('/');
cy.waitForReact(5000);
cy.switchTab('sample-data');
cy.importSampleData(SampleData.BANK);
cy.switchPanel('options');
cy.switchTab('edges');
});
describe('Edge Width', () => {
const changeWidthType = (type: string) => {
cy.react('Controller', { props: { name: 'width' } }).type(
`${type}{enter}`,
);
};
const changeWidthVariable = (variable: string) => {
cy.react('Controller', { props: { name: 'variable' } })
.nthNode(1)
.type(`${variable}{enter}`);
};
it('should be fixed with specific line width', async () => {
changeWidthType('fixed');
const modifyValue = 1;
const arrows = '{rightarrow}'.repeat(modifyValue);
const edgeSizeType = 'fixed';
const controllerName = 'value';
cy.react('OptionsEdgeStyles')
.react('NestedForm')
.react('Controller', { props: { name: controllerName } })
.nthNode(2)
.type(arrows);
const { min, max } = findDefaultFromForm(
form.edgeWidthForm,
edgeSizeType,
controllerName,
);
const edgeStyle = await getEdgeStyleFromReduxStore();
const { id, value } = edgeStyle.width as EdgeWidthFixed;
expect(id).to.deep.equal(edgeSizeType);
expect(value).to.deep.equal((min + max) / 2 + 0.1);
});
it('should adjust with property (user defined)', async () => {
const edgeSizeType = 'property';
const selectedVariable = 'amount';
const controllerName = 'range';
changeWidthType('Property');
changeWidthVariable(selectedVariable);
const { value } = findDefaultFromForm(
form.edgeWidthForm,
edgeSizeType,
controllerName,
);
const edgeStyle = await getEdgeStyleFromReduxStore();
const { id, range, variable } = edgeStyle.width as EdgeWidthProperty;
expect(id).to.deep.equal(edgeSizeType);
expect(variable).to.deep.equal(selectedVariable);
expect(range).to.deep.equal(value);
});
});
describe('Edge Label', () => {
const changeLabelField = (value: string) => {
cy.react('Controller', { props: { name: 'label' } })
.first()
.type(`${value}{enter}`);
};
it('should display label when selected', async () => {
const selectedLabelField = 'id';
changeLabelField(selectedLabelField);
const edgeStyle = await getEdgeStyleFromReduxStore();
const edgeLabel: string | string[] = edgeStyle.label;
expect(edgeLabel).to.deep.equal(selectedLabelField);
});
it('should handle multiple selections', async () => {
const selectedLabelField = 'is_foreign_target';
changeLabelField(selectedLabelField);
const expectedLabel = ['id', 'is_foreign_target']
const edgeStyle = await getEdgeStyleFromReduxStore();
const edgeLabel: string | string[] = edgeStyle.label;
expect(edgeLabel).to.deep.equal(expectedLabel);
});
});
describe('Edge Colours', () => {
const controllerName = 'color';
before(() => {
cy.visit('/');
cy.waitForReact(5000);
cy.switchTab('sample-data');
cy.importSampleData(SampleData.BANK);
cy.switchPanel('options');
cy.switchTab('edges');
});
const changeColorType = (value: string) => {
cy.react('Controller', { props: { name: controllerName } })
.first()
.type(`${value}{enter}`);
};
const changeColorValue = (value: string) => {
cy.react('Controller', { props: { name: 'value' } })
.nthNode(1)
.type(`${value}{enter}`);
};
const changeColorVariable = (value: string) => {
cy.react('Controller', { props: { name: 'variable' } }).type(
`${value}{enter}`,
);
};
describe('should change with fixed edge color', () => {
const selectedType: string = 'fixed';
const assertEdgeColour = async (selectedColor: string) => {
changeColorValue(selectedColor);
const edgeStyle: EdgeStyleOptions = await getEdgeStyleFromReduxStore();
const { id, value } = edgeStyle.color as ColorFixed;
expect(id).to.deep.equal(selectedType);
expect(value).to.deep.equal(selectedColor);
};
it('should change to blue', async () => {
cy.wait(5000)
changeColorType(selectedType);
await assertEdgeColour('blue');
});
});
describe('should change with legends', () => {
const selectedType: string = 'legend';
it('should display grey when variable is empty', async () => {
changeColorType(selectedType);
const edgeStyle: EdgeStyleOptions = await getEdgeStyleFromReduxStore();
const { id, variable, mapping } = edgeStyle.color as ColorLegend;
const { value } = findDefaultFromForm(
form.edgeColorForm,
selectedType,
'variable',
);
expect(id).to.deep.equal(selectedType);
expect(variable).to.deep.equal(value);
assert.isObject(mapping);
});
it('should display colours based on mapping', async () => {
changeColorType(selectedType);
const selectedVariable = 'id';
changeColorVariable(selectedVariable);
const edgeStyle: EdgeStyleOptions = await getEdgeStyleFromReduxStore();
const { id, variable, mapping } = edgeStyle.color as ColorLegend;
expect(id).to.deep.equal(selectedType);
expect(variable).to.deep.equal(selectedVariable);
assert.isObject(mapping);
});
});
});
describe('Edge Pattern', () => {
const changePatternField = (value: string) => {
cy.react('Controller', { props: { name: 'pattern' } }).type(
`${value}{enter}`,
);
};
const assertEdgePattern = async (pattern: EdgePattern): Promise<void> => {
const edgeStyle = await getEdgeStyleFromReduxStore();
const edgePattern: string = edgeStyle.pattern;
expect(edgePattern).to.deep.equal(pattern);
cy.getReact(graphinEl)
.getProps('data.edges.0')
.then((edge: Edge) => {
const { lineDash } = edge.style.keyshape;
expect(lineDash).to.deep.equal(mapEdgePattern(pattern));
});
};
it('should display Line when None', () => {
const selectedPatternField = 'none';
changePatternField(selectedPatternField);
// https://github.com/cylynx/motif.gl/pull/86
// setting default linewidth if there are no dropdown variables
cy.getReact(graphinEl)
.getProps('data.edges.0')
.then((edge: Edge) => {
const { lineWidth } = edge.style.keyshape;
expect(lineWidth).to.deep.equal(1);
});
});
it('should display Dot', () => {
const selectedPatternField = 'dot';
changePatternField(selectedPatternField);
assertEdgePattern(selectedPatternField);
});
it('should display Dash', () => {
const selectedPatternField = 'dash';
changePatternField(selectedPatternField);
assertEdgePattern(selectedPatternField);
});
it('should display Dash Dot', () => {
const selectedPatternField = 'dash-dot';
changePatternField(selectedPatternField);
assertEdgePattern(selectedPatternField);
});
});
describe('Edge Font Size', () => {
it('should change successfully', async () => {
const modifyValue = 1;
const arrow = '{rightarrow}'.repeat(modifyValue);
const { max, value } = form.edgeFontSizeForm;
cy.react('Controller', {
props: { name: 'fontSize', defaultValue: [value] },
})
.last()
.type(arrow);
const edgeStyle = await getEdgeStyleFromReduxStore();
const edgeLabelFontSize: number = edgeStyle.fontSize;
expect(edgeLabelFontSize).to.be.within(25, 27);
});
});
describe('Edge Arrow Options', () => {
const controllerName = 'arrow';
const changeArrow = (type: string) => {
cy.react('Controller', {
props: { name: controllerName },
})
.last()
.type(`${type}{enter}`);
};
const assertReduxValue = async (type: string) => {
const edgeStyle = await getEdgeStyleFromReduxStore();
const edgeArrow: string = edgeStyle.arrow;
expect(edgeArrow).to.deep.equal(type);
};
it('should hide arrow', async () => {
const selectedValue = 'none';
changeArrow(selectedValue);
await assertReduxValue(selectedValue);
cy.getReact(graphinEl)
.getProps('data.edges.0')
.then((edge: Edge) => {
const { endArrow } = edge.style.keyshape;
expect(endArrow).to.deep.equal({
d: -1 / 2,
path: `M 0,0 L 0,0 L 0,0 Z`,
});
});
});
it('should display arrow', async () => {
const selectedValue = 'display';
changeArrow(selectedValue);
await assertReduxValue(selectedValue);
cy.getReact(graphinEl)
.getProps('data.edges.0')
.then((edge: Edge) => {
const { endArrow } = edge.style.keyshape;
expect(endArrow).to.deep.equal(DEFAULT_EDGE_STYLE.keyshape.endArrow);
});
});
});
}); | the_stack |
import urlPath from '../util/url-path';
import crypto from 'crypto';
import BoxClient from '../box-client';
// -----------------------------------------------------------------------------
// Typedefs
// -----------------------------------------------------------------------------
/**
* A webhook trigger type constant
* @typedef {string} WebhookTriggerType
*/
enum WebhookTriggerType {
FILE_UPLOADED = 'FILE.UPLOADED',
FILE_PREVIEWED = 'FILE.PREVIEWED',
FILE_DOWNLOADED = 'FILE.DOWNLOADED',
FILE_TRASHED = 'FILE.TRASHED',
FILE_DELETED = 'FILE.DELETED',
FILE_RESTORED = 'FILE.RESTORED',
FILE_COPIED = 'FILE.COPIED',
FILE_MOVED = 'FILE.MOVED',
FILE_LOCKED = 'FILE.LOCKED',
FILE_UNLOCKED = 'FILE.UNLOCKED',
FILE_RENAMED = 'FILE.RENAMED',
COMMENT_CREATED = 'COMMENT.CREATED',
COMMENT_UPDATED = 'COMMENT.UPDATED',
COMMENT_DELETED = 'COMMENT.DELETED',
TASK_ASSIGNMENT_CREATED = 'TASK_ASSIGNMENT.CREATED',
TASK_ASSIGNMENT_UPDATED = 'TASK_ASSIGNMENT.UPDATED',
METADATA_INSTANCE_CREATED = 'METADATA_INSTANCE.CREATED',
METADATA_INSTANCE_UPDATED = 'METADATA_INSTANCE.UPDATED',
METADATA_INSTANCE_DELETED = 'METADATA_INSTANCE.DELETED',
FOLDER_CREATED = 'FOLDER.CREATED',
FOLDER_DOWNLOADED = 'FOLDER.DOWNLOADED',
FOLDER_RESTORED = 'FOLDER.RESTORED',
FOLDER_DELETED = 'FOLDER.DELETED',
FOLDER_COPIED = 'FOLDER.COPIED',
FOLDER_MOVED = 'FOLDER.MOVED',
FOLDER_TRASHED = 'FOLDER.TRASHED',
FOLDER_RENAMED = 'FOLDER.RENAMED',
WEBHOOK_DELETED = 'WEBHOOK.DELETED',
COLLABORATION_CREATED = 'COLLABORATION.CREATED',
COLLABORATION_ACCEPTED = 'COLLABORATION.ACCEPTED',
COLLABORATION_REJECTED = 'COLLABORATION.REJECTED',
COLLABORATION_REMOVED = 'COLLABORATION.REMOVED',
COLLABORATION_UPDATED = 'COLLABORATION.UPDATED',
SHARED_LINK_DELETED = 'SHARED_LINK.DELETED',
SHARED_LINK_CREATED = 'SHARED_LINK.CREATED',
SHARED_LINK_UPDATED = 'SHARED_LINK.UPDATED',
}
// -----------------------------------------------------------------------------
// Private
// -----------------------------------------------------------------------------
// Base path for all webhooks endpoints
const BASE_PATH = '/webhooks';
// This prevents replay attacks
const MAX_MESSAGE_AGE = 10 * 60; // 10 minutes
/**
* Compute the message signature
* @see {@Link https://developer.box.com/en/guides/webhooks/handle/setup-signatures/}
*
* @param {string} body - The request body of the webhook message
* @param {Object} headers - The request headers of the webhook message
* @param {?string} signatureKey - The signature to verify the message with
* @returns {?string} - The message signature (or null, if it can't be computed)
* @private
*/
function computeSignature(
body: string,
headers: Record<string, any>,
signatureKey?: string
) {
if (!signatureKey) {
return null;
}
if (headers['box-signature-version'] !== '1') {
return null;
}
if (headers['box-signature-algorithm'] !== 'HmacSHA256') {
return null;
}
let hmac = crypto.createHmac('sha256', signatureKey);
hmac.update(body);
hmac.update(headers['box-delivery-timestamp']);
const signature = hmac.digest('base64');
return signature;
}
/**
* Validate the message signature
* @see {@Link https://developer.box.com/en/guides/webhooks/handle/verify-signatures/}
*
* @param {string} body - The request body of the webhook message
* @param {Object} headers - The request headers of the webhook message
* @param {string} [primarySignatureKey] - The primary signature to verify the message with
* @param {string} [secondarySignatureKey] - The secondary signature to verify the message with
* @returns {boolean} - True or false
* @private
*/
function validateSignature(
body: string,
headers: Record<string, any>,
primarySignatureKey?: string,
secondarySignatureKey?: string
) {
// Either the primary or secondary signature must match the corresponding signature from Box
// (The use of two signatures allows the signing keys to be rotated one at a time)
const primarySignature = computeSignature(body, headers, primarySignatureKey);
if (
primarySignature &&
primarySignature === headers['box-signature-primary']
) {
return true;
}
const secondarySignature = computeSignature(
body,
headers,
secondarySignatureKey
);
if (
secondarySignature &&
secondarySignature === headers['box-signature-secondary']
) {
return true;
}
return false;
}
/**
* Validate that the delivery timestamp is not too far in the past (to prevent replay attacks)
*
* @param {Object} headers - The request headers of the webhook message
* @param {int} maxMessageAge - The maximum message age (in seconds)
* @returns {boolean} - True or false
* @private
*/
function validateDeliveryTimestamp(
headers: Record<string, any>,
maxMessageAge: number
) {
const deliveryTime = Date.parse(headers['box-delivery-timestamp']);
const currentTime = Date.now();
const messageAge = (currentTime - deliveryTime) / 1000;
if (messageAge > maxMessageAge) {
return false;
}
return true;
}
/**
* Stringify JSON with escaped multibyte Unicode characters to ensure computed signatures match PHP's default behavior
*
* @param {Object} body - The parsed JSON object
* @returns {string} - Stringified JSON with escaped multibyte Unicode characters
* @private
*/
function jsonStringifyWithEscapedUnicode(body: object) {
return JSON.stringify(body).replace(
/[\u007f-\uffff]/g,
(char) => `\\u${`0000${char.charCodeAt(0).toString(16)}`.slice(-4)}`
);
}
// -----------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------
/**
* Simple manager for interacting with all 'Webhooks' endpoints and actions.
*
* @param {BoxClient} client The Box API Client that is responsible for making calls to the API
* @constructor
*/
class Webhooks {
/**
* Primary signature key to protect webhooks against attacks.
* @static
* @type {?string}
*/
static primarySignatureKey: string | null = null;
/**
* Secondary signature key to protect webhooks against attacks.
* @static
* @type {?string}
*/
static secondarySignatureKey: string | null = null;
/**
* Sets primary and secondary signatures that are used to verify the Webhooks messages
*
* @param {string} primaryKey - The primary signature to verify the message with
* @param {string} [secondaryKey] - The secondary signature to verify the message with
* @returns {void}
*/
static setSignatureKeys(primaryKey: string, secondaryKey?: string) {
Webhooks.primarySignatureKey = primaryKey;
if (typeof secondaryKey === 'string') {
Webhooks.secondarySignatureKey = secondaryKey;
}
}
/**
* Validate a webhook message by verifying the signature and the delivery timestamp
*
* @param {string|Object} body - The request body of the webhook message
* @param {Object} headers - The request headers of the webhook message
* @param {string} [primaryKey] - The primary signature to verify the message with. If it is sent as a parameter,
it overrides the static variable primarySignatureKey
* @param {string} [secondaryKey] - The secondary signature to verify the message with. If it is sent as a parameter,
it overrides the static variable primarySignatureKey
* @param {int} [maxMessageAge] - The maximum message age (in seconds). Defaults to 10 minutes
* @returns {boolean} - True or false
*/
static validateMessage(
body: string | object,
headers: Record<string, string>,
primaryKey?: string,
secondaryKey?: string,
maxMessageAge?: number
) {
if (!primaryKey && Webhooks.primarySignatureKey) {
primaryKey = Webhooks.primarySignatureKey;
}
if (!secondaryKey && Webhooks.secondarySignatureKey) {
secondaryKey = Webhooks.secondarySignatureKey;
}
if (typeof maxMessageAge !== 'number') {
maxMessageAge = MAX_MESSAGE_AGE;
}
// For frameworks like Express that automatically parse JSON
// bodies into Objects, re-stringify for signature testing
if (typeof body === 'object') {
// Escape forward slashes to ensure a matching signature
body = jsonStringifyWithEscapedUnicode(body).replace(/\//g, '\\/');
}
if (!validateSignature(body, headers, primaryKey, secondaryKey)) {
return false;
}
if (!validateDeliveryTimestamp(headers, maxMessageAge)) {
return false;
}
return true;
}
client: BoxClient;
triggerTypes!: Record<
| 'FILE'
| 'COMMENT'
| 'TASK_ASSIGNMENT'
| 'METADATA_INSTANCE'
| 'FOLDER'
| 'WEBHOOK'
| 'COLLABORATION'
| 'SHARED_LINK',
Record<string, WebhookTriggerType>
>;
validateMessage!: typeof Webhooks.validateMessage;
constructor(client: BoxClient) {
// Attach the client, for making API calls
this.client = client;
}
/**
* Create a new webhook on a given Box object, specified by type and ID.
*
* API Endpoint: '/webhooks'
* Method: POST
*
* @param {string} targetID - Box ID of the item to create webhook on
* @param {ItemType} targetType - Type of item the webhook will be created on
* @param {string} notificationURL - The URL of your application where Box will notify you of events triggers
* @param {WebhookTriggerType[]} triggerTypes - Array of event types that trigger notification for the target
* @param {Function} [callback] - Passed the new webhook information if it was acquired successfully
* @returns {Promise<Object>} A promise resolving to the new webhook object
*/
create(
targetID: string,
targetType: string,
notificationURL: string,
triggerTypes: WebhookTriggerType[],
callback?: Function
) {
var params = {
body: {
target: {
id: targetID,
type: targetType,
},
address: notificationURL,
triggers: triggerTypes,
},
};
var apiPath = urlPath(BASE_PATH);
return this.client.wrapWithDefaultHandler(this.client.post)(
apiPath,
params,
callback
);
}
/**
* Returns a webhook object with the specified Webhook ID
*
* API Endpoint: '/webhooks/:webhookID'
* Method: GET
*
* @param {string} webhookID - ID of the webhook to retrieve
* @param {Object} [options] - Additional options for the request. Can be left null in most cases.
* @param {Function} [callback] - Passed the webhook information if it was acquired successfully
* @returns {Promise<Object>} A promise resolving to the webhook object
*/
get(webhookID: string, options?: Record<string, any>, callback?: Function) {
var params = {
qs: options,
};
var apiPath = urlPath(BASE_PATH, webhookID);
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Get a list of webhooks that are active for the current application and user.
*
* API Endpoint: '/webhooks'
* Method: GET
*
* @param {Object} [options] - Additional options for the request. Can be left null in most cases.
* @param {int} [options.limit=100] - The number of webhooks to return
* @param {string} [options.marker] - Pagination marker
* @param {Function} [callback] - Passed the list of webhooks if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the collection of webhooks
*/
getAll(
options?: {
limit?: number;
marker?: string;
},
callback?: Function
) {
var params = {
qs: options,
};
var apiPath = urlPath(BASE_PATH);
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Update a webhook
*
* API Endpoint: '/webhooks/:webhookID'
* Method: PUT
*
* @param {string} webhookID - The ID of the webhook to be updated
* @param {Object} updates - Webhook fields to update
* @param {string} [updates.address] - The new URL used by Box to send a notification when webhook is triggered
* @param {WebhookTriggerType[]} [updates.triggers] - The new events that triggers a notification
* @param {Function} [callback] - Passed the updated webhook information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the updated webhook object
*/
update(
webhookID: string,
updates?: {
address?: string;
triggers?: WebhookTriggerType[];
},
callback?: Function
) {
var apiPath = urlPath(BASE_PATH, webhookID),
params = {
body: updates,
};
return this.client.wrapWithDefaultHandler(this.client.put)(
apiPath,
params,
callback
);
}
/**
* Delete a specified webhook by ID
*
* API Endpoint: '/webhooks/:webhookID'
* Method: DELETE
*
* @param {string} webhookID - ID of webhook to be deleted
* @param {Function} [callback] - Empty response body passed if successful.
* @returns {Promise<void>} A promise resolving to nothing
*/
delete(webhookID: string, callback?: Function) {
var apiPath = urlPath(BASE_PATH, webhookID);
return this.client.wrapWithDefaultHandler(this.client.del)(
apiPath,
null,
callback
);
}
}
/**
* Enum of valid webhooks event triggers
*
* @readonly
* @enum {WebhookTriggerType}
*/
Webhooks.prototype.triggerTypes = {
FILE: {
UPLOADED: WebhookTriggerType.FILE_UPLOADED,
PREVIEWED: WebhookTriggerType.FILE_PREVIEWED,
DOWNLOADED: WebhookTriggerType.FILE_DOWNLOADED,
TRASHED: WebhookTriggerType.FILE_TRASHED,
DELETED: WebhookTriggerType.FILE_DELETED,
RESTORED: WebhookTriggerType.FILE_RESTORED,
COPIED: WebhookTriggerType.FILE_COPIED,
MOVED: WebhookTriggerType.FILE_MOVED,
LOCKED: WebhookTriggerType.FILE_LOCKED,
UNLOCKED: WebhookTriggerType.FILE_UNLOCKED,
RENAMED: WebhookTriggerType.FILE_RENAMED,
},
COMMENT: {
CREATED: WebhookTriggerType.COMMENT_CREATED,
UPDATED: WebhookTriggerType.COMMENT_UPDATED,
DELETED: WebhookTriggerType.COMMENT_DELETED,
},
TASK_ASSIGNMENT: {
CREATED: WebhookTriggerType.TASK_ASSIGNMENT_CREATED,
UPDATED: WebhookTriggerType.TASK_ASSIGNMENT_UPDATED,
},
METADATA_INSTANCE: {
CREATED: WebhookTriggerType.METADATA_INSTANCE_CREATED,
UPDATED: WebhookTriggerType.METADATA_INSTANCE_UPDATED,
DELETED: WebhookTriggerType.METADATA_INSTANCE_DELETED,
},
FOLDER: {
CREATED: WebhookTriggerType.FOLDER_CREATED,
DOWNLOADED: WebhookTriggerType.FOLDER_DOWNLOADED,
RESTORED: WebhookTriggerType.FOLDER_RESTORED,
DELETED: WebhookTriggerType.FOLDER_DELETED,
COPIED: WebhookTriggerType.FOLDER_COPIED,
MOVED: WebhookTriggerType.FOLDER_MOVED,
TRASHED: WebhookTriggerType.FOLDER_TRASHED,
RENAMED: WebhookTriggerType.FOLDER_RENAMED,
},
WEBHOOK: {
DELETED: WebhookTriggerType.WEBHOOK_DELETED,
},
COLLABORATION: {
CREATED: WebhookTriggerType.COLLABORATION_CREATED,
ACCEPTED: WebhookTriggerType.COLLABORATION_ACCEPTED,
REJECTED: WebhookTriggerType.COLLABORATION_REJECTED,
REMOVED: WebhookTriggerType.COLLABORATION_REMOVED,
UPDATED: WebhookTriggerType.COLLABORATION_UPDATED,
},
SHARED_LINK: {
DELETED: WebhookTriggerType.SHARED_LINK_DELETED,
CREATED: WebhookTriggerType.SHARED_LINK_CREATED,
UPDATED: WebhookTriggerType.SHARED_LINK_UPDATED,
},
};
Webhooks.prototype.validateMessage = Webhooks.validateMessage;
/**
* @module box-node-sdk/lib/managers/webhooks
* @see {@Link Webhooks}
*/
export = Webhooks; | the_stack |
import traverse from '@babel/traverse'
import * as t from '@babel/types'
import { SourceTextWithContext } from '../../types'
import {
LIB_FACTORY_IDENTIFIER,
LIB_IDENTIFIER,
LIB_IGNORE_FILE,
LIB_IGNORE_LINE,
LIB_MODULE,
} from '../constants'
import { toDynamicText, toStaticText } from '../extract/tsx-extractor'
import { parse, print } from '../util/ast'
import { readFile, writeFile } from '../util/file'
const removeImportRequireFactory = (ast: any, lines: string[]) => {
traverse(ast, {
enter(path) {
const node = path.node
const lineStart = node.loc ? node.loc.start.line - 1 : -1
const lineAbove = lines[lineStart - 1]
if (lineAbove?.includes(LIB_IGNORE_LINE)) {
return
}
try {
switch (node.type) {
case 'ImportDeclaration': {
if (node.source.value === LIB_MODULE) {
path.remove()
}
break
}
case 'CallExpression': {
if (t.isIdentifier(node.callee)) {
const isRequireLibModule =
node.callee.name === 'require' &&
fromStringLiteral(node.arguments[0]) === LIB_MODULE
const isDefineLib = node.callee.name === LIB_FACTORY_IDENTIFIER
if (isRequireLibModule || isDefineLib) {
const parent = path.findParent((path) =>
t.isVariableDeclaration(path.node),
)
if (parent) {
parent.remove()
}
}
}
break
}
default:
break
}
} catch (error) {
throw error
}
},
})
}
export const needTranslate = (str: string): boolean => {
return /[^\u0000-\u007F]+/.test(str) && !/^\s*$/.test(str)
}
const isCommentLine = (line: string | null): boolean => {
return Boolean(line && /^\s*(\*|\/\/|\/\*)/gi.test(line))
}
const fromStringLiteral = (
node: object | null | undefined,
): undefined | string => {
if (!node) return undefined
if (t.isStringLiteral(node)) {
return node.value
} else {
return undefined
}
}
export const wrapCode = (
code: string,
options: {
filePath?: string
namespace?: string
checkOnly?: boolean
},
): {
output: string
sourceTexts: SourceTextWithContext[]
} => {
if (code.includes(LIB_IGNORE_FILE)) {
return {
output: code,
sourceTexts: [],
}
}
const { namespace, checkOnly, filePath = '' } = options
const ast = parse(code)
let libUsed = false
const markLibUsed = (): void => {
libUsed = true
}
let libImportStatus = {
imported: false,
required: false,
namespace: undefined as string | undefined,
}
let importStatementCount = 0
let requireCallExpressionCount = 0
const lines = code.split('\n')
let sourceTexts = [] as SourceTextWithContext[]
const addStaticText = (node: t.Node, text: string): void => {
sourceTexts.push(toStaticText(node, text, filePath, lines))
}
const addDynamicText = (node: t.Node, parts: string[]) => {
sourceTexts.push(toDynamicText(node, parts, filePath, lines))
}
traverse(ast, {
enter(path) {
const node = path.node
const lineStart = node.loc ? node.loc.start.line - 1 : -1
const line = lines[lineStart]
const lineAbove = lines[lineStart - 1]
if (
lineAbove?.includes(LIB_IGNORE_LINE) ||
line?.includes(LIB_IGNORE_LINE)
) {
return
}
try {
switch (node.type) {
// '中文' => a18n('中文')
case 'StringLiteral': {
if (needTranslate(node.value)) {
// ignore when it's already: a18n(’中文’)
const parent = path.parent
if (
parent.type === 'CallExpression' &&
t.isIdentifier(parent.callee) &&
parent.callee.name === LIB_IDENTIFIER
) {
markLibUsed()
break
}
// <input placeholder="中文" /> => <input placeholder={a18n('中文') />
if (t.isJSXAttribute(parent)) {
if (checkOnly) {
addStaticText(node, node.value)
} else {
path.replaceWith(
t.jsxExpressionContainer(
t.callExpression(t.identifier(LIB_IDENTIFIER), [
t.stringLiteral(node.value),
]),
),
)
}
markLibUsed()
} else if (
!(t.isProperty(parent) && parent.key === node) &&
!t.isTSLiteralType(parent) &&
!t.isTSEnumMember(parent)
) {
if (checkOnly) {
addStaticText(node, node.value)
} else {
path.replaceWith(
t.callExpression(t.identifier(LIB_IDENTIFIER), [
t.stringLiteral(node.value),
]),
)
}
markLibUsed()
}
}
break
}
// `中文${someVar}` => a18n`中文${someVar}`
case 'TemplateLiteral': {
const { quasis } = node
if (quasis.some((q) => needTranslate(q.value.raw))) {
const parent = path.parent
if (parent.type === 'TaggedTemplateExpression') {
// ignore when it's already wrapped: a18n`中文${someVar}`
if (
t.isIdentifier(parent.tag) &&
parent.tag.name === LIB_IDENTIFIER
) {
markLibUsed()
break
}
// ignore when it's already wrapped: a18n.anyMethod`中文${someVar}`
if (
t.isMemberExpression(parent.tag) &&
t.isIdentifier(parent.tag.object) &&
parent.tag.object.name === LIB_IDENTIFIER
) {
markLibUsed()
break
}
}
if (parent.type !== 'TaggedTemplateExpression') {
if (checkOnly) {
addDynamicText(
node,
quasis.map((q) => q.value.raw),
)
} else {
path.replaceWith(
t.taggedTemplateExpression(
t.identifier(LIB_IDENTIFIER),
node,
),
)
}
markLibUsed()
}
}
break
}
// <div> 中文 </div> => <div> {a18n('中文')} </div>
case 'JSXText': {
if (needTranslate(node.value)) {
const emptyStart = node.value.match(/^\s*/)![0]
const emptyEnd = node.value.match(/\s*$/)![0]
const nonEmptyText = node.value.trim()
if (checkOnly) {
addStaticText(node, nonEmptyText)
} else {
path.replaceWithMultiple([
t.jsxText(emptyStart),
t.jsxExpressionContainer(t.stringLiteral(nonEmptyText)),
t.jsxText(emptyEnd),
])
}
markLibUsed()
}
break
}
case 'ImportDeclaration': {
importStatementCount++
if (node.source.value === LIB_MODULE) {
libImportStatus.imported = true
}
break
}
case 'CallExpression': {
if (t.isIdentifier(node.callee)) {
if (node.callee.name === 'require') {
requireCallExpressionCount++
}
const isRequireLibModule =
node.callee.name === 'require' &&
fromStringLiteral(node.arguments[0]) === LIB_MODULE
if (isRequireLibModule) {
libImportStatus.required = true
}
const isDefineLib = node.callee.name === LIB_FACTORY_IDENTIFIER
if (isDefineLib) {
const namespace = fromStringLiteral(node.arguments[0])
libImportStatus.namespace = namespace
}
}
break
}
default:
break
}
} catch (error) {
throw error
}
},
})
if (checkOnly || !libUsed) {
return {
output: code,
sourceTexts,
}
}
let output: string
if (
(libImportStatus.imported || libImportStatus.required) &&
libImportStatus.namespace == namespace
) {
output = print(ast)
} else {
removeImportRequireFactory(ast, lines)
output = print(ast)
const shouldUseImport = importStatementCount >= requireCallExpressionCount
const importDeclarators = namespace
? `{ ${LIB_FACTORY_IDENTIFIER} }`
: LIB_IDENTIFIER
const importStatement = shouldUseImport
? `import ${importDeclarators} from '${LIB_MODULE}'\n`
: `const ${importDeclarators} = require('${LIB_MODULE}')\n`
const factoryStatement = namespace
? `const a18n = ${LIB_FACTORY_IDENTIFIER}('${namespace}')\n`
: ''
output = importStatement + factoryStatement + output
}
return {
output,
sourceTexts,
}
}
export const wrapFile = (
filePath: string,
params: {
write: boolean
namespace?: string
checkOnly?: boolean
},
) => {
try {
const { namespace, checkOnly } = params
const content = readFile(filePath)
const { output: newContent, sourceTexts } = wrapCode(content, {
filePath,
namespace,
checkOnly,
})
const changed = newContent !== content
if (changed && params.write && !checkOnly) {
writeFile(filePath, newContent)
}
return {
ok: true,
sourceTexts,
}
} catch (error) {
const loc = error?.loc
if (loc) {
console.error(
`[a18n] error processing: ${filePath}:${loc.line}:${loc.column}`,
)
} else {
console.error(`[a18n] error processing: ${filePath}`)
}
console.error(error)
return {
ok: false,
}
}
} | the_stack |
import 'promise-polyfill';
import Buffers, { IOBuffer } from '../buffers/buffers';
import Context, { ContextMode } from '../context/context';
import Common from '../core/common';
import Logger from '../logger/logger';
import Vector2 from '../math/vector2';
import Renderer from '../renderer/renderer';
import Textures, { ITextureData, ITextureOptions, Texture } from '../textures/textures';
import Uniforms, { IUniformOption, Uniform, UniformMethod, UniformType } from '../uniforms/uniforms';
export interface ICanvasOptions extends WebGLContextAttributes {
vertexString?: string;
fragmentString?: string;
backgroundColor?: string;
workpath?: string;
onError?: Function;
extensions?: string[];
mode?: ContextMode;
mesh?: string;
doubleSided?: boolean;
}
export default class Canvas extends Renderer {
options: ICanvasOptions;
canvas: HTMLCanvasElement;
rect: ClientRect | DOMRect;
width: number;
height: number;
devicePixelRatio: number;
valid: boolean = false;
visible: boolean = false;
controls: boolean = false;
rafId: number;
vertexPath: string = '';
fragmentPath: string = '';
static items: Canvas[] = [];
constructor(
canvas: HTMLCanvasElement,
options: ICanvasOptions = {
// alpha: true,
// antialias: true,
// premultipliedAlpha: true
}
) {
super();
if (!canvas) {
return;
}
this.options = options;
this.canvas = canvas;
this.width = 0;
this.height = 0;
this.rect = canvas.getBoundingClientRect();
this.devicePixelRatio = window.devicePixelRatio || 1;
this.mode = options.mode || ContextMode.Flat;
this.mesh = options.mesh || undefined;
this.doubleSided = options.doubleSided || false;
this.defaultMesh = this.mesh;
this.workpath = options.workpath;
canvas.style.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';
this.getShaders_().then((_) => {
this.load().then(_ => {
if (!this.program) {
return;
}
this.addListeners_();
this.onLoop();
});
}, (error) => {
Logger.error('GlslCanvas.getShaders_.error', error);
});
Canvas.items.push(this);
}
private getShaders_(): Promise<string[]> {
return new Promise((resolve) => {
this.vertexString = this.options.vertexString || this.vertexString;
this.fragmentString = this.options.fragmentString || this.fragmentString;
const canvas = this.canvas;
const urls: any = {};
if (canvas.hasAttribute('data-vertex-url')) {
urls.vertex = canvas.getAttribute('data-vertex-url');
}
if (canvas.hasAttribute('data-fragment-url')) {
urls.fragment = canvas.getAttribute('data-fragment-url');
}
if (canvas.hasAttribute('data-vertex')) {
this.vertexString = canvas.getAttribute('data-vertex');
}
if (canvas.hasAttribute('data-fragment')) {
this.fragmentString = canvas.getAttribute('data-fragment');
}
if (Object.keys(urls).length) {
Promise.all(Object.keys(urls).map((key) => {
const url = Common.getResource(urls[key], this.workpath);
return Common.fetch(url)
// .then((response) => response.text())
.then((body) => {
const path = Common.dirname(urls[key]);
if (key === 'vertex') {
this.vertexPath = path;
return this.vertexString = body;
} else {
this.fragmentPath = path;
return this.fragmentString = body;
}
})
})).then(_ => {
resolve([this.vertexString, this.fragmentString]);
});
} else {
resolve([this.vertexString, this.fragmentString]);
}
});
}
private addListeners_(): void {
/*
const resize = (e: Event) => {
this.rect = this.canvas.getBoundingClientRect();
this.trigger('resize', e);
};
*/
this.onScroll = this.onScroll.bind(this);
this.onWheel = this.onWheel.bind(this);
this.onClick = this.onClick.bind(this);
this.onMove = this.onMove.bind(this);
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseOver = this.onMouseOver.bind(this);
this.onMouseOut = this.onMouseOut.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.onTouchMove = this.onTouchMove.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
this.onTouchStart = this.onTouchStart.bind(this);
this.onLoop = this.onLoop.bind(this);
// window.addEventListener('resize', this.onResize);
window.addEventListener('scroll', this.onScroll);
document.addEventListener('mousemove', this.onMouseMove, false);
document.addEventListener('touchmove', this.onTouchMove);
this.addCanvasListeners_();
}
private addCanvasListeners_() {
this.controls = this.canvas.hasAttribute('controls');
this.canvas.addEventListener('wheel', this.onWheel);
this.canvas.addEventListener('click', this.onClick);
this.canvas.addEventListener('mousedown', this.onMouseDown);
this.canvas.addEventListener('touchstart', this.onTouchStart);
if (this.controls) {
this.canvas.addEventListener('mouseover', this.onMouseOver);
this.canvas.addEventListener('mouseout', this.onMouseOut);
if (!this.canvas.hasAttribute('data-autoplay')) {
this.pause();
}
}
}
private removeCanvasListeners_() {
this.canvas.removeEventListener('wheel', this.onWheel);
this.canvas.removeEventListener('click', this.onClick);
this.canvas.removeEventListener('mousedown', this.onMouseDown);
this.canvas.removeEventListener('mouseup', this.onMouseUp);
this.canvas.removeEventListener('touchstart', this.onTouchStart);
this.canvas.removeEventListener('touchend', this.onTouchEnd);
if (this.controls) {
this.canvas.removeEventListener('mouseover', this.onMouseOver);
this.canvas.removeEventListener('mouseout', this.onMouseOut);
}
}
private removeListeners_() {
window.cancelAnimationFrame(this.rafId);
// window.removeEventListener('resize', this.onResize);
window.removeEventListener('scroll', this.onScroll);
document.removeEventListener('mousemove', this.onMouseMove);
document.removeEventListener('touchmove', this.onTouchMove);
this.removeCanvasListeners_();
}
private onScroll(_: Event) {
this.rect = this.canvas.getBoundingClientRect();
}
private onWheel(e: WheelEvent) {
this.camera.wheel(e.deltaY);
this.dirty = this.mode !== ContextMode.Flat;
this.trigger('wheel', e);
}
private onClick(e: MouseEvent) {
if (this.controls) {
this.toggle();
}
this.trigger('click', e);
}
private onDown(mx: number, my: number) {
const rect = this.rect;
mx = (mx - rect.left);
my = (rect.height - (my - rect.top));
const x = mx * this.devicePixelRatio;
const y = my * this.devicePixelRatio;
this.mouse.x = x;
this.mouse.y = y;
const min = Math.min(rect.width, rect.height);
this.camera.down(mx / min, my / min);
this.trigger('down', this.mouse);
}
private onMove(mx: number, my: number) {
const rect = this.rect;
mx = (mx - rect.left);
my = (rect.height - (my - rect.top));
const x = mx * this.devicePixelRatio;
const y = my * this.devicePixelRatio;
if (x !== this.mouse.x ||
y !== this.mouse.y) {
this.mouse.x = x;
this.mouse.y = y;
const min = Math.min(rect.width, rect.height);
this.camera.move(mx / min, my / min);
this.dirty = this.mode !== ContextMode.Flat && this.camera.mouse !== null;
this.trigger('move', this.mouse);
}
}
private onUp(e: Event) {
this.camera.up();
if (this.controls) {
this.pause();
}
this.trigger('out', e);
}
private onMouseDown(e: MouseEvent) {
this.onDown(e.clientX, e.clientY);
document.addEventListener('mouseup', this.onMouseUp);
document.removeEventListener('touchstart', this.onTouchStart);
document.removeEventListener('touchmove', this.onTouchMove);
}
private onMouseMove(e: MouseEvent) {
this.onMove(e.clientX, e.clientY);
}
private onMouseUp(e: MouseEvent) {
this.onUp(e);
}
private onMouseOver(e: MouseEvent) {
this.play();
this.trigger('over', e);
}
private onMouseOut(e: MouseEvent) {
this.pause();
this.trigger('out', e);
}
private onTouchStart(e: TouchEvent) {
const touch = [].slice.call(e.touches).reduce((p: Vector2, touch: Touch) => {
p = p || new Vector2();
p.x += touch.clientX;
p.y += touch.clientY;
return p;
}, null);
if (touch) {
this.onDown(touch.x / e.touches.length, touch.y / e.touches.length);
}
if (this.controls) {
this.play();
}
this.trigger('over', e);
document.addEventListener('touchend', this.onTouchEnd);
document.removeEventListener('mousedown', this.onMouseDown);
document.removeEventListener('mousemove', this.onMouseMove);
if (this.controls) {
this.canvas.removeEventListener('mouseover', this.onMouseOver);
this.canvas.removeEventListener('mouseout', this.onMouseOut);
}
}
private onTouchMove(e: TouchEvent) {
const touch = [].slice.call(e.touches).reduce((p: Vector2, touch: Touch) => {
p = p || new Vector2();
p.x += touch.clientX;
p.y += touch.clientY;
return p;
}, null);
if (touch) {
this.onMove(touch.x / e.touches.length, touch.y / e.touches.length);
}
}
private onTouchEnd(e: TouchEvent) {
this.onUp(e);
document.removeEventListener('touchend', this.onTouchEnd);
}
private onLoop(_?: number) {
this.checkRender();
this.rafId = window.requestAnimationFrame(this.onLoop);
}
private setUniform_(
key: string,
values: any[],
options: ITextureOptions = {},
type: UniformType = null
): void {
const uniform: Uniform | Uniform[] = Uniforms.parseUniform(key, values, type);
if (Array.isArray(uniform)) {
if (Uniforms.isArrayOfSampler2D(uniform)) {
uniform.forEach((x) => this.loadTexture(x.key, x.values[0], options));
} else {
uniform.forEach((x) => this.uniforms.set(x.key, x.values[0]));
}
} else if (uniform) {
switch (uniform.type) {
case UniformType.Sampler2D:
this.loadTexture(key, values[0], options);
break;
default:
this.uniforms.set(key, uniform);
}
}
}
private isVisible_(): boolean {
const rect = this.rect;
return (rect.top + rect.height) > 0 && rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
private isAnimated_(): boolean {
return (this.animated || this.textures.animated || this.mode !== ContextMode.Flat) && !this.timer.paused;
}
private isDirty_(): boolean {
return this.dirty || this.uniforms.dirty || this.textures.dirty;
}
// check size change at start of requestFrame
private sizeDidChanged_(): boolean {
const gl = this.gl;
const CW = Math.ceil(this.canvas.clientWidth),
CH = Math.ceil(this.canvas.clientHeight);
if (this.width !== CW ||
this.height !== CH) {
this.width = CW;
this.height = CH;
// Lookup the size the browser is displaying the canvas in CSS pixels
// and compute a size needed to make our drawingbuffer match it in
// device pixels.
const W = Math.ceil(CW * this.devicePixelRatio);
const H = Math.ceil(CH * this.devicePixelRatio);
this.W = W;
this.H = H;
this.canvas.width = W;
this.canvas.height = H;
/*
if (gl.canvas.width !== W ||
gl.canvas.height !== H) {
gl.canvas.width = W;
gl.canvas.height = H;
// Set the viewport to match
// gl.viewport(0, 0, W, H);
}
*/
Object.keys(this.buffers.values).forEach((key) => {
const buffer: IOBuffer = this.buffers.values[key];
buffer.resize(gl, W, H);
});
this.rect = this.canvas.getBoundingClientRect();
this.trigger('resize');
// gl.useProgram(this.program);
return true;
} else {
return false;
}
}
private parseTextures_(fragmentString: string): boolean {
const regexp = /uniform\s*sampler2D\s*([\w]*);(\s*\/\/\s*([\w|\:\/\/|\.|\-|\_|\?|\&|\=]*)|\s*)/gm;
let matches;
while ((matches = regexp.exec(fragmentString)) !== null) {
const key = matches[1];
const url = matches[3];
if (Texture.isTextureUrl(url)) {
this.textureList.push({ key, url });
} else if (!this.buffers.has(key)) {
// create empty texture
this.textureList.push({ key, url: null });
}
}
if (this.canvas.hasAttribute('data-textures')) {
const urls = this.canvas.getAttribute('data-textures').split(',');
urls.forEach((url: string, i: number) => {
const key = 'u_texture' + i;
this.textureList.push({ key, url });
});
}
return this.textureList.length > 0;
}
load(
fragmentString?: string,
vertexString?: string
): Promise<boolean> {
const fragmentVertexString: string = Context.getFragmentVertex(this.gl, fragmentString || this.fragmentString);
return Promise.all([
Context.getIncludes(fragmentString || this.fragmentString, this.fragmentPath === '' ? this.workpath : this.fragmentPath),
Context.getIncludes(fragmentVertexString || vertexString || this.vertexString, this.vertexPath === '' ? this.workpath : this.vertexPath)
]).then(array => {
this.fragmentString = array[0];
this.vertexString = array[1];
return this.createContext_();
});
}
private getContext_(): WebGLRenderingContext | WebGL2RenderingContext {
const vertexString = this.vertexString;
const fragmentString = this.fragmentString;
this.vertexString = Context.getVertex(vertexString, fragmentString, this.mode);
this.fragmentString = Context.getFragment(vertexString, fragmentString, this.mode);
if (Context.versionDiffers(this.gl, vertexString, fragmentString)) {
this.destroyContext_();
this.swapCanvas_();
this.uniforms = new Uniforms();
this.buffers = new Buffers();
this.textures = new Textures();
this.textureList = [];
}
if (!this.gl) {
const gl = Context.tryInferContext(vertexString, fragmentString, this.canvas, this.options, this.options.extensions, this.options.onError);
if (!gl) {
return null;
}
this.gl = gl;
}
return this.gl;
}
private createContext_(): boolean {
const gl = this.getContext_();
if (!gl) {
return false;
}
let vertexShader, fragmentShader;
try {
Context.inferPrecision(this.fragmentString);
vertexShader = Context.createShader(gl, this.vertexString, gl.VERTEX_SHADER);
fragmentShader = Context.createShader(gl, this.fragmentString, gl.FRAGMENT_SHADER);
// If Fragment shader fails load a empty one to sign the error
if (!fragmentShader) {
const defaultFragment = Context.getFragment(null, null, this.mode);
fragmentShader = Context.createShader(gl, defaultFragment, gl.FRAGMENT_SHADER);
this.valid = false;
} else {
this.valid = true;
}
} catch (e) {
// !!!
// console.error(e);
this.trigger('error', e);
return false;
}
// Create and use program
const program = Context.createProgram(gl, [vertexShader, fragmentShader]); //, [0,1],['a_texcoord','a_position']);
if (!program) {
this.trigger('error', Context.lastError);
return false;
}
// console.log(this.vertexString, this.fragmentString, program);
// Delete shaders
// gl.detachShader(program, vertexShader);
// gl.detachShader(program, fragmentShader);
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
this.program = program;
if (this.valid) {
try {
this.buffers = Buffers.getBuffers(gl, this.fragmentString, Context.getBufferVertex(gl));
} catch (e) {
// console.error('load', e);
this.valid = false;
this.trigger('error', e);
return false;
}
this.create_();
if (this.animated) {
this.canvas.classList.add('animated');
} else {
this.canvas.classList.remove('animated');
}
}
// Trigger event
this.trigger('load', this);
return this.valid;
}
protected create_(): void {
this.parseMode_();
this.parseMesh_();
super.create_();
this.createBuffers_();
this.createTextures_();
}
protected parseMode_() {
if (this.canvas.hasAttribute('data-mode')) {
const data = this.canvas.getAttribute('data-mode');
if (['flat', 'box', 'sphere', 'torus', 'mesh'].indexOf(data) !== -1) {
this.mode = data as ContextMode;
}
}
}
protected parseMesh_() {
if (this.canvas.hasAttribute('data-mesh')) {
const data = this.canvas.getAttribute('data-mesh');
if (data.indexOf('.obj') !== -1) {
this.mesh = this.defaultMesh = data;
}
}
}
protected createBuffers_() {
Object.keys(this.buffers.values).forEach((key) => {
const buffer: IOBuffer = this.buffers.values[key];
this.uniforms.create(UniformMethod.Uniform1i, UniformType.Sampler2D, buffer.key, [buffer.input.index]);
});
}
protected createTextures_() {
const hasTextures = this.parseTextures_(this.fragmentString);
if (hasTextures) {
this.textureList.filter(x => x.url).forEach(x => {
this.setTexture(x.key, x.url, x.options);
});
this.textureList = [];
}
}
protected update_(): void {
super.update_();
this.updateBuffers_();
this.updateTextures_();
}
protected updateBuffers_(): void {
Object.keys(this.buffers.values).forEach((key) => {
const buffer: IOBuffer = this.buffers.values[key];
this.uniforms.update(UniformMethod.Uniform1i, UniformType.Sampler2D, buffer.key, [buffer.input.index]);
});
}
protected updateTextures_(): void {
const gl = this.gl;
Object.keys(this.textures.values).forEach((key) => {
const texture: Texture = this.textures.values[key];
texture.tryUpdate(gl);
this.uniforms.update(UniformMethod.Uniform1i, UniformType.Sampler2D, texture.key, [texture.index]);
});
}
private destroyContext_(): void {
const gl = this.gl;
gl.useProgram(null);
if (this.program) {
gl.deleteProgram(this.program);
}
Object.keys(this.buffers.values).forEach((key) => {
const buffer: IOBuffer = this.buffers.values[key];
buffer.destroy(gl);
});
Object.keys(this.textures.values).forEach((key) => {
const texture: Texture = this.textures.values[key];
texture.destroy(gl);
});
this.buffers = null;
this.textures = null;
this.uniforms = null;
this.program = null;
this.gl = null;
}
private swapCanvas_(): void {
const canvas = this.canvas;
const canvas_ = canvas.cloneNode() as HTMLCanvasElement;
canvas.parentNode.replaceChild(canvas_, canvas);
this.canvas = canvas_;
this.addCanvasListeners_();
}
destroy(): void {
this.removeListeners_();
this.destroyContext_();
this.animated = false;
this.valid = false;
const index = Canvas.items.indexOf(this);
if (index !== -1) {
Canvas.items.splice(index, 1);
}
}
loadTexture(
key: string,
urlElementOrData: string | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | Element | ITextureData,
options: ITextureOptions = {}
) {
if (this.valid) {
// Logger.log('GlslCanvas.loadTexture', key, urlElementOrData);
this.textures.createOrUpdate(this.gl, key, urlElementOrData, this.buffers.count, options, this.options.workpath).then(
texture => {
const index = texture.index;
const uniform = this.uniforms.createTexture(key, index);
uniform.texture = texture;
const keyResolution = key.indexOf('[') !== -1 ? key.replace('[', 'Resolution[') : key + 'Resolution';
// const uniformResolution = ;
this.uniforms.create(UniformMethod.Uniform2f, UniformType.Float, keyResolution, [texture.width, texture.height]);
// Logger.log('loadTexture', key, url, index, texture.width, texture.height);
return texture;
},
error => {
const message = Array.isArray(error.path) ? error.path.map((x: any) => x.error ? x.error.message : '').join(', ') : error.message;
Logger.error('GlslCanvas.loadTexture.error', key, urlElementOrData, message);
this.trigger('textureError', { key, urlElementOrData, message });
});
} else {
this.textureList.push({ key, url: urlElementOrData, options });
}
}
setTexture(
key: string,
urlElementOrData: string | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | Element | ITextureData,
options: ITextureOptions = {}
): void {
return this.setUniform_(key, [urlElementOrData], options);
}
setUniform(key: string, ...values: any[]): void {
return this.setUniform_(key, values);
}
setUniformOfInt(key: string, values: any[]): void {
return this.setUniform_(key, values, null, UniformType.Int);
}
setUniforms(values: IUniformOption): void {
Object.keys(values).forEach((key) => {
this.setUniform(key, values[key]);
});
}
pause(): void {
if (this.valid) {
this.timer.pause();
this.canvas.classList.add('paused');
this.trigger('pause');
}
}
play(): void {
if (this.valid) {
this.timer.play();
this.canvas.classList.remove('paused');
this.trigger('play');
}
}
toggle(): void {
if (this.valid) {
if (this.timer.paused) {
this.play();
} else {
this.pause();
}
}
}
checkRender(): void {
if (this.isVisible_() && (this.sizeDidChanged_() || this.isDirty_() || this.isAnimated_())) {
this.render();
this.canvas.classList.add('playing');
} else {
this.canvas.classList.remove('playing');
}
}
/*
test(
fragmentString?: string,
vertexString?: string
): Promise<any> {
return new Promise((resolve, reject) => {
const vertex = this.vertexString;
const fragment = this.fragmentString;
const paused = this.timer.paused;
// Thanks to @thespite for the help here
// https://www.khronos.org/registry/webgl/extensions/EXT_disjoint_timer_query/
const extension = this.gl.getExtension('EXT_disjoint_timer_query');
const query = extension.createQueryEXT();
let wasValid = this.valid;
if (fragmentString || vertexString) {
this.load(fragmentString, vertexString);
wasValid = this.valid;
this.render();
}
this.timer.paused = true;
extension.beginQueryEXT(extension.TIME_ELAPSED_EXT, query);
this.render();
extension.endQueryEXT(extension.TIME_ELAPSED_EXT);
const waitForTest = () => {
this.render();
const available = extension.getQueryObjectEXT(query, extension.QUERY_RESULT_AVAILABLE_EXT);
const disjoint = this.gl.getParameter(extension.GPU_DISJOINT_EXT);
if (available && !disjoint) {
const result = {
wasValid: wasValid,
fragment: fragmentString || this.fragmentString,
vertex: vertexString || this.vertexString,
timeElapsedMs: extension.getQueryObjectEXT(query, extension.QUERY_RESULT_EXT) / 1000000.0
};
this.timer.paused = paused;
if (fragmentString || vertexString) {
this.load(fragment, vertex);
}
resolve(result);
} else {
window.requestAnimationFrame(waitForTest);
}
}
waitForTest();
});
}
*/
} | the_stack |
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_icons_css.m.js';
import 'chrome://resources/cr_elements/cr_page_host_style_css.js';
import 'chrome://resources/cr_elements/cr_toolbar/cr_toolbar.js';
import 'chrome://resources/cr_elements/hidden_style_css.m.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import './icons.js';
import './strings.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {sanitizeInnerHtml} from 'chrome://resources/js/parse_html_subset.m.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserReportingResponse, Extension, ManagementBrowserProxy, ManagementBrowserProxyImpl, ReportingType, ThreatProtectionInfo} from './management_browser_proxy.js';
// <if expr="chromeos">
import {DeviceReportingResponse, DeviceReportingType} from './management_browser_proxy.js';
// </if>
type BrowserReportingData = {
messageIds: string[],
icon: string,
};
const ManagementUiElementBase = WebUIListenerMixin(I18nMixin(PolymerElement));
class ManagementUiElement extends ManagementUiElementBase {
static get is() {
return 'management-ui';
}
static get properties() {
return {
/**
* List of messages related to browser reporting.
*/
browserReportingInfo_: Array,
/**
* List of messages related to browser reporting.
*/
extensions_: Array,
/**
* List of messages related to browser reporting.
*/
managedWebsites_: Array,
managedWebsitesSubtitle_: String,
// <if expr="chromeos">
/**
* List of messages related to device reporting.
*/
deviceReportingInfo_: Array,
/**
* Message stating if the Trust Roots are configured.
*/
localTrustRoots_: String,
customerLogo_: String,
managementOverview_: String,
pluginVmDataCollectionEnabled_: Boolean,
eolAdminMessage_: String,
eolMessage_: String,
showProxyServerPrivacyDisclosure_: Boolean,
// </if>
subtitle_: String,
// <if expr="not chromeos">
managementNoticeHtml_: String,
// </if>
managed_: Boolean,
extensionReportingSubtitle_: String,
threatProtectionInfo_: Object,
};
}
private browserReportingInfo_: Array<BrowserReportingData>|null;
private extensions_: Array<Extension>|null;
private managedWebsites_: string[]|null;
private managedWebsitesSubtitle_: string;
// <if expr="chromeos">
private deviceReportingInfo_: Array<DeviceReportingResponse>|null;
private localTrustRoots_: string;
private customerLogo_: string;
private managementOverview_: string;
private pluginVmDataCollectionEnabled_: boolean;
private eolAdminMessage_: string;
private eolMessage_: string;
private showProxyServerPrivacyDisclosure_: boolean;
// </if>
private subtitle_: string;
// <if expr="not chromeos">
private managementNoticeHtml_: string;
// </if>
private managed_: boolean;
private extensionReportingSubtitle_: string;
private threatProtectionInfo_: ThreatProtectionInfo;
private browserProxy_: ManagementBrowserProxy|null = null;
/** @override */
connectedCallback() {
super.connectedCallback();
document.documentElement.classList.remove('loading');
this.browserProxy_ = ManagementBrowserProxyImpl.getInstance();
this.updateManagedFields_();
this.initBrowserReportingInfo_();
this.getThreatProtectionInfo_();
this.addWebUIListener(
'browser-reporting-info-updated',
(reportingInfo: Array<BrowserReportingResponse>) =>
this.onBrowserReportingInfoReceived_(reportingInfo));
// <if expr="chromeos">
this.addWebUIListener(
'plugin-vm-data-collection-updated',
(enabled: boolean) => this.pluginVmDataCollectionEnabled_ = enabled);
// </if>
this.addWebUIListener('managed_data_changed', () => {
this.updateManagedFields_();
});
this.addWebUIListener(
'threat-protection-info-updated',
(info: ThreatProtectionInfo) => this.threatProtectionInfo_ = info);
this.getExtensions_();
this.getManagedWebsites_();
// <if expr="chromeos">
this.getDeviceReportingInfo_();
this.getPluginVmDataCollectionStatus_();
this.getLocalTrustRootsInfo_();
// </if>
}
private initBrowserReportingInfo_() {
this.browserProxy_!.initBrowserReportingInfo().then(
reportingInfo => this.onBrowserReportingInfoReceived_(reportingInfo));
}
private onBrowserReportingInfoReceived_(reportingInfo:
Array<BrowserReportingResponse>) {
const reportingInfoMap = reportingInfo.reduce((info, response) => {
info[response.reportingType] = info[response.reportingType] || {
icon: this.getIconForReportingType_(response.reportingType),
messageIds: []
};
info[response.reportingType].messageIds.push(response.messageId);
return info;
}, {} as {[k: string]: {icon: string, messageIds: string[]}});
const reportingTypeOrder = {
[ReportingType.SECURITY]: 1,
[ReportingType.EXTENSIONS]: 2,
[ReportingType.USER]: 3,
[ReportingType.USER_ACTIVITY]: 4,
[ReportingType.DEVICE]: 5,
} as {[k: string]: number};
this.browserReportingInfo_ =
Object.keys(reportingInfoMap)
.sort((a, b) => reportingTypeOrder[a] - reportingTypeOrder[b])
.map(reportingType => reportingInfoMap[reportingType]);
}
private getExtensions_() {
this.browserProxy_!.getExtensions().then(extensions => {
this.extensions_ = extensions;
});
}
private getManagedWebsites_() {
this.browserProxy_!.getManagedWebsites().then(managedWebsites => {
this.managedWebsites_ = managedWebsites;
});
}
private getThreatProtectionInfo_() {
this.browserProxy_!.getThreatProtectionInfo().then(info => {
this.threatProtectionInfo_ = info;
});
}
/**
* @return Whether there is threat protection info to show.
*/
private showThreatProtectionInfo_(): boolean {
return !!this.threatProtectionInfo_ &&
this.threatProtectionInfo_.info.length > 0;
}
// <if expr="chromeos">
private getLocalTrustRootsInfo_() {
this.browserProxy_!.getLocalTrustRootsInfo().then(trustRootsConfigured => {
this.localTrustRoots_ = trustRootsConfigured ?
loadTimeData.getString('managementTrustRootsConfigured') :
'';
});
}
private getDeviceReportingInfo_() {
this.browserProxy_!.getDeviceReportingInfo().then(reportingInfo => {
this.deviceReportingInfo_ = reportingInfo;
});
}
private getPluginVmDataCollectionStatus_() {
this.browserProxy_!.getPluginVmDataCollectionStatus().then(
pluginVmDataCollectionEnabled => {
this.pluginVmDataCollectionEnabled_ = pluginVmDataCollectionEnabled;
});
}
/**
* @return Whether there are device reporting info to show.
*/
private showDeviceReportingInfo_(): boolean {
return !!this.deviceReportingInfo_ && this.deviceReportingInfo_.length > 0;
}
/**
* @param eolAdminMessage The device return instructions
* @return Whether there are device return instructions from the
* admin in case an update is required after reaching end of life.
*/
private isEmpty_(eolAdminMessage: string): boolean {
return !eolAdminMessage || eolAdminMessage.trim().length === 0;
}
/**
* @return The associated icon.
*/
private getIconForDeviceReportingType_(reportingType: DeviceReportingType):
string {
switch (reportingType) {
case DeviceReportingType.SUPERVISED_USER:
return 'management:supervised-user';
case DeviceReportingType.DEVICE_ACTIVITY:
return 'management:timelapse';
case DeviceReportingType.STATISTIC:
return 'management:bar-chart';
case DeviceReportingType.DEVICE:
return 'cr:computer';
case DeviceReportingType.CRASH_REPORT:
return 'management:crash';
case DeviceReportingType.APP_INFO_AND_ACTIVITY:
return 'management:timelapse';
case DeviceReportingType.LOGS:
return 'management:report';
case DeviceReportingType.PRINT:
return 'cr:print';
case DeviceReportingType.PRINT_JOBS:
return 'cr:print';
case DeviceReportingType.DLP_EVENTS:
return 'management:policy';
case DeviceReportingType.CROSTINI:
return 'management:linux';
case DeviceReportingType.USERNAME:
return 'management:account-circle';
case DeviceReportingType.EXTENSION:
return 'cr:extension';
case DeviceReportingType.ANDROID_APPLICATION:
return 'management:play-store';
case DeviceReportingType.LOGIN_LOGOUT:
return 'management:timelapse';
default:
return 'cr:computer';
}
}
// </if>
/**
* @return Whether there are browser reporting info to show.
*/
private showBrowserReportingInfo_(): boolean {
return !!this.browserReportingInfo_ &&
this.browserReportingInfo_.length > 0;
}
/**
* @return Whether there are extension reporting info to show.
*/
private showExtensionReportingInfo_(): boolean {
return !!this.extensions_ && this.extensions_.length > 0;
}
/**
* @return Whether there is managed websites info to show.
*/
private showManagedWebsitesInfo_(): boolean {
return !!this.managedWebsites_ && this.managedWebsites_.length > 0;
}
/**
* @return The associated icon.
*/
private getIconForReportingType_(reportingType: ReportingType): string {
switch (reportingType) {
case ReportingType.SECURITY:
return 'cr:security';
case ReportingType.DEVICE:
return 'cr:computer';
case ReportingType.EXTENSIONS:
return 'cr:extension';
case ReportingType.USER:
return 'management:account-circle';
case ReportingType.USER_ACTIVITY:
return 'management:public';
default:
return 'cr:security';
}
}
/**
* Handles the 'search-changed' event fired from the toolbar.
* Redirects to the settings page initialized the the current
* search query.
*/
private onSearchChanged_(e: CustomEvent<string>) {
const query = e.detail;
window.location.href =
`chrome://settings?search=${encodeURIComponent(query)}`;
}
private onTapBack_() {
if (history.length > 1) {
history.back();
} else {
window.location.href = 'chrome://settings/help';
}
}
private updateManagedFields_() {
this.browserProxy_!.getContextualManagedData().then(data => {
this.managed_ = data.managed;
this.extensionReportingSubtitle_ = data.extensionReportingTitle;
this.managedWebsitesSubtitle_ = data.managedWebsitesSubtitle;
this.subtitle_ = data.pageSubtitle;
// <if expr="chromeos">
this.customerLogo_ = data.customerLogo;
this.managementOverview_ = data.overview;
this.eolMessage_ = data.eolMessage;
this.showProxyServerPrivacyDisclosure_ =
data.showProxyServerPrivacyDisclosure;
try {
// Sanitizing the message could throw an error if it contains non
// supported markup.
this.eolAdminMessage_ = sanitizeInnerHtml(data.eolAdminMessage);
} catch (e) {
this.eolAdminMessage_ = '';
}
// </if>
// <if expr="not chromeos">
this.managementNoticeHtml_ = data.browserManagementNotice;
// </if>
});
}
static get template() {
return html`{__html_template__}`;
}
}
customElements.define(ManagementUiElement.is, ManagementUiElement); | the_stack |
import * as std from "tstl";
import { ExternalSystemArray } from "../external/ExternalSystemArray";
import { ParallelSystem } from "./ParallelSystem";
import { InvokeHistory } from "../slave/InvokeHistory";
import { PRInvokeHistory } from "./PRInvokeHistory";
import { Invoke } from "../../protocol/invoke/Invoke";
import { InvokeParameter } from "../../protocol/invoke/InvokeParameter";
/**
* Master of Parallel Processing System.
*
* The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system
* drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your
* system, a **Master** of *Parallel Processing System* that requesting *parallel process* to **slave** systems and the
* children {@link ParallelSystem} objects represent the remote **slave** systems, who is being requested the
* *parallel processes*.
*
* You can specify this {@link ParallelSystemArray} class to be *a server accepting parallel clients* or
* *a client connecting to parallel servers*. Even both of them is possible. Extends one of them below and overrides
* abstract factory method(s) creating the child {@link ParallelSystem} object.
*
* - {@link ParallelClientArray}: A server accepting {@link ParallelSystem parallel clients}.
* - {@link ParallelServerArray}: A client connecting to {@link ParallelServer parallel servers}.
* - {@link ParallelServerClientArray}: Both of them. Accepts {@link ParallelSystem parallel clients} and connects to
* {@link ParallelServer parallel servers} at the same time.
*
* When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}.
* When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s
* {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices
* will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}.
*
* <a href="http://samchon.github.io/framework/images/design/ts_class_diagram/templates_parallel_system.png"
* target="_blank">
* <img src="http://samchon.github.io/framework/images/design/ts_class_diagram/templates_parallel_system.png"
* style="max-width: 100%" />
* </a>
*
* #### Proxy Pattern
* This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take
* advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the
* *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it
* may better to utilizing the *Proxy Pattern*:
*
* The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which
* {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not
* important. Only interested in user's perspective is *which can be done*.
*
* By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged
* to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}.
* Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.
*
* <ul>
* <li>
* {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring
* from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}.
* </li>
* <li>
* When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call
* {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the
* external system.
* </li>
* <li> Those strategy is called *Proxy Pattern*. </li>
* </ul>
*
* @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System)
* @author Jeongho Nam <http://samchon.org>
*/
export abstract class ParallelSystemArray<System extends ParallelSystem>
extends ExternalSystemArray<System>
{
/**
* @hidden
*/
private history_sequence_: number;
/* ---------------------------------------------------------
CONSTRUCTORS
--------------------------------------------------------- */
/**
* Default Constructor.
*/
public constructor()
{
super();
this.history_sequence_ = 0;
}
/* =========================================================
INVOKE MESSAGE CHAIN
- SEND DATA
- PERFORMANCE ESTIMATION
============================================================
SEND & REPLY DATA
--------------------------------------------------------- */
/**
* Send an {@link Invoke} message with segment size.
*
* Sends an {@link Invoke} message requesting a **parallel process** with its *segment size*. The {@link Invoke}
* message will be delivered to children {@link ParallelSystem} objects with the *piece size*, which is divided
* from the *segment size*, basis on their {@link ParallelSystem.getPerformance performance indices}.
*
* - If segment size is 100,
* - The segment will be allocated such below:
*
* Name | Performance index | Number of pieces to be allocated | Formula
* --------|-------------------|----------------------------------|--------------
* Snail | 1 | 10 | 100 / 10 * 1
* Cheetah | 4 | 40 | 100 / 10 * 4
* Rabbit | 3 | 30 | 100 / 10 * 3
* Turtle | 2 | 20 | 100 / 10 * 2
*
* When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate
* {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their
* execution time.
*
* @param invoke An {@link Invoke} message requesting parallel process.
* @param size Number of pieces to segment.
*
* @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*.
*
* @see {@link sendPieceData}, {@link ParallelSystem.getPerformacen}
*/
public sendSegmentData(invoke: Invoke, size: number): number
{
return this.sendPieceData(invoke, 0, size);
}
/**
* Send an {@link Invoke} message with range of pieces.
*
* Sends an {@link Invoke} message requesting a **parallel process** with its *range of pieces [first, last)*.
* The {@link Invoke} will be delivered to children {@link ParallelSystem} objects with the newly computed
* *range of sub-pieces*, which is divided from the *range of pieces (first to last)*, basis on their
* {@link ParallelSystem.getPerformance performance indices}.
*
* - If indices of pieces are 0 to 50,
* - The sub-pieces will be allocated such below:
*
* Name | Performance index | Range of sub-pieces to be allocated | Formula
* --------|-------------------|-------------------------------------|------------------------
* Snail | 1 | ( 0, 5] | (50 - 0) / 10 * 1
* Cheetah | 4 | ( 5, 25] | (50 - 0) / 10 * 4 + 5
* Rabbit | 3 | (25, 40] | (50 - 0) / 10 * 3 + 25
* Turtle | 2 | (40, 50] | (50 - 0) / 10 * 2 + 40
*
* When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate
* {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their
* execution time.
*
* @param invoke An {@link Invoke} message requesting parallel process.
* @param first Initial piece's index in a section.
* @param last Final piece's index in a section. The range used is [*first*, *last*), which contains
* all the pieces' indices between *first* and *last*, including the piece pointed by index
* *first*, but not the piece pointed by the index *last*.
*
* @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*.
*
* @see {@link sendSegmentData}, {@link ParallelSystem.getPerformacen}
*/
public sendPieceData(invoke: Invoke, first: number, last: number): number
{
if (invoke.has("_History_uid") == false)
invoke.push_back(new InvokeParameter("_History_uid", ++this.history_sequence_));
else
{
// INVOKE MESSAGE ALREADY HAS ITS OWN UNIQUE ID
// - THIS IS A TYPE OF ParallelSystemArrayMediator. THE MESSAGE HAS COME FROM ITS MASTER
// - A ParallelSystem HAS DISCONNECTED. THE SYSTEM SHIFTED ITS CHAIN TO OTHER SLAVES.
let uid: number = invoke.get("_History_uid").getValue();
// FOR CASE 1. UPDATE HISTORY_SEQUENCE TO MAXIMUM
if (uid > this.history_sequence_)
this.history_sequence_ = uid;
}
let segment_size: number = last - first; // TOTAL NUMBER OF PIECES TO DIVIDE
let candidate_systems: std.Vector<ParallelSystem> = new std.Vector<ParallelSystem>(); // SYSTEMS TO BE GET DIVIDED PROCESSES
let participants_count: number = 0;
// POP EXCLUDEDS
for (let i: number = 0; i < this.size(); i++)
if (this.at(i)["exclude_"] == false)
candidate_systems.push(this.at(i));
// ORDERS
for (let i: number = 0; i < candidate_systems.size(); i++)
{
let system: ParallelSystem = candidate_systems.at(i);
// COMPUTE FIRST AND LAST INDEX TO ALLOCATE
let piece_size: number = (i == candidate_systems.size() - 1)
? segment_size - first
: Math.floor(segment_size / candidate_systems.size() * system.getPerformance());
if (piece_size == 0)
continue;
// SEND DATA WITH PIECES' INDEXES
system["_Send_piece_data"](invoke, first, first + piece_size);
first += piece_size; // FOR THE NEXT STEP
participants_count++;
}
return participants_count;
}
/* ---------------------------------------------------------
PERFORMANCE ESTIMATION
--------------------------------------------------------- */
/**
* @hidden
*/
protected _Complete_history(history: InvokeHistory): boolean
{
// WRONG TYPE
if ((history instanceof PRInvokeHistory) == false)
return false;
let uid: number = history.getUID();
// ALL THE SUB-TASKS ARE DONE?
for (let i: number = 0; i < this.size(); i++)
if (this.at(i)["progress_list_"].has(uid) == true)
return false; // IT'S ON A PROCESS IN SOME SYSTEM.
//--------
// RE-CALCULATE PERFORMANCE INDEX
//--------
// CONSTRUCT BASIC DATA
let system_pairs = new std.Vector<std.Pair<ParallelSystem, number>>();
let performance_index_average: number = 0.0;
for (let i: number = 0; i < this.size(); i++)
{
let system: ParallelSystem = this.at(i);
if (system["history_list_"].has(uid) == false)
continue; // NO HISTORY (HAVE NOT PARTICIPATED IN THE PARALLEL PROCESS)
// COMPUTE PERFORMANCE INDEX BASIS ON EXECUTION TIME OF THIS PARALLEL PROCESS
let my_history: PRInvokeHistory = system["history_list_"].get(uid) as PRInvokeHistory;
let performance_index: number = my_history.computeSize() / my_history.computeElapsedTime();
// PUSH TO SYSTEM PAIRS AND ADD TO AVERAGE
system_pairs.push_back(std.make_pair(system, performance_index));
performance_index_average += performance_index;
}
performance_index_average /= system_pairs.size();
// RE-CALCULATE PERFORMANCE INDEX
for (let i: number = 0; i < system_pairs.size(); i++)
{
// SYSTEM AND NEW PERFORMANCE INDEX BASIS ON THE EXECUTION TIME
let system: ParallelSystem = system_pairs.at(i).first;
if (system["enforced_"] == true)
continue; // PERFORMANCE INDEX IS ENFORCED. DOES NOT PERMIT REVALUATION
let new_performance: number = system_pairs.at(i).second / performance_index_average;
// DEDUCT RATIO TO REFLECT THE NEW PERFORMANCE INDEX -> MAXIMUM: 30%
let ordinary_ratio: number;
if (system["history_list_"].size() < 2)
ordinary_ratio = .3;
else
ordinary_ratio = Math.min(0.7, 1.0 / (system["history_list_"].size() - 1.0));
// DEFINE NEW PERFORMANCE
system.setPerformance((system.getPerformance() * ordinary_ratio) + (new_performance * (1 - ordinary_ratio)));
}
// AT LAST, NORMALIZE PERFORMANCE INDEXES OF ALL SYSTEMS
this._Normalize_performance();
return true;
}
/**
* @hidden
*/
protected _Normalize_performance(): void
{
// COMPUTE AVERAGE
let average: number = 0.0;
let denominator: number = 0;
for (let i: number = 0; i < this.size(); i++)
{
let system: ParallelSystem = this.at(i);
if (system["enforced_"] == true)
continue; // PERFORMANCE INDEX IS ENFORCED. DOES NOT PERMIT REVALUATION
average += system.getPerformance();
denominator++;
}
average /= denominator;
// DIVIDE FROM THE AVERAGE
for (let i: number = 0; i < this.size(); i++)
{
let system: ParallelSystem = this.at(i);
if (system["enforced_"] == true)
continue; // PERFORMANCE INDEX IS ENFORCED. DOES NOT PERMIT REVALUATION
system.setPerformance(system.getPerformance() / average);
}
}
} | the_stack |
import * as path from "path";
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import { PulumiApp } from "@webiny/pulumi-sdk";
// @ts-ignore
import { getLayerArn } from "@webiny/aws-layers";
import { createLambdaRole, getCommonLambdaEnvVariables } from "../lambdaUtils";
import { StorageOutput, VpcConfig } from "../common";
import { getAwsAccountId } from "../awsUtils";
interface PreRenderingServiceParams {
env: Record<string, pulumi.Input<string>>;
}
export function createPrerenderingService(app: PulumiApp, params: PreRenderingServiceParams) {
const queue = app.addResource(aws.sqs.Queue, {
name: "ps-render-queue",
config: {
visibilityTimeoutSeconds: 300,
fifoQueue: true
}
});
const policy = createLambdaPolicy(app, queue.output);
const subscriber = createRenderSubscriber(app, queue.output, policy.output, params);
const renderer = createRenderer(app, queue.output, policy.output, params);
const flush = createFlushService(app, policy.output, params);
return {
subscriber,
renderer,
flush
};
}
function createRenderSubscriber(
app: PulumiApp,
queue: pulumi.Output<aws.sqs.Queue>,
policy: pulumi.Output<aws.iam.Policy>,
params: PreRenderingServiceParams
) {
const storage = app.getModule(StorageOutput);
const role = createLambdaRole(app, {
name: "ps-render-subscriber-role",
policy: policy,
executionRole: aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole
});
const lambda = app.addResource(aws.lambda.Function, {
name: "ps-render-subscriber-lambda",
config: {
role: role.output.arn,
runtime: "nodejs14.x",
handler: "handler.handler",
timeout: 30,
memorySize: 512,
environment: {
variables: {
...getCommonLambdaEnvVariables(app),
...params.env,
SQS_QUEUE: queue.url
}
},
description: "Subscribes to render events on event bus",
code: new pulumi.asset.AssetArchive({
".": new pulumi.asset.FileArchive(
path.join(app.ctx.appDir, "prerendering/subscribe/build")
)
}),
vpcConfig: app.getModule(VpcConfig).functionVpcConfig
}
});
const eventRule = app.addResource(aws.cloudwatch.EventRule, {
name: "ps-render-subscriber-event-rule",
config: {
eventBusName: storage.eventBusArn,
eventPattern: JSON.stringify({
"detail-type": ["RenderPages"]
})
}
});
const eventPermission = app.addResource(aws.lambda.Permission, {
name: "ps-render-subscriber-event-permission",
config: {
action: "lambda:InvokeFunction",
function: lambda.output.arn,
principal: "events.amazonaws.com",
sourceArn: eventRule.output.arn
}
});
const eventTarget = app.addResource(aws.cloudwatch.EventTarget, {
name: "ps-render-subscriber-event-target",
config: {
rule: eventRule.output.name,
eventBusName: storage.eventBusArn,
arn: lambda.output.arn
}
});
return {
policy,
role,
lambda,
eventRule,
eventPermission,
eventTarget
};
}
function createRenderer(
app: PulumiApp,
queue: pulumi.Output<aws.sqs.Queue>,
policy: pulumi.Output<aws.iam.Policy>,
params: PreRenderingServiceParams
) {
const role = createLambdaRole(app, {
name: "ps-render-lambda-role",
policy: policy,
executionRole: aws.iam.ManagedPolicy.AWSLambdaSQSQueueExecutionRole
});
const lambda = app.addResource(aws.lambda.Function, {
name: "ps-render-lambda",
config: {
role: role.output.arn,
runtime: "nodejs14.x",
handler: "handler.handler",
timeout: 300,
memorySize: 2048,
layers: [getLayerArn("shelf-io-chrome-aws-lambda-layer")],
environment: {
variables: {
...getCommonLambdaEnvVariables(app),
...params.env
}
},
description: "Renders pages and stores output in an S3 bucket of choice.",
code: new pulumi.asset.AssetArchive({
".": new pulumi.asset.FileArchive(
path.join(app.ctx.appDir, "prerendering/render/build")
)
}),
vpcConfig: app.getModule(VpcConfig).functionVpcConfig
}
});
const eventSourceMapping = app.addResource(aws.lambda.EventSourceMapping, {
name: "ps-render-event-source-mapping",
config: {
functionName: lambda.output.arn,
eventSourceArn: queue.arn,
batchSize: 1
}
});
return {
policy,
role,
lambda,
eventSourceMapping
};
}
function createFlushService(
app: PulumiApp,
policy: pulumi.Output<aws.iam.Policy>,
params: PreRenderingServiceParams
) {
const storage = app.getModule(StorageOutput);
const role = createLambdaRole(app, {
name: "ps-flush-lambda-role",
policy: policy,
executionRole: aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole
});
const lambda = app.addResource(aws.lambda.Function, {
name: "ps-flush-lambda",
config: {
role: role.output.arn,
runtime: "nodejs14.x",
handler: "handler.handler",
timeout: 30,
memorySize: 512,
environment: {
variables: {
...getCommonLambdaEnvVariables(app),
...params.env
}
},
description: "Subscribes to fluhs events on event bus",
code: new pulumi.asset.AssetArchive({
".": new pulumi.asset.FileArchive(
path.join(app.ctx.appDir, "prerendering/flush/build")
)
}),
vpcConfig: app.getModule(VpcConfig).functionVpcConfig
}
});
const eventRule = app.addResource(aws.cloudwatch.EventRule, {
name: "ps-flush-event-rule",
config: {
eventBusName: storage.eventBusArn,
eventPattern: JSON.stringify({
"detail-type": ["FlushPages"]
})
}
});
const eventPermission = app.addResource(aws.lambda.Permission, {
name: "ps-flush-event-permission",
config: {
action: "lambda:InvokeFunction",
function: lambda.output.arn,
principal: "events.amazonaws.com",
sourceArn: eventRule.output.arn
}
});
const eventTarget = app.addResource(aws.cloudwatch.EventTarget, {
name: "ps-flush-event-target",
config: {
rule: eventRule.output.name,
eventBusName: storage.eventBusArn,
arn: lambda.output.arn
}
});
return {
policy,
role,
lambda,
eventRule,
eventPermission,
eventTarget
};
}
function createLambdaPolicy(app: PulumiApp, queue: pulumi.Output<aws.sqs.Queue>) {
const storage = app.getModule(StorageOutput);
const awsAccountId = getAwsAccountId(app);
return app.addResource(aws.iam.Policy, {
name: "ps-lambda-policy",
config: {
description: "This policy enables access to Lambda, S3, Cloudfront, SQS and Dynamodb",
policy: {
Version: "2012-10-17",
Statement: [
{
Sid: "PermissionForDynamodb",
Effect: "Allow",
Action: [
"dynamodb:BatchGetItem",
"dynamodb:BatchWriteItem",
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:UpdateItem"
],
Resource: storage.apply(s => {
// Add permissions to DynamoDB table
const resources = [
`${s.primaryDynamodbTableArn}`,
`${s.primaryDynamodbTableArn}/*`
];
// Attach permissions for elastic search dynamo as well (if ES is enabled).
if (s.elasticsearchDynamodbTableArn) {
resources.push(
`${s.elasticsearchDynamodbTableArn}`,
`${s.elasticsearchDynamodbTableArn}/*`
);
}
return resources;
})
},
{
Sid: "PermissionForS3",
Effect: "Allow",
Action: [
"s3:DeleteObject",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:PutObject",
"s3:PutObjectAcl"
],
Resource: [
pulumi.interpolate`arn:aws:s3:::${storage.fileManagerBucketId}/*`,
/**
* We're using the hard-coded value for "delivery" S3 bucket because;
* It is created during deployment of the `apps/website` stack which is after the api stack,
* so, we don't know its ARN.
*/
"arn:aws:s3:::delivery-*/*"
]
},
{
Sid: "PermissionForCloudfront",
Effect: "Allow",
Action: "cloudfront:CreateInvalidation",
Resource: pulumi.interpolate`arn:aws:cloudfront::${awsAccountId}:distribution/*`
},
{
Sid: "PermissionForSQS",
Effect: "Allow",
Action: ["sqs:SendMessage", "sqs:SendMessageBatch"],
Resource: queue.arn
}
]
}
}
});
} | the_stack |
import * as microsoftTeams from "@microsoft/teams-js";
import * as constants from "./constants";
import { cardTemplates, appRoot } from "./dialogs/CardTemplates";
import { taskModuleLink } from "./utils/DeepLinks";
declare var appId: any; // Injected at template render time
// Helper function for generating an adaptive card attachment
function acAttachment(ac: any): any {
return {
contentType: "application/vnd.microsoft.card.adaptive",
content: ac,
};
}
// Set the desired theme
function setTheme(theme: string): void {
if (theme) {
// Possible values for theme: 'default', 'light', 'dark' and 'contrast'
document.body.className = "theme-" + (theme === "default" ? "light" : theme);
}
}
// Create the URL that Microsoft Teams will load in the tab. You can compose any URL even with query strings.
function createTabUrl(): string {
let tabChoice = document.getElementById("tabChoice");
let selectedTab = tabChoice[(tabChoice as HTMLSelectElement).selectedIndex].value;
return window.location.protocol + "//" + window.location.host + "/" + selectedTab;
}
// Call the initialize API first
microsoftTeams.initialize();
// Check the initial theme user chose and respect it
microsoftTeams.getContext(function(context: microsoftTeams.Context): void {
if (context && context.theme) {
setTheme(context.theme);
}
});
// Handle theme changes
microsoftTeams.registerOnThemeChangeHandler(function(theme: string): void {
setTheme(theme);
});
// Save configuration changes
microsoftTeams.settings.registerOnSaveHandler(function(saveEvent: microsoftTeams.settings.SaveEvent): void {
// Let the Microsoft Teams platform know what you want to load based on
// what the user configured on this page
microsoftTeams.settings.setSettings({
contentUrl: createTabUrl(), // Mandatory parameter
entityId: createTabUrl(), // Mandatory parameter
});
// Tells Microsoft Teams platform that we are done saving our settings. Microsoft Teams waits
// for the app to call this API before it dismisses the dialog. If the wait times out, you will
// see an error indicating that the configuration settings could not be saved.
saveEvent.notifySuccess();
});
// Logic to let the user configure what they want to see in the tab being loaded
document.addEventListener("DOMContentLoaded", function(): void {
// This module runs on multiple pages, so we need to isolate page-specific logic.
// If we are on the tab configuration page, wire up the save button initialization state
let tabChoice = document.getElementById("tabChoice");
if (tabChoice) {
tabChoice.onchange = function(): void {
let selectedTab = this[(this as HTMLSelectElement).selectedIndex].value;
// This API tells Microsoft Teams to enable the 'Save' button. Since Microsoft Teams always assumes
// an initial invalid state, without this call the 'Save' button will never be enabled.
microsoftTeams.settings.setValidityState(selectedTab === "first" || selectedTab === "second" || selectedTab === "taskmodule");
};
}
// If we are on the Task Module page, initialize the buttons and deep links
let taskModuleButtons = document.getElementsByClassName("taskModuleButton");
if (taskModuleButtons.length > 0) {
// Initialize deep links
let taskInfo = {
title: null,
height: null,
width: null,
url: null,
card: null,
fallbackUrl: null,
completionBotId: null,
};
let deepLink = document.getElementById("dlYouTube") as HTMLAnchorElement;
deepLink.href = taskModuleLink(appId, constants.TaskModuleStrings.YouTubeTitle, constants.TaskModuleSizes.youtube.height, constants.TaskModuleSizes.youtube.width, `${appRoot()}/${constants.TaskModuleIds.YouTube}`, null, `${appRoot()}/${constants.TaskModuleIds.YouTube}`);
deepLink = document.getElementById("dlPowerApps") as HTMLAnchorElement;
deepLink.href = taskModuleLink(appId, constants.TaskModuleStrings.PowerAppTitle, constants.TaskModuleSizes.powerapp.height, constants.TaskModuleSizes.powerapp.width, `${appRoot()}/${constants.TaskModuleIds.PowerApp}`, null, `${appRoot()}/${constants.TaskModuleIds.PowerApp}`);
deepLink = document.getElementById("dlCustomForm") as HTMLAnchorElement;
deepLink.href = taskModuleLink(appId, constants.TaskModuleStrings.CustomFormTitle, constants.TaskModuleSizes.customform.height, constants.TaskModuleSizes.customform.width, `${appRoot()}/${constants.TaskModuleIds.CustomForm}`, null, `${appRoot()}/${constants.TaskModuleIds.CustomForm}`);
deepLink = document.getElementById("dlAdaptiveCard1") as HTMLAnchorElement;
deepLink.href = taskModuleLink(appId, constants.TaskModuleStrings.AdaptiveCardTitle, constants.TaskModuleSizes.adaptivecard.height, constants.TaskModuleSizes.adaptivecard.width, null, cardTemplates.adaptiveCard);
deepLink = document.getElementById("dlAdaptiveCard2") as HTMLAnchorElement;
deepLink.href = taskModuleLink(appId, constants.TaskModuleStrings.AdaptiveCardTitle, constants.TaskModuleSizes.adaptivecard.height, constants.TaskModuleSizes.adaptivecard.width, null, cardTemplates.adaptiveCard, null, appId);
for (let btn of taskModuleButtons) {
btn.addEventListener("click",
function (): void {
// Hide customFormResults, adaptiveResults
document.getElementById("customFormResults").style.display = "none";
document.getElementById("adaptiveResults").style.display = "none";
taskInfo.url = `${appRoot()}/${this.id.toLowerCase()}?theme={theme}`;
// Define default submitHandler()
let submitHandler = (err: string, result: any): void => { console.log(`Err: ${err}; Result: + ${result}`); };
switch (this.id.toLowerCase()) {
case constants.TaskModuleIds.YouTube:
taskInfo.title = constants.TaskModuleStrings.YouTubeTitle;
taskInfo.height = constants.TaskModuleSizes.youtube.height;
taskInfo.width = constants.TaskModuleSizes.youtube.width;
microsoftTeams.tasks.startTask(taskInfo, submitHandler);
break;
case constants.TaskModuleIds.PowerApp:
taskInfo.title = constants.TaskModuleStrings.PowerAppTitle;
taskInfo.height = constants.TaskModuleSizes.powerapp.height;
taskInfo.width = constants.TaskModuleSizes.powerapp.width;
microsoftTeams.tasks.startTask(taskInfo, submitHandler);
break;
case constants.TaskModuleIds.CustomForm:
taskInfo.title = constants.TaskModuleStrings.CustomFormTitle;
taskInfo.height = constants.TaskModuleSizes.customform.height;
taskInfo.width = constants.TaskModuleSizes.customform.width;
submitHandler = (err: string, result: any): void => {
// Unhide and populate customFormResults
let resultsElement = document.getElementById("customFormResults");
resultsElement.style.display = "block";
if (err) {
resultsElement.innerHTML = `Error/Cancel: ${err}`;
}
if (result) {
resultsElement.innerHTML = `Result: Name: "${result.name}"; Email: "${result.email}"; Favorite book: "${result.favoriteBook}"`;
}
};
microsoftTeams.tasks.startTask(taskInfo, submitHandler);
break;
case constants.TaskModuleIds.AdaptiveCard1:
taskInfo.title = constants.TaskModuleStrings.AdaptiveCardTitle;
taskInfo.url = null;
taskInfo.height = constants.TaskModuleSizes.adaptivecard.height;
taskInfo.width = constants.TaskModuleSizes.adaptivecard.width;
taskInfo.card = acAttachment(cardTemplates.adaptiveCard);
submitHandler = (err: string, result: any): void => {
// Unhide and populate adaptiveResults
let resultsElement = document.getElementById("adaptiveResults");
resultsElement.style.display = "block";
if (err) {
resultsElement.innerHTML = `Error/Cancel: ${err}`;
}
if (result) {
resultsElement.innerHTML = `Result: ${JSON.stringify(result)}`;
}
};
microsoftTeams.tasks.startTask(taskInfo, submitHandler);
break;
case constants.TaskModuleIds.AdaptiveCard2:
taskInfo.title = constants.TaskModuleStrings.AdaptiveCardTitle;
taskInfo.url = null;
taskInfo.height = constants.TaskModuleSizes.adaptivecard.height;
taskInfo.width = constants.TaskModuleSizes.adaptivecard.width;
taskInfo.card = acAttachment(cardTemplates.adaptiveCard);
// Send the Adaptive Card as filled in by the user to the bot in this app
taskInfo.completionBotId = appId;
microsoftTeams.tasks.startTask(taskInfo);
break;
default:
console.log("Unexpected button ID: " + this.id.toLowerCase());
return;
}
console.log("URL: " + taskInfo.url);
});
}
}
}); | the_stack |
import {
ActionResult,
bind,
CustomMiddleware,
DefaultFacility,
HttpCookie,
HttpStatusError,
Invocation,
invoke,
PlumierApplication,
response,
RouteInfo,
RouteMetadata,
VirtualRoute,
Class
} from "@plumier/core"
import Axios, { AxiosError } from "axios"
import crypto from "crypto"
import Csrf from "csrf"
import debug from "debug"
import { Context } from "koa"
import OAuth from "oauth-1.0a"
import qs from "querystring"
import { decorateMethod } from "@plumier/reflect"
// --------------------------------------------------------------------- //
// ------------------------------- TYPES ------------------------------- //
// --------------------------------------------------------------------- //
export enum CookieName {
csrfSecret = "plum-oauth:csrf-secret",
provider = "plum-oauth:provider"
}
export type SocialProvider = "Facebook" | "GitHub" | "Google" | "GitLab" | "Twitter"
export type OAuthVersion = "1.0a" | "2.0"
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export interface EndPoint {
endpoint: string
params: {}
}
export interface OAuthOptions {
provider: SocialProvider
clientId: string
clientSecret: string
token: EndPoint
requestToken?: EndPoint
profile: EndPoint & { transformer: (value: any) => Optional<OAuthUser, "provider"> }
login: EndPoint
oAuthVersion: OAuthVersion
}
export interface OAuthUser {
provider: SocialProvider
id: string,
name: string,
firstName: string,
lastName: string,
profilePicture: string,
email?: string,
gender?: string,
dateOfBirth?: string
}
export interface OAuthProviderOption {
clientId?: string,
clientSecret?: string,
loginEndPoint?: string,
profileParams?: {}
}
interface ParserResult {
user: Optional<OAuthUser, "provider">,
profile: any,
token: any
}
interface GeneratorResult {
redirect: string,
cookies: OAuthCookies
}
export type OAuth1Request = (opt: { url: string, method: "GET" | "POST", data: any }, token?: OAuth.Token) => Promise<any>
// --------------------------------------------------------------------- //
// ------------------------------- HELPER ------------------------------ //
// --------------------------------------------------------------------- //
const log = {
debug: debug("@plumier/social-login:debug"),
error: debug("@plumier/social-login:error")
}
export function splitName(name: string | undefined) {
if (!name) return { firstName: "", lastName: "" }
const idx = name.lastIndexOf(" ")
if (idx === -1) return { firstName: name, lastName: "" }
const lastName = name.substr(idx + 1)
const firstName = name.substring(0, idx)
return { firstName, lastName }
}
class OAuthCookies {
static async oAuth2(provider: SocialProvider) {
const csrf = new Csrf()
const secret = await csrf.secret()
return new OAuthCookies(secret, provider)
}
constructor(public secret: string, private provider: SocialProvider) { }
toHttpCookies(): HttpCookie[] {
return [
{ key: CookieName.csrfSecret, value: this.secret },
{ key: CookieName.provider, value: this.provider },
]
}
}
export function oAuth1ARequest(apiKey: string, apiKeySecret: string): OAuth1Request {
var oauth = new OAuth({
consumer: {
key: apiKey,
secret: apiKeySecret
},
signature_method: 'HMAC-SHA1',
hash_function: function (base_string, key) {
return crypto.createHmac('sha1', key).update(base_string).digest('base64');
}
});
return async ({ url, method, data }: { url: string, method: "GET" | "POST", data: any }, token?: OAuth.Token) => {
const headers:any = oauth.toHeader(oauth.authorize({ url, method, data }, token))
const resp = await Axios({ url, method, headers, data: method === "GET" ? undefined : data })
return resp.data
}
}
// --------------------------------------------------------------------- //
// ----------------------------- DECORATORS ---------------------------- //
// --------------------------------------------------------------------- //
export interface OAuthRedirectUriDecorator { name: "OAuthRedirectUriDecorator", provider: SocialProvider }
export function redirectUri(provider: SocialProvider | "General" = "General") {
return decorateMethod(<OAuthRedirectUriDecorator>{ name: "OAuthRedirectUriDecorator", provider })
}
declare module "@plumier/core" {
namespace bind {
export function oAuthUser(): (target: any, name: string, index: number) => void
export function oAuthToken(): (target: any, name: string, index: number) => void
export function oAuthProfile(): (target: any, name: string, index: number) => void
}
}
bind.oAuthUser = () => bind.custom(x => x.state.oAuthUser)
bind.oAuthToken = () => bind.custom(x => x.state.oAuthToken)
bind.oAuthProfile = () => bind.custom(x => x.state.oAuthProfile)
// --------------------------------------------------------------------- //
// ------------------------------ RESPONSE ----------------------------- //
// --------------------------------------------------------------------- //
declare module "@plumier/core" {
namespace response {
function postMessage(message: any, origin?: string): ActionResult;
}
}
response.postMessage = (message: any, origin?: string) => {
return new ActionResult(`
<!DOCTYPE html>
<html>
<title></title>
<body>
<div class="container"></div>
<script type="text/javascript">
var message = '${JSON.stringify(message)}';
var origin ${!!origin ? `= '${origin}'` : ""};
(function(){
window.onbeforeunload = function () {
window.opener.postMessage({ status: "Close" }, origin || window.location.origin);
};
window.opener.postMessage(JSON.parse(message), origin || window.location.origin);
})()
</script>
</body>
</html>
`).setHeader("Content-Type", "text/html")
}
function clientRedirect(url: string) {
// redirect client using JS to possibly set cookie before redirection
return new ActionResult(`
<!DOCTYPE html>
<html>
<title></title>
<body>
<div class="container"></div>
<script type="text/javascript">
const REDIRECT = '${url}';
(function(){
window.location.href = REDIRECT;
})()
</script>
</body>
</html>
`).setHeader("Content-Type", "text/html")
}
// --------------------------------------------------------------------- //
// ------------------------ LOGIN URL GENERATOR ------------------------ //
// --------------------------------------------------------------------- //
// oauth 2.0
async function oAuth20LoginGenerator(ctx: Context, option: OAuthOptions, redirect_uri: string): Promise<GeneratorResult> {
const params: any = { ...option.login.params, ...ctx.query }
params.redirect_uri = ctx.origin + redirect_uri
params.client_id = option.clientId
const cookies = await OAuthCookies.oAuth2(option.provider)
const csrf = new Csrf()
params.state = csrf.create(cookies.secret)
const redirect = option.login.endpoint + "?" + qs.stringify(params)
return { redirect, cookies }
}
// oauth 1.0a
async function oAuth10aLoginGenerator(ctx: Context, opt: OAuthOptions, redirectUri: string): Promise<GeneratorResult> {
const request = oAuth1ARequest(opt.clientId, opt.clientSecret)
const rawTokens = await request({
url: opt.requestToken!.endpoint,
method: "POST",
data: { oauth_callback: ctx.origin + redirectUri }
})
const reqTokens: any = qs.parse(rawTokens)
const params = { oauth_token: reqTokens.oauth_token, ...opt.login.params, ...ctx.query }
const redirect = `${opt.login.endpoint}?${qs.stringify(params)}`
const cookies = new OAuthCookies(reqTokens.oauth_token, opt.provider)
return { redirect, cookies }
}
// --------------------------------------------------------------------- //
// --------------------------- PROFILE PARSER -------------------------- //
// --------------------------------------------------------------------- //
// oauth 2.0
async function oAuth20ProfileParser(ctx: Context, option: OAuthOptions, redirect_uri: string): Promise<ParserResult> {
const req = ctx.request
const secret = ctx.cookies.get(CookieName.csrfSecret)!
if (!new Csrf().verify(secret, req.query.state as string)) {
log.error("*** Invalid csrf token ***")
log.error("CSRF Secret: %s", secret)
log.error("CSRF Token: %s", req.query.state)
throw new HttpStatusError(400)
}
const { clientId: client_id, clientSecret: client_secret } = option
// request access token
const { data: token } = await Axios.post(option.token.endpoint,
{ client_id, redirect_uri, client_secret, code: req.query.code, ...option.token.params },
{ headers: { Accept: 'application/json' } }) as any
// request profile
const { data: profile } = await Axios.get(option.profile.endpoint, {
params: option.profile.params,
headers: { Authorization: `Bearer ${token.access_token}` }
})
const user = option.profile.transformer(profile)
return { user, profile, token }
}
// oauth 1.0
async function oAuth10aProfileParser(ctx: Context, option: OAuthOptions, redirect_uri: string): Promise<ParserResult> {
const req = ctx.request
const secret = ctx.cookies.get(CookieName.csrfSecret)!
if (secret !== req.query.oauth_token) {
log.error("*** Invalid oauth_token ***")
log.error("Saved token: %s", secret)
log.error("Request token: %s", req.query.oauth_token)
throw new HttpStatusError(400)
}
const request = oAuth1ARequest(option.clientId, option.clientSecret)
const rawTokens = await request({
url: option.token.endpoint, method: "POST",
data: {
oauth_token: req.query.oauth_token,
oauth_verifier: req.query.oauth_verifier
}
})
const token: any = qs.parse(rawTokens)
const profile = await request({
url: option.profile.endpoint, method: "GET",
data: {}
}, { key: token.oauth_token, secret: token.oauth_token_secret })
const user = option.profile.transformer(profile)
return { user, profile, token }
}
// --------------------------------------------------------------------- //
// ---------------------------- MIDDLEWARES ---------------------------- //
// --------------------------------------------------------------------- //
class OAuthLoginEndPointMiddleware implements CustomMiddleware {
readonly generator = {
"1.0a": oAuth10aLoginGenerator,
"2.0": oAuth20LoginGenerator
}
constructor(private option: OAuthOptions, private loginPath: string, private redirectUri: string) { }
async execute(invocation: Readonly<Invocation>): Promise<ActionResult> {
if (invocation.ctx.path.toLowerCase() !== this.loginPath.toLowerCase()) return invocation.proceed()
const { redirect, cookies } = await this.generator[this.option.oAuthVersion](invocation.ctx,
this.option, this.redirectUri)
return clientRedirect(redirect)
.setCookie(cookies.toHttpCookies())
}
}
class OAuthRedirectUriMiddleware implements CustomMiddleware {
readonly parser = {
"1.0a": oAuth10aProfileParser,
"2.0": oAuth20ProfileParser
}
constructor(private option: OAuthOptions, private redirectUri: string) { }
async execute(inv: Readonly<Invocation>): Promise<ActionResult> {
const req = inv.ctx.request;
if (inv.ctx.state.caller === "invoke") return inv.proceed()
if (inv.ctx.path.toLocaleLowerCase() !== this.redirectUri.toLowerCase()) return inv.proceed()
const provider = inv.ctx.cookies.get(CookieName.provider)
if (provider !== this.option.provider) return inv.proceed()
log.debug("Provider: %s", this.option.provider)
const redirectUri = req.origin + req.path
try {
const result = await this.parser[this.option.oAuthVersion](inv.ctx, this.option, redirectUri)
log.debug("OAuth User: %O", result.user)
const provider = this.option.provider
inv.ctx.state.oAuthUser = { ...result.user, provider }
inv.ctx.state.oAuthToken = { ...result.token, provider }
inv.ctx.state.oAuthProfile = { ...result.profile, provider }
}
catch (e) {
log.error("*** OAuth Error ***", this.option.provider)
log.error("Auth Code: %s", req.query.code)
log.error("Redirect Uri: %s", redirectUri)
if (e.response) {
const error = (e as AxiosError)
const response = error.response!;
log.error("Request URL: %s %s", error.config.method, error.config.url)
log.error("Request Data: %o", error.config.data)
log.error("Request Headers: %o", error.config.headers)
log.error("Error: %o", { status: response.status, message: response.statusText, data: response.data })
throw new HttpStatusError(response.status, response.statusText)
}
throw e
}
return invoke(inv.ctx, inv.ctx.route!)
}
}
// --------------------------------------------------------------------- //
// ------------------------------ FACILITY ----------------------------- //
// --------------------------------------------------------------------- //
export class OAuthProviderBaseFacility extends DefaultFacility {
private option: Optional<OAuthOptions, "clientId" | "clientSecret">
private loginEndpoint: string
constructor(option: Optional<OAuthOptions, "clientId" | "clientSecret">, opt?: OAuthProviderOption) {
super()
this.option = {
...option,
clientId: opt?.clientId,
clientSecret: opt?.clientSecret,
}
if (opt && opt.profileParams)
this.option.profile.params = { ...this.option.profile.params, ...opt.profileParams }
this.loginEndpoint = opt?.loginEndPoint ?? `/auth/${this.option.provider.toLowerCase()}/login`
}
async generateRoutes(): Promise<VirtualRoute[]> {
return [{
kind: "VirtualRoute",
method: "get",
provider: this.constructor as Class,
url: this.loginEndpoint,
access: "Public",
openApiOperation: {
description: `Redirect request to ${this.option.provider} login page. This endpoint writes CSRF token on the client required to generate ${this.option.provider} login endpoint`,
tags: ["Social Login"],
parameters: [
{}
],
}
}]
}
getRedirectUri(routes: RouteMetadata[], provider: string) {
return routes.find((x): x is RouteInfo => x.kind === "ActionRoute" && x.action.decorators
.some((y: OAuthRedirectUriDecorator) => y.name === "OAuthRedirectUriDecorator" && y.provider === provider))
}
async initialize(app: Readonly<PlumierApplication>, routes: RouteMetadata[]) {
const redirectUriRoute = this.getRedirectUri(routes, this.option.provider) ?? this.getRedirectUri(routes, "General")
if (!redirectUriRoute) throw new Error(`OAuth: No ${this.option.provider} redirect uri handler found`)
if (redirectUriRoute.url.search(":") > -1) throw new Error(`OAuth: Parameterized route is not supported on ${this.option.provider} callback uri`)
if (redirectUriRoute.method !== "get") throw new Error(`OAuth: Redirect uri must have GET http method on ${redirectUriRoute.controller.name}.${redirectUriRoute.action.name}`)
const clientIdKey = `PLUM_${this.option.provider.toUpperCase()}_CLIENT_ID`
const clientSecretKey = `PLUM_${this.option.provider.toUpperCase()}_CLIENT_SECRET`
const clientId = this.option.clientId ?? process.env[clientIdKey]
if (!clientId) throw new Error(`OAuth: Client id for ${this.option.provider} not provided`)
const clientSecret = this.option.clientSecret ?? process.env[clientSecretKey]
if (!clientSecret) throw new Error(`OAuth: Client secret for ${this.option.provider} not provided`)
const option = { ...this.option, clientId, clientSecret }
app.use(new OAuthLoginEndPointMiddleware(option, this.loginEndpoint, redirectUriRoute.url))
app.use(new OAuthRedirectUriMiddleware(option, redirectUriRoute.url))
}
} | the_stack |
import { EmitType, L10n, createElement, isUndefined } from '@syncfusion/ej2-base';
import { SortOrder } from '@syncfusion/ej2-lists/src/common';
import { DataManager, ODataV4Adaptor, Query } from '@syncfusion/ej2-data';
import { DropDownBase } from '../../src/drop-down-base/drop-down-base';
import '../../node_modules/es6-promise/dist/es6-promise';
import {profile , inMB, getMemoryProfile} from '../common/common.spec';
let datasource: { [key: string]: Object }[] = [{ id: 'list1', text: 'JAVA', icon: 'icon' }, { id: 'list2', text: 'C#' },
{ id: 'list3', text: 'C++' }, { id: 'list4', text: '.NET', icon: 'icon' }, { id: 'list5', text: 'Oracle' }];
let datasource2: { [key: string]: Object }[] = [{ id: 'id2', text: 'PHP', icon: 'icon1' }, { id: 'id1', text: 'HTML', icon: 'icon1' }, { id: 'id3', text: 'PERL', icon: 'icon1' },
{ id: 'list1', text: 'JAVA', icon: 'icon1' }, { id: 'list2', text: 'Phython', icon: 'icon1' }, { id: 'list5', text: 'Oracle', icon: 'icon1' }];
L10n.load({
'fr': {
'dropdowns': {
noRecordsTemplate: "Pas de modèle d'enregistrement"
}
}
});
describe('DropDownBase', () => {
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;
}
});
//Local data bindng with default values
describe('Local data bindng with default values', () => {
let listObj: DropDownBase;
let element: HTMLElement = createElement('div', { id: 'dropdownbase' });
beforeAll(() => {
document.body.appendChild(element);
listObj = new DropDownBase({ dataSource: datasource });
listObj.appendTo(element);
(listObj as any).setZIndex();
});
afterAll(() => {
if (element) {
let parent: HTMLElement = element.parentElement as HTMLElement;
parent.remove();
}
});
/**
* initialize
*/
it('Default initialize', () => {
let next: HTMLElement = listObj.element.nextElementSibling as HTMLElement;
expect(next.childNodes.length).not.toBe(0);
expect(next.classList.contains('e-rtl')).toBe(false);
expect(listObj.itemTemplate).toBe(null);
expect(listObj.groupTemplate).toBe(null);
expect(listObj.enabled).toBe(true);
expect(listObj.dataSource).toEqual(datasource);
expect(listObj.query).toBe(null);
});
});
//Dynamic property changes
describe('Dynamic property changes', () => {
let listObj: any;
let element: HTMLElement;
beforeEach(() => {
element = createElement('div', { id: 'dropdownbase' });
document.body.appendChild(element);
listObj = new DropDownBase({ dataSource: datasource });
listObj.appendTo(element);
});
afterEach(() => {
if (element) {
let parent: HTMLElement = element.parentElement as HTMLElement;
parent.remove();
document.body.innerHTML = '';
}
});
/**
* enableRtl
*/
it('enableRtl changed', () => {
listObj.enableRtl = true;
listObj.dataBind();
expect(listObj.element.nextElementSibling.classList.contains('e-rtl')).toEqual(true);
});
/**
* enabled
*/
it('enabled behavior testing', () => {
listObj.enabled = false;
listObj.dataBind();
expect(listObj.element.getAttribute('aria-disabled')).toBe('true');
});
/**
* dataSource
*/
it('dataSource, query and sortOrder properties changes', () => {
listObj.dataSource = datasource2;
listObj.sortOrder = 'Ascending';
listObj.query = new Query().take(4);
listObj.fields = { value: 'id', text: 'text' };
listObj.dataBind();
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li.length).toEqual(4);
expect(li[0].textContent).toBe('HTML');
});
it('iconCss properties changes', () => {
listObj.dataSource = datasource2;
listObj.fields = { text: 'text', iconCss: 'icon' };
listObj.dataBind();
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect((li[0].firstChild as HTMLElement).tagName).toContain('SPAN');
});
/**
* itemTemplate
*/
it('itemTemplate property', () => {
listObj.fields = { text: 'text', iconCss: 'icon' };
listObj.itemTemplate = '<div class="demo"> ${text} </div><div class="id"> ${id} </div>';
listObj.dataBind();
let eles: Element = listObj.element.nextElementSibling;
let item: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>eles.querySelectorAll('.e-list-item');
expect(item[0].firstElementChild.classList.contains('demo')).toBe(true);
});
/**
* locale
*/
it('locale property', () => {
let data: { [key: string]: Object }[] = [];
listObj.dataSource = data;
listObj.dataBind();
listObj.locale = 'fr';
listObj.dataBind();
expect(listObj.locale).toBe('fr');
expect(listObj.list.innerHTML).toBe("Pas de modèle d'enregistrement");
listObj.noRecordsTemplate = 'Empty data source';
listObj.locale = 'en-US';
listObj.dataBind();
expect(listObj.noRecordsTemplate).toBe('Empty data source');
element.parentElement.remove();
document.body.innerHTML = '';
});
});
// HTMLData Binding
describe('HTMLData data binding', () => {
let ele: HTMLElement = document.createElement('ul');
ele.id = 'newlist';
ele.innerHTML = '<li id="i1">item1</li>' +
'<li id="i2">item2</li><li id="i3">item3</li><li id="i4">item4</li><li id="i5">item5</li>' +
'<li>item6</li><li>item7</li>';
let nTree: DropDownBase;
beforeAll(() => {
document.body.appendChild(ele);
nTree = new DropDownBase();
nTree.appendTo('#newlist');
});
afterAll(() => {
if (ele) {
let parent: HTMLElement = ele.parentElement as HTMLElement;
parent.remove();
document.body.innerText = '';
}
})
/**
* initialize
*/
it('initialized HTML data', () => {
expect(ele.nextElementSibling.querySelectorAll('.e-list-item').length).toBe(7);
});
});
describe('Remote Data Binding', () => {
describe('default query', () => {
let ele: HTMLElement = document.createElement('div');
ele.appendChild(document.createElement('ul'));
ele.id = 'newTree';
let nTree: DropDownBase;
beforeAll(() => {
document.body.appendChild(ele);
});
it('initialized HTML data', (done) => {
nTree = new DropDownBase({
dataSource: new DataManager({
url: '/api/Employees',
adaptor: new ODataV4Adaptor
}),
fields: { value: 'EmployeeID', text: 'FirstName' },
actionComplete: (e: any) => {
expect(e.result.length).toBe(9);
}
});
nTree.appendTo('#newTree');
setTimeout(done, 800);
});
afterAll(() => {
if (ele) ele.parentElement.remove();
});
});
});
// Method testing
describe('method testing ', () => {
let listObj: any;
let element: HTMLElement
beforeEach(() => {
element = createElement('div', { id: 'dropdownbase' });
document.body.appendChild(element);
listObj = new DropDownBase({ dataSource: datasource });
listObj.appendTo(element);
});
afterEach(() => {
if (element) {
let parent: HTMLElement = element.parentElement as HTMLElement;
parent.remove();
};
document.body.innerHTML = '';
});
/**
* getModuleName
*/
it('getModuleName method', () => {
let name: string = listObj.getModuleName();
expect(name).toEqual('dropdownbase');
});
/**
* getPersistData
*/
it('getPersistData method ', () => {
let stringItems: any = listObj.getPersistData();
expect(stringItems.search('value')).toBe(-1);
});
/**
* addItem
*/
it('addItem method', () => {
listObj.addItem([{ id: 'list3', text: 'HTML' }, { id: 'list4', text: 'PHP' }], 2);
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[2].textContent).toEqual('HTML');
expect(listObj.liCollections[2].textContent).toEqual('HTML');
});
/**
* addItem with single arg
*/
it('addItem method without index', () => {
let select: Element = listObj.element.nextElementSibling.querySelector('li').classList.add('e-active');
listObj.addItem([{ id: 'list5', text: 'C' }, { id: 'list6', text: 'NewItem' }]);
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[li.length - 1].textContent).toEqual('NewItem');
expect(listObj.liCollections[li.length - 1].textContent).toEqual('NewItem');
});
/**
* addItem while datasource empty.
*/
it('addItem while datasource empty', () => {
listObj.dataSource = [];
listObj.dataBind();
listObj.addItem([{ id: 'list7', text: 'Oops' }]);
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[0].textContent).toEqual('Oops');
});
it('addItem with high index length', () => {
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
listObj.addItem([{ id: 'list7', text: 'Oops' }], 20);
let li1: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li1[li1.length - 1].textContent).toEqual('Oops');
});
it('addItem as non array', () => {
listObj.addItem({ id: 'list90', text: 'Oops1' });
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[li.length - 1].textContent).toEqual('Oops1');
});
/**
* getItems
*/
it('getItems method', () => {
let items: any = listObj.getItems();
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(items.length).toEqual(li.length);
});
/**
* destroy
*/
it('destroy method ', () => {
listObj.destroy();
expect(!(listObj.element.nextElementSibling)).toBe(true);
document.body.innerHTML = '';
});
/**
* getIndexByvalue
*/
it('getIndexByvalue method ', () => {
var index = listObj.getIndexByValue('C++');
expect(index).toEqual(2);
});
});
// Action events
describe('Events', () => {
describe('Action events ', () => {
let beginAction: EmitType<Object> = jasmine.createSpy('actionBegin');
let ele: HTMLElement = document.createElement('div');
ele.appendChild(document.createElement('ul'));
ele.id = 'newlist';
let list: any;
beforeAll(() => {
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) { ele.parentElement.remove(); };
jasmine.Ajax.uninstall();
});
/**
* actionComplete
*/
it('actionComplete events triggered', (done) => {
list = new DropDownBase({
dataSource: new DataManager({ url: '/api/Employees', adaptor: new ODataV4Adaptor }),
fields: { text: 'FirstName' },
actionBegin: beginAction,
actionComplete: (e: any) => {
expect(e.result.length).toBe(9);
}
});
list.appendTo('#newlist');
setTimeout(done, 800);
});
/**
* actionBegin
*/
it('actionBegin event triggered', () => {
expect(beginAction).toHaveBeenCalled();
});
});
describe('No data with remote ', () => {
let beginAction: EmitType<Object> = jasmine.createSpy('actionBegin');
let ele: HTMLElement = document.createElement('div');
ele.appendChild(document.createElement('ul'));
ele.id = 'newlist';
let list: any;
beforeAll(() => {
document.body.appendChild(ele);
});
afterAll(() => {
if (ele) { ele.parentElement.remove(); };
jasmine.Ajax.uninstall();
});
/**
* actionComplete
*/
it('noRecordsTemplate', (done) => {
list = new DropDownBase({
dataSource: new DataManager({ url: '/api/Employees', adaptor: new ODataV4Adaptor }),
fields: { text: 'FirstName' },
actionBegin: beginAction,
actionComplete: (e: any) => {
e.result = [];
}
});
list.appendTo('#newlist');
setTimeout(() => {
expect(ele.nextElementSibling.querySelectorAll('li').length).toBe(0);
expect(list.list.innerHTML).toBe('No records found');
done();
}, 800);
});
});
describe('actionFailure event', () => {
let actionFailedFunction: EmitType<Object> = jasmine.createSpy('actionFailure');
let ele: HTMLElement = document.createElement('div');
ele.appendChild(document.createElement('ul'));
ele.id = 'newTree';
let listObj: any;
beforeAll((done) => {
jasmine.Ajax.install();
document.body.appendChild(ele);
listObj = new DropDownBase({
dataSource: new DataManager({
url: '/test/db',
adaptor: new ODataV4Adaptor
}),
fields: { value: 'EmployeeID', text: 'FirstName' },
actionFailure: actionFailedFunction
});
listObj.appendTo('#newTree');
setTimeout(done, 800);
});
beforeEach((done: Function) => {
let request: JasmineAjaxRequest = jasmine.Ajax.requests.mostRecent();
request.respondWith({
'status': 404,
'contentType': 'application/json',
'responseText': 'Page not found'
});
setTimeout(() => { done(); }, 100);
});
it('initialized HTML data', () => {
expect(actionFailedFunction).toHaveBeenCalled();
expect(listObj.list.textContent).toBe(listObj.actionFailureTemplate);
});
afterAll(() => {
ele.remove();
jasmine.Ajax.uninstall();
});
});
});
describe('Template', () => {
let listObj: any;
let element: HTMLElement;
let datasource1: { [key: string]: Object }[] = [{ 'text': 'Audi A6', 'id': 'e807', 'category': 'Audi' }, { 'text': 'Audi A7', 'id': 'a0cc', 'category': 'Audi' },
{ 'text': 'BMW 501', 'id': 'f8435', 'category': 'BMW' }, { 'text': 'BMW 3', 'id': 'b2b1', 'category': 'BMW' }];
beforeEach(() => {
element = createElement('div', { id: 'dropdownbase', attrs: { 'tabindex': '1' } });
document.body.appendChild(element);
});
afterEach(() => {
if (element) {
element.parentElement.remove();
document.body.innerHTML = '';
}
});
/**
* itemTemplate
*/
it('itemTemplate with category ', (done) => {
listObj = new DropDownBase({
dataSource: datasource1,
fields: { groupBy: 'category' },
itemTemplate: '<div class="ename"> ${text} </div><div class="desig"> ${id} </div>',
});
listObj.appendTo(element);
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[0].classList.contains('e-list-group-item')).toBe(true);
expect(ele.querySelector('ul').firstChild.textContent).toBe('Audi');
listObj.element.nextElementSibling.style.overflow = "auto";
listObj.element.nextElementSibling.style.height = '80px';
listObj.dataBind();
listObj.list.scrollTop = ele.scrollHeight;
setTimeout(() => {
listObj.list.scrollTop = 0;
setTimeout(() => {
expect(listObj.list.firstChild.textContent).toBe('Audi');
done();
}, 101);
}, 500);
});
/**
* itemTemplate
*/
it('itemTemplate with sorting', () => {
listObj = new DropDownBase({
dataSource: datasource, sortOrder: 'Ascending',
fields: { value: 'text' },
itemTemplate: '<div class="ename"> ${text} </div><div class="desig"> ${id} </div>',
});
listObj.appendTo(element);
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[0].getAttribute('data-value')).toEqual('.NET');
});
/**
* groupTemplate
*/
it('groupBy & groupTemplate', () => {
let grpList: DropDownBase = new DropDownBase({
dataSource: datasource1, fields: { groupBy: 'category', value: 'id', text: 'text' },
groupTemplate: '<div class="category"> ${text} </div><div class="design"> </div> '
});
grpList.appendTo('#dropdownbase');
let ele: Element = grpList.element.nextElementSibling;
let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('.e-list-group-item');
expect(li[0].firstElementChild.classList.contains('category')).toBe(true);
});
it('groupBy & SortOrder', () => {
let datasource9: { [key: string]: Object }[] = [{ 'text': 'Audi A7', 'id': 'e807', 'category': 'Audi' },
{ 'text': 'Audi A6', 'id': 'a0cc', 'category': 'Audi' },
{ 'text': 'BMW 501', 'id': 'f8435', 'category': 'BMW' }, { 'text': 'BMW 3', 'id': 'b2b1', 'category': 'BMW' }];
let grpList: DropDownBase = new DropDownBase({
dataSource: datasource9, fields: { groupBy: 'category', value: 'id', text: 'text' },
sortOrder: 'Ascending'
});
grpList.appendTo('#dropdownbase');
let ele: Element = grpList.element.nextElementSibling;
let li: Element = <Element & HTMLLIElement>ele.querySelector('.e-list-item');
expect(li.innerHTML).toEqual('Audi A6');
});
it('groupBy & SortOrder & itemtemplate', () => {
let datasource9: { [key: string]: Object }[] = [{ 'text': 'Audi A7', 'id': 'e807', 'category': 'Audi' },
{ 'text': 'Audi A6', 'id': 'a0cc', 'category': 'Audi' },
{ 'text': 'BMW 501', 'id': 'f8435', 'category': 'BMW' }, { 'text': 'BMW 3', 'id': 'b2b1', 'category': 'BMW' }];
let grpList: DropDownBase = new DropDownBase({
dataSource: datasource9, fields: { groupBy: 'category', value: 'id', text: 'text' },
sortOrder: 'Ascending',
itemTemplate: '<div class="ename">${text}</div><div class="desig"> ${id} </div>',
});
grpList.appendTo('#dropdownbase');
let ele: Element = grpList.element.nextElementSibling;
let li: Element = <Element & HTMLLIElement>ele.querySelector('.ename');
expect(li.innerHTML).toEqual('Audi A6');
});
/**
* groupTemplate
*/
it('groupBy with dynamic groupTemplate', () => {
let grpList: DropDownBase = new DropDownBase({ dataSource: datasource1, fields: { groupBy: 'category', value: 'id' } });
grpList.appendTo('#dropdownbase');
let ele: Element = grpList.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('.e-list-group-item');
expect(li.length).toEqual(2);
grpList.groupTemplate = '<div class="category"> ${category} </div><div class="design"> </div> ';
grpList.dataBind();
expect(li[0].firstElementChild.classList.contains('category')).toBe(true);
});
});
describe('Floating header', () => {
let listObj: any;
let element: HTMLElement;
let datasource1: { [key: string]: Object }[] = [{ 'text': 'Audi A6', 'id': 'e807', 'category': 'Audi' }, { 'text': 'Audi A7', 'id': 'a0cc', 'category': 'Audi' },
{ 'text': 'BMW 501', 'id': 'f8435', 'category': 'BMW' }, { 'text': 'BMW 3', 'id': 'b2b1', 'category': 'BMW' }];
beforeEach(() => {
element = createElement('div', { id: 'dropdownbase', attrs: { 'tabindex': '1' } });
document.body.appendChild(element);
});
afterEach(() => {
if (element) {
element.parentElement.remove();
document.body.innerHTML = '';
}
});
/**
* itemTemplate
*/
it('itemTemplate with groupBy ', (done) => {
listObj = new DropDownBase({
dataSource: datasource1,
fields: { groupBy: 'category', text: 'text' },
itemTemplate: '<div class="ename"> ${text} </div><div class="desig"> ${id} </div>',
});
listObj.appendTo(element);
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[0].classList.contains('e-list-group-item')).toBe(true);
expect(ele.querySelector('ul').firstChild.textContent).toBe('Audi');
listObj.element.nextElementSibling.style.overflow = "scroll";
listObj.element.nextElementSibling.style.height = '80px';
listObj.dataBind();
listObj.list.scrollTop = ele.scrollHeight;
setTimeout(() => {
listObj.list.scrollTop = 0;
setTimeout(() => {
expect(listObj.list.firstChild.textContent).toBe('Audi');
done();
}, 400);
}, 400);
});
it('Floating header', (done) => {
listObj = new DropDownBase({
dataSource: datasource1,
fields: { groupBy: 'category', text: 'text', value: 'id' }
});
listObj.appendTo(element);
let ele: Element = listObj.element.nextElementSibling;
let li: Element[] & NodeListOf<HTMLLIElement> = <Element[] & NodeListOf<HTMLLIElement>>ele.querySelectorAll('li');
expect(li[0].classList.contains('e-list-group-item')).toBe(true);
expect(ele.querySelector('ul').firstChild.textContent).toBe('Audi');
listObj.element.nextElementSibling.style.overflow = "auto";
listObj.element.nextElementSibling.style.height = '80px';
listObj.dataBind();
listObj.list.scrollTop = ele.scrollHeight;
setTimeout(() => {
listObj.list.scrollTop = 0;
setTimeout(() => {
expect(listObj.fixedHeaderElement.innerText).toBe('Audi');
listObj.scrollTimer = 1;
listObj.groupTemplate = '<h3 class="ecategory"> ${category} </h3>';
setTimeout(() => {
expect(listObj.fixedHeaderElement.firstElementChild.tagName).toBe('H3');
done();
}, 200);
}, 200);
}, 200);
});
it('getDataByValue method for Object dataSource', () => {
listObj = new DropDownBase({
dataSource: datasource1,
fields: { groupBy: 'category', text: 'text', value: 'id' }
});
listObj.appendTo(element);
let ele: Element = listObj.element.nextElementSibling;
let data = listObj.getDataByValue('e807');
expect(data.text).toBe('Audi A6');
let data1 = listObj.getDataByValue('e8071');
expect(data1).toBe(null);
});
it('getDataByValue method for string array dataSource', () => {
let items: string[] = ['FootBall', 'Cricket', 'ValleyBall', 'Tennis'];
listObj = new DropDownBase({ dataSource: items });
listObj.appendTo(element);
let ele: Element = listObj.element.nextElementSibling;
let data = listObj.getDataByValue('Cricket');
expect(data).toBe('Cricket');
});
});
describe("select element Rendering", () => {
let listObj: any;
let element: string = "<select id='select1'><option>option1</option><option value='option2'>option2</option></select>";
let groupelement: string = "<select id='select2'><optgroup label='option'><option>option1</option><option value='option2'>option2</option></optgroup><option>option3</option></select>";
afterAll(() => {
let groupselect: HTMLSelectElement = document.getElementById('select2') as HTMLSelectElement;
let select: HTMLSelectElement = document.getElementById('select1') as HTMLSelectElement;
if (select) {
let parent: HTMLElement = select.parentElement as HTMLElement;
parent.remove();
}
if (groupselect) {
let parent: HTMLElement = groupselect.parentElement as HTMLElement;
parent.remove();
}
});
/**
* Select Rendering
*/
it('Select Rendering with options only', () => {
document.body.innerHTML = element;
let select: HTMLSelectElement = document.getElementById('select1') as HTMLSelectElement;
listObj = new DropDownBase();
listObj.appendTo(select);
let ele: HTMLElement = select.nextElementSibling as HTMLElement;
expect(ele.querySelectorAll('li').length).toBe(2);
expect(ele.querySelectorAll('li')[0].innerText).toBe('option1');
expect(ele.querySelectorAll('li')[0].getAttribute('data-value')).toBe('option1');
expect(ele.querySelectorAll('li')[1].getAttribute('data-value')).toBe('option2');
});
it('Select Rendering with options and optgroup', (done) => {
document.body.innerHTML = groupelement;
let groupselect: HTMLSelectElement = document.getElementById('select2') as HTMLSelectElement;
listObj = new DropDownBase();
listObj.appendTo(groupselect);
let ele: HTMLElement = groupselect.nextElementSibling as HTMLElement;
expect(ele.querySelectorAll('li').length).toBe(4);
expect(ele.querySelectorAll('li')[0].innerText).toBe('option3');
expect(ele.querySelectorAll('li')[1].classList).toContain('e-list-group-item');
expect(ele.querySelectorAll('li')[2].getAttribute('data-value')).toBe('option1');
expect(ele.querySelectorAll('li')[3].getAttribute('data-value')).toBe('option2');
expect(ele.querySelectorAll('li')[3].textContent).toBe('option2');
listObj.list.style.overflow = "auto";
listObj.list.style.height = '60px';
listObj.list.scrollTop = 30;
setTimeout(() => {
expect(listObj.fixedHeaderElement.style.display).toBe('block');
listObj.scrollTimer = 1;
done();
}, 50);
});
});
describe('boolean array datasource', () => {
let listObj: DropDownBase;
let element: HTMLElement = createElement('div', { id: 'dropdownbase' });
let booleanArray = [ false, true ];
beforeAll(() => {
document.body.appendChild(element);
listObj = new DropDownBase({ dataSource: booleanArray });
listObj.appendTo(element);
(listObj as any).setZIndex();
});
afterAll(() => {
if (element) {
let parent: HTMLElement = element.parentElement as HTMLElement;
parent.remove();
}
});
/**
* initialize
*/
it('Boolean Array list initialize', () => {
let next: HTMLUListElement = listObj.element.nextElementSibling.children[0] as HTMLUListElement;
(<any>listObj).updateListValues();
expect(listObj.getDataByValue(true)).toBe(true);
//expect();
});
});
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);
})
});
//Dummy spec updateDataList method
describe('Spec for empty method ', () => {
let listObj: any;
let element: HTMLElement
beforeEach(() => {
element = createElement('div', { id: 'dropdownbase' });
document.body.appendChild(element);
});
afterEach(() => {
if (element) {
let parent: HTMLElement = element.parentElement as HTMLElement;
parent.remove();
};
document.body.innerHTML = '';
});
it('addItem method', () => {
listObj = new DropDownBase({ dataSource: datasource });
listObj.appendTo(element);
listObj.updateDataList();
});
}); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import {
DetectorResponse,
DiagnosticsListHostingEnvironmentDetectorResponsesOptionalParams,
DiagnosticsListSiteDetectorResponsesOptionalParams,
DiagnosticCategory,
DiagnosticsListSiteDiagnosticCategoriesOptionalParams,
AnalysisDefinition,
DiagnosticsListSiteAnalysesOptionalParams,
DetectorDefinitionResource,
DiagnosticsListSiteDetectorsOptionalParams,
DiagnosticsListSiteDetectorResponsesSlotOptionalParams,
DiagnosticsListSiteDiagnosticCategoriesSlotOptionalParams,
DiagnosticsListSiteAnalysesSlotOptionalParams,
DiagnosticsListSiteDetectorsSlotOptionalParams,
DiagnosticsGetHostingEnvironmentDetectorResponseOptionalParams,
DiagnosticsGetHostingEnvironmentDetectorResponseResponse,
DiagnosticsGetSiteDetectorResponseOptionalParams,
DiagnosticsGetSiteDetectorResponseResponse,
DiagnosticsGetSiteDiagnosticCategoryOptionalParams,
DiagnosticsGetSiteDiagnosticCategoryResponse,
DiagnosticsGetSiteAnalysisOptionalParams,
DiagnosticsGetSiteAnalysisResponse,
DiagnosticsExecuteSiteAnalysisOptionalParams,
DiagnosticsExecuteSiteAnalysisResponse,
DiagnosticsGetSiteDetectorOptionalParams,
DiagnosticsGetSiteDetectorResponse,
DiagnosticsExecuteSiteDetectorOptionalParams,
DiagnosticsExecuteSiteDetectorResponse,
DiagnosticsGetSiteDetectorResponseSlotOptionalParams,
DiagnosticsGetSiteDetectorResponseSlotResponse,
DiagnosticsGetSiteDiagnosticCategorySlotOptionalParams,
DiagnosticsGetSiteDiagnosticCategorySlotResponse,
DiagnosticsGetSiteAnalysisSlotOptionalParams,
DiagnosticsGetSiteAnalysisSlotResponse,
DiagnosticsExecuteSiteAnalysisSlotOptionalParams,
DiagnosticsExecuteSiteAnalysisSlotResponse,
DiagnosticsGetSiteDetectorSlotOptionalParams,
DiagnosticsGetSiteDetectorSlotResponse,
DiagnosticsExecuteSiteDetectorSlotOptionalParams,
DiagnosticsExecuteSiteDetectorSlotResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a Diagnostics. */
export interface Diagnostics {
/**
* Description for List Hosting Environment Detector Responses
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param name Site Name
* @param options The options parameters.
*/
listHostingEnvironmentDetectorResponses(
resourceGroupName: string,
name: string,
options?: DiagnosticsListHostingEnvironmentDetectorResponsesOptionalParams
): PagedAsyncIterableIterator<DetectorResponse>;
/**
* Description for List Site Detector Responses
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param options The options parameters.
*/
listSiteDetectorResponses(
resourceGroupName: string,
siteName: string,
options?: DiagnosticsListSiteDetectorResponsesOptionalParams
): PagedAsyncIterableIterator<DetectorResponse>;
/**
* Description for Get Diagnostics Categories
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param options The options parameters.
*/
listSiteDiagnosticCategories(
resourceGroupName: string,
siteName: string,
options?: DiagnosticsListSiteDiagnosticCategoriesOptionalParams
): PagedAsyncIterableIterator<DiagnosticCategory>;
/**
* Description for Get Site Analyses
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param options The options parameters.
*/
listSiteAnalyses(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
options?: DiagnosticsListSiteAnalysesOptionalParams
): PagedAsyncIterableIterator<AnalysisDefinition>;
/**
* Description for Get Detectors
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param options The options parameters.
*/
listSiteDetectors(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
options?: DiagnosticsListSiteDetectorsOptionalParams
): PagedAsyncIterableIterator<DetectorDefinitionResource>;
/**
* Description for List Site Detector Responses
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param slot Slot Name
* @param options The options parameters.
*/
listSiteDetectorResponsesSlot(
resourceGroupName: string,
siteName: string,
slot: string,
options?: DiagnosticsListSiteDetectorResponsesSlotOptionalParams
): PagedAsyncIterableIterator<DetectorResponse>;
/**
* Description for Get Diagnostics Categories
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param slot Slot Name
* @param options The options parameters.
*/
listSiteDiagnosticCategoriesSlot(
resourceGroupName: string,
siteName: string,
slot: string,
options?: DiagnosticsListSiteDiagnosticCategoriesSlotOptionalParams
): PagedAsyncIterableIterator<DiagnosticCategory>;
/**
* Description for Get Site Analyses
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param slot Slot Name
* @param options The options parameters.
*/
listSiteAnalysesSlot(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
slot: string,
options?: DiagnosticsListSiteAnalysesSlotOptionalParams
): PagedAsyncIterableIterator<AnalysisDefinition>;
/**
* Description for Get Detectors
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param slot Slot Name
* @param options The options parameters.
*/
listSiteDetectorsSlot(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
slot: string,
options?: DiagnosticsListSiteDetectorsSlotOptionalParams
): PagedAsyncIterableIterator<DetectorDefinitionResource>;
/**
* Description for Get Hosting Environment Detector Response
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param name App Service Environment Name
* @param detectorName Detector Resource Name
* @param options The options parameters.
*/
getHostingEnvironmentDetectorResponse(
resourceGroupName: string,
name: string,
detectorName: string,
options?: DiagnosticsGetHostingEnvironmentDetectorResponseOptionalParams
): Promise<DiagnosticsGetHostingEnvironmentDetectorResponseResponse>;
/**
* Description for Get site detector response
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param detectorName Detector Resource Name
* @param options The options parameters.
*/
getSiteDetectorResponse(
resourceGroupName: string,
siteName: string,
detectorName: string,
options?: DiagnosticsGetSiteDetectorResponseOptionalParams
): Promise<DiagnosticsGetSiteDetectorResponseResponse>;
/**
* Description for Get Diagnostics Category
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param options The options parameters.
*/
getSiteDiagnosticCategory(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
options?: DiagnosticsGetSiteDiagnosticCategoryOptionalParams
): Promise<DiagnosticsGetSiteDiagnosticCategoryResponse>;
/**
* Description for Get Site Analysis
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param analysisName Analysis Name
* @param options The options parameters.
*/
getSiteAnalysis(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
analysisName: string,
options?: DiagnosticsGetSiteAnalysisOptionalParams
): Promise<DiagnosticsGetSiteAnalysisResponse>;
/**
* Description for Execute Analysis
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Category Name
* @param analysisName Analysis Resource Name
* @param options The options parameters.
*/
executeSiteAnalysis(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
analysisName: string,
options?: DiagnosticsExecuteSiteAnalysisOptionalParams
): Promise<DiagnosticsExecuteSiteAnalysisResponse>;
/**
* Description for Get Detector
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param detectorName Detector Name
* @param options The options parameters.
*/
getSiteDetector(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
detectorName: string,
options?: DiagnosticsGetSiteDetectorOptionalParams
): Promise<DiagnosticsGetSiteDetectorResponse>;
/**
* Description for Execute Detector
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param detectorName Detector Resource Name
* @param diagnosticCategory Category Name
* @param options The options parameters.
*/
executeSiteDetector(
resourceGroupName: string,
siteName: string,
detectorName: string,
diagnosticCategory: string,
options?: DiagnosticsExecuteSiteDetectorOptionalParams
): Promise<DiagnosticsExecuteSiteDetectorResponse>;
/**
* Description for Get site detector response
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param detectorName Detector Resource Name
* @param slot Slot Name
* @param options The options parameters.
*/
getSiteDetectorResponseSlot(
resourceGroupName: string,
siteName: string,
detectorName: string,
slot: string,
options?: DiagnosticsGetSiteDetectorResponseSlotOptionalParams
): Promise<DiagnosticsGetSiteDetectorResponseSlotResponse>;
/**
* Description for Get Diagnostics Category
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param slot Slot Name
* @param options The options parameters.
*/
getSiteDiagnosticCategorySlot(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
slot: string,
options?: DiagnosticsGetSiteDiagnosticCategorySlotOptionalParams
): Promise<DiagnosticsGetSiteDiagnosticCategorySlotResponse>;
/**
* Description for Get Site Analysis
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param analysisName Analysis Name
* @param slot Slot - optional
* @param options The options parameters.
*/
getSiteAnalysisSlot(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
analysisName: string,
slot: string,
options?: DiagnosticsGetSiteAnalysisSlotOptionalParams
): Promise<DiagnosticsGetSiteAnalysisSlotResponse>;
/**
* Description for Execute Analysis
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Category Name
* @param analysisName Analysis Resource Name
* @param slot Slot Name
* @param options The options parameters.
*/
executeSiteAnalysisSlot(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
analysisName: string,
slot: string,
options?: DiagnosticsExecuteSiteAnalysisSlotOptionalParams
): Promise<DiagnosticsExecuteSiteAnalysisSlotResponse>;
/**
* Description for Get Detector
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param diagnosticCategory Diagnostic Category
* @param detectorName Detector Name
* @param slot Slot Name
* @param options The options parameters.
*/
getSiteDetectorSlot(
resourceGroupName: string,
siteName: string,
diagnosticCategory: string,
detectorName: string,
slot: string,
options?: DiagnosticsGetSiteDetectorSlotOptionalParams
): Promise<DiagnosticsGetSiteDetectorSlotResponse>;
/**
* Description for Execute Detector
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param siteName Site Name
* @param detectorName Detector Resource Name
* @param diagnosticCategory Category Name
* @param slot Slot Name
* @param options The options parameters.
*/
executeSiteDetectorSlot(
resourceGroupName: string,
siteName: string,
detectorName: string,
diagnosticCategory: string,
slot: string,
options?: DiagnosticsExecuteSiteDetectorSlotOptionalParams
): Promise<DiagnosticsExecuteSiteDetectorSlotResponse>;
} | the_stack |
import { TypesAwareObjectMapper } from "../../Mapping/ObjectMapper";
import {
DocumentType,
} from "../DocumentAbstractions";
import {
ObjectTypeDescriptor,
ObjectLiteralDescriptor,
ClassConstructor, EntityConstructor, Field
} from "../../Types";
import * as pluralize from "pluralize";
import { ClientConfiguration } from "../Operations/Configuration/ClientConfiguration";
import { ReadBalanceBehavior } from "../../Http/ReadBalanceBehavior";
import { throwError } from "../../Exceptions";
import { CONSTANTS } from "../../Constants";
import { TypeUtil } from "../../Utility/TypeUtil";
import { DateUtil, DateUtilOpts } from "../../Utility/DateUtil";
import { CasingConvention, ObjectUtil, ObjectChangeCaseOptions } from "../../Utility/ObjectUtil";
import { LoadBalanceBehavior } from "../../Http/LoadBalanceBehavior";
import { BulkInsertConventions } from "./BulkInsertConventions";
import { InMemoryDocumentSessionOperations } from "../Session/InMemoryDocumentSessionOperations";
export type IdConvention = (databaseName: string, entity: object) => Promise<string>;
export type IValueForQueryConverter<T> =
(fieldName: Field<T>, value: T, forRange: boolean, stringValue: (value: any) => void) => boolean;
function createServerDefaults() {
const conventions = new DocumentConventions();
conventions.sendApplicationIdentifier = false;
conventions.freeze();
return conventions;
}
export class DocumentConventions {
private static _defaults: DocumentConventions = new DocumentConventions();
public static defaultForServerConventions = createServerDefaults();
public static get defaultConventions() {
return this._defaults;
}
private static _cachedDefaultTypeCollectionNames: Map<ObjectTypeDescriptor, string> = new Map();
private readonly _listOfQueryValueToObjectConverters:
{ Type: EntityConstructor<any>; Converter: IValueForQueryConverter<any> }[] = [];
private _registeredIdConventions:
Map<ObjectTypeDescriptor, IdConvention> = new Map();
private _registeredIdPropertyNames:
Map<ObjectTypeDescriptor, string> = new Map();
private _frozen: boolean;
private _originalConfiguration: ClientConfiguration;
private _identityPartsSeparator: string;
private _disableTopologyUpdates: boolean;
private _disableAtomicDocumentWritesInClusterWideTransaction: boolean;
private _shouldIgnoreEntityChanges: (sessionOperations: InMemoryDocumentSessionOperations, entity: object, documentId: string) => boolean;
private _transformClassCollectionNameToDocumentIdPrefix: (maybeClassCollectionName: string) => string;
private _documentIdGenerator: IdConvention;
private _loadBalancerPerSessionContextSelector: (databaseName: string) => string;
private _findCollectionName: (constructorOrTypeChecker: ObjectTypeDescriptor) => string;
private _identityProperty: string;
private _findJsTypeName: (ctorOrTypeChecker: ObjectTypeDescriptor) => string;
private _findJsType: (id: string, doc: object) => ObjectTypeDescriptor;
private _useOptimisticConcurrency: boolean;
private _throwIfQueryPageSizeIsNotSet: boolean;
private _maxNumberOfRequestsPerSession: number;
private _requestTimeout: number | undefined;
private _firstBroadcastAttemptTimeout: number | undefined;
private _secondBroadcastAttemptTimeout: number | undefined;
private _waitForIndexesAfterSaveChangesTimeout: number | undefined;
private _waitForReplicationAfterSaveChangesTimeout: number | undefined;
private _waitForNonStaleResultsTimeout: number | undefined;
private _loadBalancerContextSeed: number;
private _loadBalanceBehavior: LoadBalanceBehavior;
private _readBalanceBehavior: ReadBalanceBehavior;
private _maxHttpCacheSize: number;
private readonly _knownEntityTypes: Map<string, ObjectTypeDescriptor>;
private _localEntityFieldNameConvention: CasingConvention;
private _remoteEntityFieldNameConvention: CasingConvention;
private _objectMapper: TypesAwareObjectMapper;
private _dateUtil: DateUtil;
private _syncJsonParseLimit: number;
private _useCompression: boolean;
private _sendApplicationIdentifier: boolean;
private readonly _bulkInsert: BulkInsertConventions;
public get bulkInsert() {
return this._bulkInsert;
}
public constructor() {
this._readBalanceBehavior = "None";
this._identityPartsSeparator = "/";
this._identityProperty = CONSTANTS.Documents.Metadata.ID_PROPERTY;
this._findJsType = (id: string, doc: object) => {
const metadata = doc[CONSTANTS.Documents.Metadata.KEY];
if (metadata) {
const jsType = metadata[CONSTANTS.Documents.Metadata.RAVEN_JS_TYPE] as string;
return this.getJsTypeByDocumentType(jsType);
}
return null;
};
this._findJsTypeName = (ctorOrTypeChecker: ObjectTypeDescriptor) => {
if (!ctorOrTypeChecker) {
return null;
}
const name = (ctorOrTypeChecker as ClassConstructor).name;
if (name === "Object") {
return null;
}
return name;
};
this._transformClassCollectionNameToDocumentIdPrefix =
collectionName => DocumentConventions.defaultTransformCollectionNameToDocumentIdPrefix(collectionName);
this._findCollectionName = type => DocumentConventions.defaultGetCollectionName(type);
this._maxNumberOfRequestsPerSession = 30;
this._bulkInsert = new BulkInsertConventions(() => this._assertNotFrozen());
this._maxHttpCacheSize = 128 * 1024 * 1024;
this._knownEntityTypes = new Map();
this._objectMapper = new TypesAwareObjectMapper({
dateFormat: DateUtil.DEFAULT_DATE_FORMAT,
documentConventions: this
});
this._useCompression = null;
this._dateUtilOpts = {};
this._dateUtil = new DateUtil(this._dateUtilOpts);
this._syncJsonParseLimit = 2 * 1_024 * 1_024;
this._firstBroadcastAttemptTimeout = 5_000;
this._secondBroadcastAttemptTimeout = 30_000;
this._waitForIndexesAfterSaveChangesTimeout = 15_000;
this._waitForReplicationAfterSaveChangesTimeout = 15_000;
this._waitForNonStaleResultsTimeout = 15_000;
this._sendApplicationIdentifier = true;
}
public get requestTimeout() {
return this._requestTimeout;
}
public set requestTimeout(requestTimeout: number) {
this._assertNotFrozen();
this._requestTimeout = requestTimeout;
}
/**
* Enables sending a unique application identifier to the RavenDB Server that is used for Client API usage tracking.
* It allows RavenDB Server to issue performance hint notifications e.g. during robust topology update requests which could indicate Client API misuse impacting the overall performance
* @return if option is enabled
*/
public get sendApplicationIdentifier() {
return this._sendApplicationIdentifier;
}
/**
* Enables sending a unique application identifier to the RavenDB Server that is used for Client API usage tracking.
* It allows RavenDB Server to issue performance hint notifications e.g. during robust topology update requests which could indicate Client API misuse impacting the overall performance
* @param sendApplicationIdentifier if option should be enabled
*/
public set sendApplicationIdentifier(sendApplicationIdentifier: boolean) {
this._assertNotFrozen();
this._sendApplicationIdentifier = sendApplicationIdentifier;
}
/**
* Get the timeout for the second broadcast attempt.
* Default: 30 seconds
*
* Upon failure of the first attempt the request executor will resend the command to all nodes simultaneously.
* @return broadcast timeout
*/
public get secondBroadcastAttemptTimeout() {
return this._secondBroadcastAttemptTimeout;
}
/**
* Set the timeout for the second broadcast attempt.
* Default: 30 seconds
*
* Upon failure of the first attempt the request executor will resend the command to all nodes simultaneously.
*
* @param secondBroadcastAttemptTimeout broadcast timeout
*/
public set secondBroadcastAttemptTimeout(secondBroadcastAttemptTimeout: number) {
this._assertNotFrozen();
this._secondBroadcastAttemptTimeout = secondBroadcastAttemptTimeout;
}
/**
* Get the timeout for the first broadcast attempt.
* Default: 5 seconds
*
* First attempt will send a single request to a selected node.
* @return broadcast timeout
*/
public get firstBroadcastAttemptTimeout() {
return this._firstBroadcastAttemptTimeout;
}
/**
* Set the timeout for the first broadcast attempt.
* Default: 5 seconds
*
* First attempt will send a single request to a selected node.
*
* @param firstBroadcastAttemptTimeout broadcast timeout
*/
public set firstBroadcastAttemptTimeout(firstBroadcastAttemptTimeout: number) {
this._assertNotFrozen();
this._firstBroadcastAttemptTimeout = firstBroadcastAttemptTimeout;
}
public get objectMapper(): TypesAwareObjectMapper {
return this._objectMapper;
}
public set objectMapper(value: TypesAwareObjectMapper) {
this._assertNotFrozen();
this._objectMapper = value;
}
/**
* Sets json length limit for sync parsing. Beyond that size
* we fallback to async parsing
*/
public get syncJsonParseLimit(): number {
return this._syncJsonParseLimit;
}
/**
* Gets json length limit for sync parsing. Beyond that size
* we fallback to async parsing
*/
public set syncJsonParseLimit(value: number) {
this._assertNotFrozen();
this._syncJsonParseLimit = value;
}
public get dateUtil(): DateUtil {
return this._dateUtil;
}
public get readBalanceBehavior(): ReadBalanceBehavior {
return this._readBalanceBehavior;
}
public set readBalanceBehavior(value: ReadBalanceBehavior) {
this._assertNotFrozen();
this._readBalanceBehavior = value;
}
public get loadBalancerContextSeed() {
return this._loadBalancerContextSeed;
}
public set loadBalancerContextSeed(seed: number) {
this._assertNotFrozen();
this._loadBalancerContextSeed = seed;
}
/**
* We have to make this check so if admin activated this, but client code did not provide the selector,
* it is still disabled. Relevant if we have multiple clients / versions at once.
*/
public get loadBalanceBehavior() {
return this._loadBalanceBehavior;
}
public set loadBalanceBehavior(loadBalanceBehavior: LoadBalanceBehavior) {
this._assertNotFrozen();
this._loadBalanceBehavior = loadBalanceBehavior;
}
/**
* Gets the function that allow to specialize the topology
* selection for a particular session. Used in load balancing
* scenarios
*/
public get loadBalancerPerSessionContextSelector(): (databaseName: string) => string {
return this._loadBalancerPerSessionContextSelector;
}
/**
* Sets the function that allow to specialize the topology
* selection for a particular session. Used in load balancing
* scenarios
* @param selector selector to use
*/
public set loadBalancerPerSessionContextSelector(selector: (databaseName: string) => string) {
this._loadBalancerPerSessionContextSelector = selector;
}
public get entityFieldNameConvention(): CasingConvention {
return this._localEntityFieldNameConvention;
}
public set entityFieldNameConvention(val) {
this._assertNotFrozen();
this._localEntityFieldNameConvention = val;
}
public get remoteEntityFieldNameConvention() {
return this._remoteEntityFieldNameConvention;
}
public set remoteEntityFieldNameConvention(val) {
this._assertNotFrozen();
this._remoteEntityFieldNameConvention = val;
}
public set useOptimisticConcurrency(val) {
this._assertNotFrozen();
this._useOptimisticConcurrency = val;
}
public get useOptimisticConcurrency() {
return this._useOptimisticConcurrency;
}
public deserializeEntityFromJson(documentType: ObjectTypeDescriptor, document: object): object {
try {
const typeName = documentType ? documentType.name : null;
return this.objectMapper.fromObjectLiteral(document, { typeName });
} catch (err) {
throwError("RavenException", "Cannot deserialize entity", err);
}
}
public get maxNumberOfRequestsPerSession(): number {
return this._maxNumberOfRequestsPerSession;
}
public set maxNumberOfRequestsPerSession(value: number) {
this._maxNumberOfRequestsPerSession = value;
}
public get maxHttpCacheSize(): number {
return this._maxHttpCacheSize;
}
public set maxHttpCacheSize(value: number) {
this._assertNotFrozen();
this._maxHttpCacheSize = value;
}
public get hasExplicitlySetCompressionUsage() {
return this._useCompression !== null;
}
public get waitForIndexesAfterSaveChangesTimeout() {
return this._waitForIndexesAfterSaveChangesTimeout;
}
public set waitForIndexesAfterSaveChangesTimeout(value: number) {
this._assertNotFrozen();
this._waitForIndexesAfterSaveChangesTimeout = value;
}
public get waitForNonStaleResultsTimeout() {
return this._waitForNonStaleResultsTimeout;
}
public set waitForNonStaleResultsTimeout(value: number) {
this._assertNotFrozen();
this._waitForNonStaleResultsTimeout = value;
}
public get waitForReplicationAfterSaveChangesTimeout() {
return this._waitForNonStaleResultsTimeout;
}
public set waitForReplicationAfterSaveChangesTimeout(value: number) {
this._assertNotFrozen();
this._waitForReplicationAfterSaveChangesTimeout = value;
}
public get useCompression() {
if (this._useCompression === null) {
return true;
}
return this._useCompression;
}
public set useCompression(value) {
this._assertNotFrozen();
this._useCompression = value;
}
private _dateUtilOpts: DateUtilOpts;
public get storeDatesInUtc() {
return this._dateUtilOpts.useUtcDates;
}
public set storeDatesInUtc(value) {
this._assertNotFrozen();
this._dateUtilOpts.useUtcDates = value;
}
public get storeDatesWithTimezoneInfo() {
return this._dateUtilOpts.withTimezone;
}
public set storeDatesWithTimezoneInfo(value) {
this._assertNotFrozen();
this._dateUtilOpts.withTimezone = true;
}
/**
* If set to 'true' then it will throw an exception when any query is performed (in session)
* without explicit page size set.
* This can be useful for development purposes to pinpoint all the possible performance bottlenecks
* since from 4.0 there is no limitation for number of results returned from server.
*/
public isThrowIfQueryPageSizeIsNotSet(): boolean {
return this._throwIfQueryPageSizeIsNotSet;
}
/**
* If set to 'true' then it will throw an exception when any query is performed (in session)
* without explicit page size set.
* This can be useful for development purposes to pinpoint all the possible performance bottlenecks
* since from 4.0 there is no limitation for number of results returned from server.
*/
public setThrowIfQueryPageSizeIsNotSet(throwIfQueryPageSizeIsNotSet: boolean): void {
this._assertNotFrozen();
this._throwIfQueryPageSizeIsNotSet = throwIfQueryPageSizeIsNotSet;
}
/**
* Whether UseOptimisticConcurrency is set to true by default for all opened sessions
*/
public isUseOptimisticConcurrency(): boolean {
return this._useOptimisticConcurrency;
}
/**
* Whether UseOptimisticConcurrency is set to true by default for all opened sessions
*/
public setUseOptimisticConcurrency(useOptimisticConcurrency: boolean): void {
this._assertNotFrozen();
this._useOptimisticConcurrency = useOptimisticConcurrency;
}
public get identityProperty() {
return this._identityProperty;
}
public set identityProperty(val) {
this._assertNotFrozen();
this._identityProperty = val;
}
public get findJsType() {
return this._findJsType;
}
public set findJsType(value) {
this._assertNotFrozen();
this._findJsType = value;
}
public get findJsTypeName() {
return this._findJsTypeName;
}
public set findJsTypeName(value) {
this._assertNotFrozen();
this._findJsTypeName = value;
}
public get findCollectionName() {
return this._findCollectionName;
}
public set findCollectionName(value) {
this._assertNotFrozen();
this._findCollectionName = value;
}
public get documentIdGenerator() {
return this._documentIdGenerator;
}
public set documentIdGenerator(value) {
this._assertNotFrozen();
this._documentIdGenerator = value;
}
public get identityPartsSeparator(): string {
return this._identityPartsSeparator;
}
public set identityPartsSeparator(value: string) {
this._assertNotFrozen();
if (this.identityPartsSeparator === "|") {
throwError("InvalidArgumentException", "Cannot set identity parts separator to '|'");
}
this._identityPartsSeparator = value;
}
public get shouldIgnoreEntityChanges() {
return this._shouldIgnoreEntityChanges;
}
public set shouldIgnoreEntityChanges(
shouldIgnoreEntityChanges: (sessionOperations: InMemoryDocumentSessionOperations, entity: object, documentId: string) => boolean) {
this._assertNotFrozen();
this._shouldIgnoreEntityChanges = shouldIgnoreEntityChanges;
}
public get disableTopologyUpdates(): boolean {
return this._disableTopologyUpdates;
}
public set disableTopologyUpdates(value: boolean) {
this._assertNotFrozen();
this._disableTopologyUpdates = value;
}
public get throwIfQueryPageSizeIsNotSet(): boolean {
return this._throwIfQueryPageSizeIsNotSet;
}
public set throwIfQueryPageSizeIsNotSet(value: boolean) {
this._assertNotFrozen();
this._throwIfQueryPageSizeIsNotSet = value;
}
public get transformClassCollectionNameToDocumentIdPrefix() {
return this._transformClassCollectionNameToDocumentIdPrefix;
}
public set transformClassCollectionNameToDocumentIdPrefix(value) {
this._assertNotFrozen();
this._transformClassCollectionNameToDocumentIdPrefix = value;
}
/**
* Default method used when finding a collection name for a type
*/
public static defaultGetCollectionName(ctorOrTypeChecker: ObjectTypeDescriptor): string {
if (!ctorOrTypeChecker) {
return null;
}
if (!TypeUtil.isObjectTypeDescriptor(ctorOrTypeChecker)) {
throwError("InvalidArgumentException", "Invalid class argument.");
}
if (!ctorOrTypeChecker.name) {
throwError("InvalidArgumentException", "Type name cannot be null or undefined.");
}
let result = this._cachedDefaultTypeCollectionNames.get(ctorOrTypeChecker);
if (result) {
return result;
}
if (typeof (ctorOrTypeChecker) === "string") {
result = pluralize.plural(ctorOrTypeChecker);
} else {
result = pluralize.plural(ctorOrTypeChecker.name);
}
this._cachedDefaultTypeCollectionNames.set(ctorOrTypeChecker, result);
return result;
}
/**
* Gets the collection name for a given type.
*/
public getCollectionNameForType(ctorOrTypeChecker: ObjectTypeDescriptor): string {
const collectionName: string = this._findCollectionName(ctorOrTypeChecker);
return collectionName || DocumentConventions.defaultGetCollectionName(ctorOrTypeChecker);
}
/**
* Gets the collection name for a given type.
*/
public getCollectionNameForEntity(entity: object): string {
if (!entity) {
return null;
}
const typeDescriptor = this.getEntityTypeDescriptor(entity);
if (typeDescriptor) {
return this.getCollectionNameForType(typeDescriptor);
}
if (this._findCollectionNameForObjectLiteral && entity.constructor === Object) {
return this._findCollectionNameForObjectLiteral(entity);
}
return null;
}
private _findCollectionNameForObjectLiteral: (entity: object) => string;
public get findCollectionNameForObjectLiteral() {
return this._findCollectionNameForObjectLiteral;
}
public set findCollectionNameForObjectLiteral(value: (entity: object) => string) {
this._findCollectionNameForObjectLiteral = value;
}
public getTypeDescriptorByEntity<T extends object>(entity: T): ObjectTypeDescriptor<T> {
return this.getEntityTypeDescriptor(entity);
}
public getEntityTypeDescriptor<T extends object>(entity: T): ObjectTypeDescriptor<T> {
if (TypeUtil.isClass(entity.constructor)) {
return entity.constructor as ClassConstructor;
}
for (const entityType of this._knownEntityTypes.values()) {
if (!TypeUtil.isObjectLiteralTypeDescriptor(entityType)) {
continue;
}
if ((entityType as ObjectLiteralDescriptor<T>).isType(entity)) {
return entityType as ObjectLiteralDescriptor<T>;
}
}
return null;
}
/**
* Generates the document id.
*/
public generateDocumentId(database: string, entity: object): Promise<string> {
for (const [typeDescriptor, idConvention] of this._registeredIdConventions) {
if (TypeUtil.isType(entity, typeDescriptor)) {
return Promise.resolve(idConvention(database, entity));
}
}
return this._documentIdGenerator(database, entity);
}
/**
* Register an id convention for a single type.
* Note that you can still fall back to the DocumentIdGenerator if you want.
*/
public registerIdConvention<TEntity>(
ctorOrTypeChecker: ObjectTypeDescriptor,
idConvention: IdConvention): DocumentConventions {
this._assertNotFrozen();
this._registeredIdConventions.set(ctorOrTypeChecker, idConvention);
return this;
}
public registerEntityIdPropertyName(ctorOrTypeChecker: ObjectTypeDescriptor, idProperty: string) {
this._registeredIdPropertyNames.set(ctorOrTypeChecker, idProperty);
}
/**
* Get the java class (if exists) from the document
*/
public getJsType(id: string, document: object): ObjectTypeDescriptor {
return this._findJsType(id, document);
}
/**
* Get the Java class name to be stored in the entity metadata
*/
public getJsTypeName(entityType: ObjectTypeDescriptor): string {
return this._findJsTypeName(entityType);
}
/**
* EXPERT: Disable automatic atomic writes with cluster write transactions. If set to 'true', will only consider explicitly
* added compare exchange values to validate cluster wide transactions.
*/
public get disableAtomicDocumentWritesInClusterWideTransaction() {
return this._disableAtomicDocumentWritesInClusterWideTransaction;
}
/**
* EXPERT: Disable automatic atomic writes with cluster write transactions. If set to 'true', will only consider explicitly
* added compare exchange values to validate cluster wide transactions.
*/
public set disableAtomicDocumentWritesInClusterWideTransaction(disableAtomicDocumentWritesInClusterWideTransaction: boolean) {
this._assertNotFrozen();
this._disableAtomicDocumentWritesInClusterWideTransaction = disableAtomicDocumentWritesInClusterWideTransaction;
}
public clone(): DocumentConventions {
const cloned = new DocumentConventions();
return Object.assign(cloned, this);
}
/**
* Gets the identity property.
*/
public getIdentityProperty(documentType: DocumentType): string {
const typeDescriptor = this.getJsTypeByDocumentType(documentType);
return this._registeredIdPropertyNames.get(typeDescriptor)
|| this._identityProperty;
}
public updateFrom(configuration: ClientConfiguration): void {
if (!configuration) {
return;
}
const orig = this._originalConfiguration;
if (configuration.disabled && !orig) { // nothing to do
return;
}
if (configuration.disabled && orig) { // need to revert to original values
this._maxNumberOfRequestsPerSession = orig.maxNumberOfRequestsPerSession ?? this.maxNumberOfRequestsPerSession;
this._readBalanceBehavior = orig.readBalanceBehavior ?? this._readBalanceBehavior;
this._identityPartsSeparator = orig.identityPartsSeparator ?? this._identityPartsSeparator;
this._loadBalanceBehavior = orig.loadBalanceBehavior ?? this._loadBalanceBehavior;
this._loadBalancerContextSeed = orig.loadBalancerContextSeed ?? this._loadBalancerContextSeed;
this._originalConfiguration = null;
return;
}
if (!this._originalConfiguration) {
this._originalConfiguration = {
etag: -1,
maxNumberOfRequestsPerSession: this._maxNumberOfRequestsPerSession,
readBalanceBehavior: this._readBalanceBehavior,
identityPartsSeparator: this._identityPartsSeparator,
loadBalanceBehavior: this._loadBalanceBehavior,
loadBalancerContextSeed: this._loadBalancerContextSeed,
disabled: false
};
}
this._maxNumberOfRequestsPerSession =
configuration.maxNumberOfRequestsPerSession
?? this._originalConfiguration.maxNumberOfRequestsPerSession
?? this._maxNumberOfRequestsPerSession;
this._readBalanceBehavior =
configuration.readBalanceBehavior
?? this._originalConfiguration.readBalanceBehavior
?? this._readBalanceBehavior;
this._loadBalanceBehavior =
configuration.loadBalanceBehavior
?? this._originalConfiguration.loadBalanceBehavior
?? this._loadBalanceBehavior;
this._loadBalancerContextSeed =
configuration.loadBalancerContextSeed
?? this._originalConfiguration.loadBalancerContextSeed
?? this._loadBalancerContextSeed;
this._identityPartsSeparator =
configuration.identityPartsSeparator
?? this._originalConfiguration.identityPartsSeparator
?? this._identityPartsSeparator;
}
public static defaultTransformCollectionNameToDocumentIdPrefix(collectionName: string): string {
const upperCaseRegex = /[A-Z]/g;
const m = collectionName.match(upperCaseRegex);
const upperCount = m ? m.length : 0;
if (upperCount <= 1) {
return collectionName.toLowerCase();
}
// multiple capital letters, so probably something that we want to preserve caps on.
return collectionName;
}
/* TBD 4.1 custom serializers
public registerQueryValueConverter<T extends object>(type: EntityConstructor<T>,
converter: IValueForQueryConverter<T>) {
this._assertNotFrozen();
let index;
for (index = 0; index < this._listOfQueryValueToObjectConverters.length; index++) {
const entry = this._listOfQueryValueToObjectConverters[index];
if (type instanceof entry.Type) {
break;
}
}
this._listOfQueryValueToObjectConverters.splice(index, 0, {
Type: type,
Converter: (fieldName, value, forRange, stringValue) => {
if (value instanceof type) {
return converter(fieldName, value, forRange, stringValue);
}
stringValue(null);
return false;
}
});
}
*/
public tryConvertValueToObjectForQuery(fieldName: string, value: any, forRange: boolean, strValue: (value: any) => void) {
for (const queryValueConverter of this._listOfQueryValueToObjectConverters) {
if (!(value instanceof queryValueConverter.Type)) {
continue;
}
return queryValueConverter.Converter(fieldName, value, forRange, strValue);
}
strValue(null);
return false;
}
public freeze() {
this._frozen = true;
}
private _assertNotFrozen(): void {
if (this._frozen) {
throwError("RavenException",
"Conventions has been frozen after documentStore.initialize() and no changes can be applied to them");
}
}
public get knownEntityTypesByName() {
return this._knownEntityTypes;
}
public get knownEntityTypes() {
return Array.from(this._knownEntityTypes.values());
}
public registerJsType(entityType: ObjectTypeDescriptor): this;
public registerJsType(entityType: ObjectTypeDescriptor, name: string): this;
public registerJsType(entityType: ObjectTypeDescriptor, name?: string): this {
return this.registerEntityType(entityType, name);
}
public registerEntityType(entityType: ObjectTypeDescriptor): this;
public registerEntityType(entityType: ObjectTypeDescriptor, name: string): this;
public registerEntityType(entityType: ObjectTypeDescriptor, name?: string): this {
if (!TypeUtil.isObjectTypeDescriptor(entityType)) {
throwError("InvalidArgumentException",
"Entity type must be a constructor or an object literal descriptor.");
}
if (name) {
this._knownEntityTypes.set(name, entityType);
}
this._knownEntityTypes.set(entityType.name, entityType);
return this;
}
public tryRegisterJsType(docType: DocumentType): this {
return this.tryRegisterEntityType(docType);
}
public tryRegisterEntityType(docType: DocumentType): this {
if (TypeUtil.isObjectTypeDescriptor(docType)) {
this.registerJsType(docType as ObjectTypeDescriptor);
}
return this;
}
public getJsTypeByDocumentType<T extends object>(documentType: DocumentType<T>): ObjectTypeDescriptor<T>;
public getJsTypeByDocumentType<T extends object>(typeName: string): ObjectTypeDescriptor<T>;
public getJsTypeByDocumentType<T extends object>(
docTypeOrTypeName: string | DocumentType<T>): ObjectTypeDescriptor<T> {
if (!docTypeOrTypeName) {
return null;
}
if (typeof(docTypeOrTypeName) === "string") {
return this._knownEntityTypes.get(
docTypeOrTypeName) as ObjectLiteralDescriptor<T> || null;
}
if (docTypeOrTypeName.name === "Object") {
return null;
}
return docTypeOrTypeName as ObjectTypeDescriptor<T>;
}
public transformObjectKeysToRemoteFieldNameConvention(obj: object, opts?: ObjectChangeCaseOptions) {
if (!this._remoteEntityFieldNameConvention) {
return obj;
}
const options: any = opts || {
recursive: true,
arrayRecursive: true,
ignorePaths: [
CONSTANTS.Documents.Metadata.IGNORE_CASE_TRANSFORM_REGEX,
]
};
options.defaultTransform = this._remoteEntityFieldNameConvention;
return ObjectUtil.transformObjectKeys(obj, options);
}
public transformObjectKeysToLocalFieldNameConvention(
obj: object, opts?: ObjectChangeCaseOptions) {
if (!this._localEntityFieldNameConvention) {
return obj as object;
}
const options = opts || {
recursive: true,
arrayRecursive: true,
ignorePaths: [
CONSTANTS.Documents.Metadata.IGNORE_CASE_TRANSFORM_REGEX,
/@projection/
]
} as any;
options.defaultTransform = this._localEntityFieldNameConvention;
return ObjectUtil.transformObjectKeys(obj, options as ObjectChangeCaseOptions);
}
public validate() {
if ((this._remoteEntityFieldNameConvention && !this._localEntityFieldNameConvention)
|| (!this._remoteEntityFieldNameConvention && this._localEntityFieldNameConvention)) {
throwError("ConfigurationException",
"When configuring field name conventions, "
+ "one has to configure both local and remote field name convention.");
}
}
}
DocumentConventions.defaultConventions.freeze(); | the_stack |
import { resolveFileSystem, FileSystem } from "@xmcl/system";
import { parse as parseToml } from "@iarna/toml";
import { AnnotationVisitor, ClassReader, ClassVisitor, MethodVisitor, Opcodes } from "@xmcl/asm";
/**
* The @Mod data from class file
*/
export interface ForgeModAnnotationData {
[key: string]: any;
value: string;
modid: string;
name: string;
version: string;
/**
* A dependency string for this mod, which specifies which mod(s) it depends on in order to run.
*
* A dependency string must start with a combination of these prefixes, separated by "-":
* [before, after], [required], [client, server]
* At least one "before", "after", or "required" must be specified.
* Then ":" and the mod id.
* Then a version range should be specified for the mod by adding "@" and the version range.
* The version range format is described in the javadoc here:
* {@link VersionRange#createFromVersionSpec(java.lang.String)}
* Then a ";".
*
* If a "required" mod is missing, or a mod exists with a version outside the specified range,
* the game will not start and an error screen will tell the player which versions are required.
*
* Example:
* Our example mod:
* * depends on Forge and uses new features that were introduced in Forge version 14.21.1.2395
* "required:forge@[14.21.1.2395,);"
*
* 1.12.2 Note: for compatibility with Forge older than 14.23.0.2501 the syntax must follow this older format:
* "required-after:forge@[14.21.1.2395,);"
* For more explanation see https://github.com/MinecraftForge/MinecraftForge/issues/4918
*
* * is a dedicated addon to mod1 and has to have its event handlers run after mod1's are run,
* "required-after:mod1;"
* * has optional integration with mod2 which depends on features introduced in mod2 version 4.7.0,
* "after:mod2@[4.7.0,);"
* * depends on a client-side-only rendering library called rendermod
* "required-client:rendermod;"
*
* The full dependencies string is all of those combined:
* "required:forge@[14.21.1.2395,);required-after:mod1;after:mod2@[4.7.0,);required-client:rendermod;"
*
* This will stop the game and display an error message if any of these is true:
* The installed forge is too old,
* mod1 is missing,
* an old version of mod2 is present,
* rendermod is missing on the client.
*/
dependencies: string;
useMetadata: boolean;
acceptedMinecraftVersions: string;
acceptableRemoteVersions: string;
acceptableSaveVersions: string;
modLanguage: string;
modLanguageAdapter: string
clientSideOnly: boolean;
serverSideOnly: boolean;
}
/**
* Represent the forge `mcmod.info` format.
*/
export interface ForgeModMcmodInfo {
/**
* The modid this description is linked to. If the mod is not loaded, the description is ignored.
*/
modid: string;
/**
* The user-friendly name of this mod.
*/
name: string;
/**
* A description of this mod in 1-2 paragraphs.
*/
description: string;
/**
* The version of the mod.
*/
version: string;
/**
* The Minecraft version.
*/
mcversion: string;
/**
* A link to the mod’s homepage.
*/
url: string;
/**
* Defined but unused. Superseded by updateJSON.
*/
updateUrl: string;
/**
* The URL to a version JSON.
*/
updateJSON: string;
/**
* A list of authors to this mod.
*/
authorList: string[];
/**
* A string that contains any acknowledgements you want to mention.
*/
credits: string;
/**
* The path to the mod’s logo. It is resolved on top of the classpath, so you should put it in a location where the name will not conflict, maybe under your own assets folder.
*/
logoFile: string;
/**
* A list of images to be shown on the info page. Currently unimplemented.
*/
screenshots: string[];
/**
* The modid of a parent mod, if applicable. Using this allows modules of another mod to be listed under it in the info page, like BuildCraft.
*/
parent: string;
/**
* If true and `Mod.useMetadata`, the below 3 lists of dependencies will be used. If not, they do nothing.
*/
useDependencyInformation: boolean;
/**
* A list of modids. If one is missing, the game will crash. This does not affect the ordering of mod loading! To specify ordering as well as requirement, have a coupled entry in dependencies.
*/
requiredMods: string[];
/**
* A list of modids. All of the listed mods will load before this one. If one is not present, nothing happens.
*/
dependencies: string[];
/**
* A list of modids. All of the listed mods will load after this one. If one is not present, nothing happens.
*/
dependants: string[];
}
/**
* This file defines the metadata of your mod. Its information may be viewed by users from the main screen of the game through the Mods button. A single info file can describe several mods.
*
* The mods.toml file is formatted as TOML, the example mods.toml file in the MDK provides comments explaining the contents of the file. It should be stored as src/main/resources/META-INF/mods.toml. A basic mods.toml, describing one mod, may look like this:
*/
export interface ForgeModTOMLData {
/**
* The modid this file is linked to
*/
modid: string;
/**
* The version of the mod.It should be just numbers seperated by dots, ideally conforming to Semantic Versioning
*/
version: string;
/**
* The user - friendly name of this mod
*/
displayName: string;
/**
* The URL to a version JSON
*/
updateJSONURL: string;
/**
* A link to the mod’s homepage
*/
displayURL: string;
/**
* The filename of the mod’s logo.It must be placed in the root resource folder, not in a subfolder
*/
logoFile: string;
/**
* A string that contains any acknowledgements you want to mention
*/
credits: string;
/**
* The authors to this mod
*/
authors: string;
/**
* A description of this mod
*/
description: string;
/**
* A list of dependencies of this mod
*/
dependencies: { modId: string; mandatory: boolean; versionRange: string; ordering: "NONE" | "BEFORE" | "AFTER"; side: "BOTH" | "CLIENT" | "SERVER" }[];
/**
* The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
*/
modLoader: string;
/**
* A version range to match for said mod loader - for regular FML @Mod it will be the forge version
*/
loaderVersion: string;
/**
* A URL to refer people to when problems occur with this mod
*/
issueTrackerURL: string;
}
export interface ForgeModASMData {
/**
* Does class files contain cpw package
*/
usedLegacyFMLPackage: boolean;
/**
* Does class files contain forge package
*/
usedForgePackage: boolean;
/**
* Does class files contain minecraft package
*/
usedMinecraftPackage: boolean;
/**
* Does class files contain minecraft.client package
*/
usedMinecraftClientPackage: boolean;
modAnnotations: ForgeModAnnotationData[];
}
/**
* The metadata inferred from manifest
*/
export interface ManifestMetadata {
modid: string;
name: string;
authors: string[];
version: string;
description: string;
url: string;
}
class ModAnnotationVisitor extends AnnotationVisitor {
constructor(readonly map: ForgeModAnnotationData) { super(Opcodes.ASM5); }
public visit(s: string, o: any) {
if (s === "value") {
this.map.modid = o
} else {
this.map[s] = o;
}
}
}
class DummyModConstructorVisitor extends MethodVisitor {
private stack: any[] = [];
constructor(private parent: ModClassVisitor, api: number) {
super(api);
}
visitLdcInsn(value: any) {
this.stack.push(value);
}
visitFieldInsn(opcode: number, owner: string, name: string, desc: string) {
if (opcode === Opcodes.PUTFIELD) {
const last = this.stack.pop();
if (last) {
if (name === "modId") {
this.parent.guess.modid = last;
} else if (name === "version") {
this.parent.guess.version = last;
} else if (name === "name") {
this.parent.guess.name = last;
} else if (name === "url") {
this.parent.guess.url = last;
} else if (name === "parent") {
this.parent.guess.parent = last;
} else if (name === "mcversion") {
this.parent.guess.mcversion = last;
}
}
}
}
}
class ModClassVisitor extends ClassVisitor {
public fields: Record<string, any> = {};
public className: string = "";
public isDummyModContainer: boolean = false;
public isPluginClass: boolean = false;
public constructor(readonly result: ForgeModASMData, public guess: Partial<ForgeModAnnotationData>, readonly corePlugin?: string) {
super(Opcodes.ASM5);
}
private validateType(desc: string) {
if (desc.indexOf("net/minecraftforge") !== -1) {
this.result.usedForgePackage = true;
}
if (desc.indexOf("net/minecraft") !== -1) {
this.result.usedMinecraftPackage = true;
}
if (desc.indexOf("cpw/mods/fml") !== -1) {
this.result.usedLegacyFMLPackage = true;
}
if (desc.indexOf("net/minecraft/client") !== -1) {
this.result.usedMinecraftClientPackage = true;
}
}
visit(version: number, access: number, name: string, signature: string, superName: string, interfaces: string[]): void {
this.className = name;
this.isPluginClass = name === this.corePlugin;
if (superName === "net/minecraftforge/fml/common/DummyModContainer") {
this.isDummyModContainer = true;
}
this.validateType(superName);
for (const intef of interfaces) {
this.validateType(intef);
}
}
public visitMethod(access: number, name: string, desc: string, signature: string, exceptions: string[]) {
if (this.isDummyModContainer && name === "<init>") {
return new DummyModConstructorVisitor(this, Opcodes.ASM5);
}
this.validateType(desc);
return null;
}
public visitField(access: number, name: string, desc: string, signature: string, value: any) {
this.fields[name] = value;
return null;
}
public visitAnnotation(desc: string, visible: boolean): AnnotationVisitor | null {
if (desc === "Lnet/minecraftforge/fml/common/Mod;" || desc === "Lcpw/mods/fml/common/Mod;") {
const annotationData: ForgeModAnnotationData = {
modid: "",
name: "",
version: "",
dependencies: "",
useMetadata: true,
clientSideOnly: false,
serverSideOnly: false,
acceptedMinecraftVersions: "",
acceptableRemoteVersions: "",
acceptableSaveVersions: "",
modLanguage: "java",
modLanguageAdapter: "",
value: "",
}
this.result.modAnnotations.push(annotationData);
return new ModAnnotationVisitor(annotationData);
}
return null;
}
visitEnd() {
if (this.className === "Config" && this.fields && this.fields.OF_NAME) {
this.result.modAnnotations.push({
modid: this.fields.OF_NAME,
name: this.fields.OF_NAME,
mcversion: this.fields.MC_VERSION,
version: `${this.fields.OF_EDITION}_${this.fields.OF_RELEASE}`,
description: "OptiFine is a Minecraft optimization mod. It allows Minecraft to run faster and look better with full support for HD textures and many configuration options.",
authorList: ["sp614x"],
url: "https://optifine.net",
clientSideOnly: true,
serverSideOnly: false,
value: "",
dependencies: "",
useMetadata: false,
acceptableRemoteVersions: "",
acceptableSaveVersions: "",
acceptedMinecraftVersions: `[${this.fields.MC_VERSION}]`,
modLanguage: "java",
modLanguageAdapter: "",
})
}
for (const [k, v] of Object.entries(this.fields)) {
switch (k.toUpperCase()) {
case "MODID":
case "MOD_ID":
this.guess.modid = this.guess.modid || v;
break;
case "MODNAME":
case "MOD_NAME":
this.guess.name = this.guess.name || v;
break;
case "VERSION":
case "MOD_VERSION":
this.guess.version = this.guess.version || v;
break;
case "MCVERSION":
this.guess.mcversion = this.guess.mcversion || v;
break;
}
}
}
}
/**
* Read the mod info from `META-INF/MANIFEST.MF`
* @returns The manifest directionary
*/
export async function readForgeModManifest(mod: ForgeModInput, manifestStore: Record<string, any> = {}): Promise<ManifestMetadata | undefined> {
const fs = await resolveFileSystem(mod);
if (! await fs.existsFile("META-INF/MANIFEST.MF")) { return undefined; }
const data = await fs.readFile("META-INF/MANIFEST.MF");
const manifest: Record<string, string> = data.toString().split("\n")
.map((l) => l.trim())
.filter((l) => l.length > 0)
.map((l) => l.split(":").map((s) => s.trim()))
.reduce((a, b) => ({ ...a, [b[0]]: b[1] }), {}) as any;
Object.assign(manifestStore, manifest);
const metadata: ManifestMetadata = {
modid: "",
name: "",
authors: new Array<string>(),
version: "",
description: "",
url: "",
};
if (typeof manifest.TweakName === "string") {
metadata.modid = manifest.TweakName;
metadata.name = manifest.TweakName;
}
if (typeof manifest.TweakAuthor === "string") {
metadata.authors = [manifest.TweakAuthor];
}
if (typeof manifest.TweakVersion === "string") {
metadata.version = manifest.TweakVersion;
}
if (manifest.TweakMetaFile) {
const file = manifest.TweakMetaFile;
if (await fs.existsFile(`META-INF/${file}`)) {
const metadataContent = await fs.readFile(`META-INF/${file}`, "utf-8").then((s) => s.replace(/^\uFEFF/, "")).then(JSON.parse);
if (metadataContent.id) {
metadata.modid = metadataContent.id;
}
if (metadataContent.name) {
metadata.name = metadataContent.name;
}
if (metadataContent.version) {
metadata.version = metadataContent.version;
}
if (metadataContent.authors) {
metadata.authors = metadataContent.authors;
}
if (metadataContent.description) {
metadata.description = metadataContent.description;
}
if (metadataContent.url) {
metadata.url = metadataContent.url;
}
}
}
return metadata;
}
/**
* Read mod metadata from new toml metadata file.
*/
export async function readForgeModToml(mod: ForgeModInput, manifest?: Record<string, string>) {
const fs = await resolveFileSystem(mod);
const existed = await fs.existsFile("META-INF/mods.toml");
const all: ForgeModTOMLData[] = [];
if (existed) {
const str = await fs.readFile("META-INF/mods.toml", "utf-8");
const root = parseToml(str);
if (root.mods instanceof Array) {
for (const mod of root.mods) {
const tomlMod = mod as any;
const modObject: ForgeModTOMLData = {
modid: tomlMod.modId ?? "",
authors: tomlMod.authors ?? root.authors as string ?? "",
version: tomlMod.version === "${file.jarVersion}" && typeof manifest?.["Implementation-Version"] === "string"
? manifest?.["Implementation-Version"] : tomlMod.version,
displayName: tomlMod.displayName ?? "",
description: tomlMod.description ?? "",
displayURL: tomlMod.displayURL ?? root.displayURL as string ?? "",
updateJSONURL: tomlMod.updateJSONURL ?? root.updateJSONURL ?? "",
dependencies: [],
logoFile: tomlMod.logoFile ?? "",
credits: tomlMod.credits ?? "",
loaderVersion: root.loaderVersion as string ?? "",
modLoader: root.modLoader as string ?? "",
issueTrackerURL: root.issueTrackerURL as string ?? "",
}
all.push(modObject);
}
}
if (typeof root.dependencies === "object") {
for (const mod of all) {
const dep = (root.dependencies as Record<string, any>)[mod.modid];
if (dep) { mod.dependencies = dep; }
}
}
}
return all;
}
/**
* Use asm to scan all the class files of the mod. This might take long time to read.
*/
export async function readForgeModAsm(mod: ForgeModInput, manifest: Record<string, string> = {}): Promise<ForgeModASMData> {
const fs = await resolveFileSystem(mod);
let corePluginClass: string | undefined;
if (manifest) {
if (typeof manifest.FMLCorePlugin === "string") {
const clazz = manifest.FMLCorePlugin.replace(/\./g, "/");
if (await fs.existsFile(clazz) || await fs.existsFile(`/${clazz}`)) {
corePluginClass = clazz;
}
}
}
const result: ForgeModASMData = {
usedForgePackage: false,
usedLegacyFMLPackage: false,
usedMinecraftClientPackage: false,
usedMinecraftPackage: false,
modAnnotations: []
};
const guessing: Partial<ForgeModAnnotationData> = {};
await fs.walkFiles("/", async (f) => {
if (!f.endsWith(".class")) { return; }
const data = await fs.readFile(f);
const visitor = new ModClassVisitor(result, guessing, corePluginClass);
new ClassReader(data).accept(visitor);
});
if (result.modAnnotations.length === 0 && guessing.modid && (result.usedForgePackage || result.usedLegacyFMLPackage)) {
result.modAnnotations.push({
modid: guessing.modid ?? "",
name: guessing.name ?? "",
version: guessing.version ?? "",
dependencies: guessing.dependencies ?? "",
useMetadata: guessing.useMetadata ?? false,
clientSideOnly: guessing.clientSideOnly ?? false,
serverSideOnly: guessing.serverSideOnly ?? false,
acceptedMinecraftVersions: guessing.acceptedMinecraftVersions ?? "",
acceptableRemoteVersions: guessing.acceptableRemoteVersions ?? "",
acceptableSaveVersions: guessing.acceptableSaveVersions ?? "",
modLanguage: guessing.modLanguage ?? "java",
modLanguageAdapter: guessing.modLanguageAdapter ?? "",
value: guessing.value ?? "",
});
}
return result;
}
/**
* Read `mcmod.info`, `cccmod.info`, and `neimod.info` json file
* @param mod The mod path or buffer or opened file system.
*/
export async function readForgeModJson(mod: ForgeModInput): Promise<ForgeModMcmodInfo[]> {
const fs = await resolveFileSystem(mod);
const all = [] as ForgeModMcmodInfo[];
function normalize(json: Partial<ForgeModMcmodInfo>) {
const metadata: ForgeModMcmodInfo = {
modid: "",
name: "",
description: "",
version: "",
mcversion: "",
url: "",
updateUrl: "",
updateJSON: "",
authorList: [],
credits: "",
logoFile: "",
screenshots: [],
parent: "",
useDependencyInformation: false,
requiredMods: [],
dependencies: [],
dependants: [],
};
metadata.modid = json.modid ?? metadata.modid;
metadata.name = json.name ?? metadata.name;
metadata.description = json.description ?? metadata.description;
metadata.version = json.version ?? metadata.version;
metadata.mcversion = json.mcversion ?? metadata.mcversion;
metadata.url = json.url ?? metadata.url;
metadata.updateUrl = json.updateUrl ?? metadata.updateUrl;
metadata.updateJSON = json.updateJSON ?? metadata.updateJSON;
metadata.authorList = json.authorList ?? metadata.authorList;
metadata.credits = json.credits ?? metadata.credits;
metadata.logoFile = json.logoFile ?? metadata.logoFile;
metadata.screenshots = json.screenshots ?? metadata.screenshots;
metadata.parent = json.parent ?? metadata.parent;
metadata.useDependencyInformation = json.useDependencyInformation ?? metadata.useDependencyInformation;
metadata.requiredMods = json.requiredMods ?? metadata.requiredMods;
metadata.dependencies = json.dependencies ?? metadata.dependencies;
metadata.dependants = json.dependants ?? metadata.dependants;
return metadata;
}
function readJsonMetadata(json: any) {
const modList: Array<Partial<ForgeModMcmodInfo>> = [];
if (json instanceof Array) {
modList.push(...json);
} else if (json.modList instanceof Array) {
modList.push(...json.modList);
} else if (json.modid) {
modList.push(json);
}
all.push(...modList.map(normalize));
}
if (await fs.existsFile("mcmod.info")) {
try {
const json = JSON.parse((await fs.readFile("mcmod.info", "utf-8")).replace(/^\uFEFF/, ""));
readJsonMetadata(json);
} catch (e) { }
} else if (await fs.existsFile("cccmod.info")) {
try {
const text = (await fs.readFile("cccmod.info", "utf-8")).replace(/^\uFEFF/, "").replace(/\n\n/g, "\\n").replace(/\n/g, "");
const json = JSON.parse(text);
readJsonMetadata(json);
} catch (e) { }
} else if (await fs.existsFile("neimod.info")) {
try {
const text = (await fs.readFile("neimod.info", "utf-8")).replace(/^\uFEFF/, "").replace(/\n\n/g, "\\n").replace(/\n/g, "");
const json = JSON.parse(text);
readJsonMetadata(json);
} catch (e) { }
}
return all;
}
type ForgeModInput = Uint8Array | string | FileSystem;
/**
* Represnet a full scan of a mod file data.
*/
export interface ForgeModMetadata extends ForgeModASMData {
/**
* The mcmod.info file metadata. If no mcmod.info file, it will be an empty array
*/
mcmodInfo: ForgeModMcmodInfo[];
/**
* The java manifest file data. If no metadata, it will be an empty object
*/
manifest: Record<string, any>;
/**
* The mod info extract from manfiest. If no manifest, it will be undefined!
*/
manifestMetadata?: ManifestMetadata;
/**
* The toml mod metadata
*/
modsToml: ForgeModTOMLData[];
}
/**
* Read metadata of the input mod.
*
* This will scan the mcmod.info file, all class file for `@Mod` & coremod `DummyModContainer` class.
* This will also scan the manifest file on `META-INF/MANIFEST.MF` for tweak mod.
*
* If the input is totally not a mod. It will throw {@link NonForgeModFileError}.
*
* @throws {@link NonForgeModFileError}
* @param mod The mod path or data
* @returns The mod metadata
*/
export async function readForgeMod(mod: ForgeModInput): Promise<ForgeModMetadata> {
const fs = await resolveFileSystem(mod);
const jsons = await readForgeModJson(fs);
const manifest: Record<string, any> = {};
const manifestMetadata = await readForgeModManifest(fs, manifest);
const tomls = await readForgeModToml(fs, manifest);
const base = await readForgeModAsm(fs, manifest);
if (jsons.length === 0 && (!manifestMetadata || !manifestMetadata.modid) && tomls.length === 0 && base.modAnnotations.length === 0) {
throw new ForgeModParseFailedError(mod, base, manifest);
}
const result: ForgeModMetadata = {
mcmodInfo: jsons,
manifest: manifest,
manifestMetadata: manifestMetadata?.modid ? manifestMetadata : undefined,
modsToml: tomls,
...base,
};
return result;
}
export class ForgeModParseFailedError extends Error {
constructor(readonly mod: ForgeModInput, readonly asm: Omit<ForgeModASMData, "modAnnotations">, readonly manifest: Record<string, any>) {
super("Cannot find the mod metadata in the mod!");
}
} | the_stack |
import {
$el,
getNumTypeAttr,
getStrTypeAttr,
nextAll,
prevAll,
removeAttrs,
setCss,
setHtml
} from '../../dom-utils';
import { warn } from '../../mixins';
import { type, validComps } from '../../utils';
import PREFIX from '../prefix';
interface Config {
config(
el: string
): {
current: number;
title: string;
content: string;
status: string;
itemStatus: string[];
};
}
class Steps implements Config {
readonly VERSION: string;
readonly COMPONENTS: NodeListOf<Element>;
constructor() {
this.VERSION = '1.0';
this.COMPONENTS = $el('r-steps', { all: true });
this._create(this.COMPONENTS);
}
public config(
el: string
): {
current: number;
title: string;
content: string;
status: string;
itemStatus: string[];
} {
const target = $el(el) as HTMLElement;
validComps(target, 'steps');
const { _setCurrentStep, _setStatus, _setStatusIcon } = Steps.prototype;
const _current = target.dataset['current']!;
const StepsTitle = target.querySelector(`.${PREFIX.steps}-title`)!;
const StepsContent = target.querySelector(`.${PREFIX.steps}-content`)!;
const StepsStep = target.querySelectorAll('r-step')!;
const setTitleOrContent = (elem: Element, val: string) => {
if (val && !type.isStr(val)) return;
setHtml(elem, val);
};
return {
get current() {
return Number(target.dataset['current']);
},
set current(newVal: number) {
if (!type.isNum(newVal)) return;
_setCurrentStep(target, newVal, target.dataset['status']!);
},
get title() {
return setHtml(StepsTitle);
},
set title(newVal: string) {
setTitleOrContent(StepsTitle, newVal);
},
get content() {
return setHtml(StepsContent);
},
set content(newVal: string) {
setTitleOrContent(StepsContent, newVal);
},
get status() {
return target.dataset['status']!;
},
set status(newVal: string) {
if (newVal && !type.isStr(newVal)) return;
const currentStep = target.querySelector(`r-step[data-index="${_current}"]`)!;
_setStatus(target, currentStep, newVal);
},
get itemStatus() {
return [];
},
set itemStatus(newVal: string[]) {
if (newVal && !type.isArr(newVal)) return;
const changeStatus = (elem: Element, status: string) => {
elem.setAttribute('status', status);
_setStatusIcon(status, elem);
};
if (newVal.length == 1) {
const step = StepsStep[0];
changeStatus(step, newVal[0]);
return;
}
StepsStep.forEach((step, idx) =>
newVal[idx] ? changeStatus(step, newVal[idx]) : ''
);
}
};
}
private _create(COMPONENTS: NodeListOf<Element>): void {
COMPONENTS.forEach((node) => {
const { current, status, direction } = this._attrs(node);
const StepsStepItem = node.querySelectorAll('r-step');
this._setDirection(node, direction);
this._setStepChildren(StepsStepItem);
this._setCurrentStep(node, current, status);
removeAttrs(node, ['current', 'status']);
});
}
private _setDirection(node: Element, direction: string): void {
node.setAttribute('direction', `${direction}`);
}
private _setStepChildren(stepItem: NodeListOf<Element>): void {
stepItem.forEach((step, idx) => {
// @ts-ignore
step.dataset['index'] = `${idx}`;
this._setStatusFlag(step);
const { icon, title, content } = this._attrs(step);
const stepsText = idx + 1;
const template = `
<div class="${PREFIX.steps}-tail"><i></i></div>
<div class="${PREFIX.steps}-head">
<div class="${PREFIX.steps}-head-inner">
<span id="stepsIcon"></span>
<span id="stepsText">${stepsText}</span>
</div>
</div>
<div class="${PREFIX.steps}-main">
<div class="${PREFIX.steps}-title">${title}</div>
<div class="${PREFIX.steps}-content">${content}</div>
</div>
`;
setHtml(step, template);
this._setCustomIcon(step, icon);
removeAttrs(step, ['title', 'content', 'icon']);
});
}
private _setStatusFlag(step: Element): void {
const status = step.getAttribute('status');
// 如果用户在步骤项设置了status则为该项打上标记,避免被自动设置的默认状态覆盖
if (status) {
// @ts-ignore
step.dataset['specifiesStatus'] = status;
}
}
private _setCurrentStep(node: Element, current: number, status: string): void {
const len = node.childElementCount - 1;
// 防止溢出边界
if (current > len) {
warn(
`The currently active step item you set does not exist in the <r-steps>. --> "${current}"`
);
console.error(node);
current = len;
}
// @ts-ignore
node.dataset['current'] = current;
const { _setStatus } = Steps.prototype;
const currentStep = node.querySelector(`r-step[data-index="${current}"]`)!;
_setStatus(node, currentStep, status);
}
private _setStatus(node: Element, currentStep: Element, status: string): void {
// @ts-ignore
node.dataset['status'] = status;
const { _setStatusIcon, _setPrevAndNextStatus, _setNextError } = Steps.prototype;
// @ts-ignore
const isAutoStatus = currentStep.dataset['autoStatus'];
const selfStatus = currentStep.getAttribute('status');
// 1.如果步骤项设置了status则优先使用该状态,不包括打上autoStatus的标记项。
// 2.如果步骤项父容器指定了某项步骤项为活跃状态,并且指定了 status 则使用该状态。
if (selfStatus && isAutoStatus !== '') {
currentStep.setAttribute('status', selfStatus);
_setStatusIcon(selfStatus, currentStep);
} else {
currentStep.setAttribute('status', status);
_setStatusIcon(status, currentStep);
}
_setPrevAndNextStatus('prev', currentStep, _setStatusIcon);
_setPrevAndNextStatus('next', currentStep, _setStatusIcon);
_setNextError(node);
}
private _setPrevAndNextStatus(
type: 'prev' | 'next',
currentStep: Element,
setStatusIcon: any
): void {
// @ts-ignore
const func = type === 'prev' ? prevAll : nextAll;
const defaultStatus = type === 'prev' ? 'finish' : 'wait';
func(currentStep).forEach((step) => {
// @ts-ignore
const hasSetStatus = step.dataset['specifiesStatus'];
// 当前步骤项位置的其他节点如果没有提示设置status,则默认设置为 finish / wait,并打上标记
// 如果其中有某个设置了则略过
if (!hasSetStatus) {
// @ts-ignore
step.dataset['autoStatus'] = '';
step.setAttribute('status', defaultStatus);
setStatusIcon(defaultStatus, step);
} else {
setStatusIcon(hasSetStatus, step);
}
});
}
private _setStatusIcon(status: string, step: Element): void {
// @ts-ignore
const isUseCustomIcon: boolean = step.dataset['useIcon'] === 'true';
// 如果使用了自定义图标则略过
if (isUseCustomIcon) return;
const StepsIcon = step.querySelector('#stepsIcon')!;
const StepsText = StepsIcon.nextElementSibling!;
// 步骤项状态不为finish或error则显示步骤数字、隐藏图标容器,反之。
if (status !== 'finish' && status !== 'error') {
setCss(StepsIcon, 'display', 'none');
setCss(StepsText, 'display', '');
return;
}
setCss(StepsIcon, 'display', '');
setCss(StepsText, 'display', 'none');
let iconType = '';
if (status === 'finish') {
iconType = 'ios-checkmark';
}
if (status === 'error') {
iconType = 'ios-close';
}
StepsIcon.className = `${PREFIX.steps}-icon ${PREFIX.icon} ${PREFIX.icon}-${iconType}`;
}
private _setCustomIcon(step: Element, icon: string): void {
if (!icon) return;
// @ts-ignore
step.dataset['useIcon'] = 'true';
step.classList.add(`${PREFIX.steps}-custom`);
const StepsIcon = step.querySelector('#stepsIcon')!;
StepsIcon.classList.add(`${PREFIX.icon}`);
StepsIcon.classList.add(`${PREFIX.icon}-${icon}`);
setCss(StepsIcon.nextElementSibling!, 'display', 'none');
}
private _setNextError(node: Element): void {
const StepsStep = node.querySelectorAll('r-step');
StepsStep.forEach((step, idx) => {
if (step.getAttribute('status') === 'error' && idx !== 0) {
const prevStep = StepsStep[idx - 1];
if (prevStep.getAttribute('status') === 'error') {
prevStep.classList.add(`${PREFIX.steps}-next-error`);
} else {
prevStep.classList.remove(`${PREFIX.steps}-next-error`);
}
}
});
}
private _attrs(node: Element) {
return {
current: getNumTypeAttr(node, 'current', 0),
icon: getStrTypeAttr(node, 'icon', ''),
title: getStrTypeAttr(node, 'title', ''),
status: getStrTypeAttr(node, 'status', 'process'),
content: getStrTypeAttr(node, 'content', ''),
direction: getStrTypeAttr(node, 'direction', 'horizontal')
};
}
}
export default Steps; | the_stack |
import {
Component,
Event,
EventEmitter,
h,
Listen,
Method,
Prop,
State,
Watch,
} from '@stencil/core';
import { Disposal } from '../../../utils/Disposal';
import { listen } from '../../../utils/dom';
import { loadSDK } from '../../../utils/network';
import { isString, isUndefined } from '../../../utils/unit';
import { MediaType } from '../../core/player/MediaType';
import { PlayerProps } from '../../core/player/PlayerProps';
import { withComponentRegistry } from '../../core/player/withComponentRegistry';
import { withPlayerContext } from '../../core/player/withPlayerContext';
import {
MediaCrossOriginOption,
MediaFileProvider,
MediaPreloadOption,
} from '../file/MediaFileProvider';
import { dashRegex } from '../file/utils';
import { withProviderConnect } from '../ProviderConnect';
import {
createProviderDispatcher,
ProviderDispatcher,
} from '../ProviderDispatcher';
/**
* Enables loading, playing and controlling
* [MPEG DASH](https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP) based media. It
* uses [`dashjs`](https://github.com/Dash-Industry-Forum/dash.js.md) under the hood.
*
* > You don't interact with this component for passing player properties, controlling playback,
* listening to player events and so on, that is all done through the `vime-player` component.
*/
@Component({
tag: 'vm-dash',
styleUrl: 'dash.css',
shadow: true,
})
export class Dash implements MediaFileProvider<any> {
private dash?: any;
private dispatch!: ProviderDispatcher;
private mediaEl?: HTMLVideoElement;
private videoProvider!: HTMLVmVideoElement;
private textTracksDisposal = new Disposal();
@State() hasAttached = false;
/**
* The URL of the `manifest.mpd` file to use.
*/
@Prop() src!: string;
@Watch('src')
@Watch('hasAttached')
onSrcChange() {
if (!this.hasAttached) return;
this.vmLoadStart.emit();
this.dash?.attachSource(this.src);
}
/**
* The NPM package version of the `dashjs` library to download and use.
*/
@Prop() version = 'latest';
/**
* The URL where the `dashjs` library source can be found. If this property is used, then the
* `version` property is ignored.
*/
@Prop() libSrc?: string;
/**
* The `dashjs` configuration.
*/
@Prop({ attribute: 'config' }) config: Record<string, any> = {};
/** @internal */
@Prop() autoplay = false;
/** @inheritdoc */
@Prop() crossOrigin?: MediaCrossOriginOption;
/** @inheritdoc */
@Prop() preload?: MediaPreloadOption = 'metadata';
/** @inheritdoc */
@Prop() poster?: string;
/** @inheritdoc */
@Prop() controlsList?: string;
/** @inheritdoc */
@Prop({ attribute: 'auto-pip' }) autoPiP?: boolean;
/** @inheritdoc */
@Prop({ attribute: 'disable-pip' }) disablePiP?: boolean;
/** @inheritdoc */
@Prop() disableRemotePlayback?: boolean;
/**
* The title of the current media.
*/
@Prop() mediaTitle?: string;
/**
* Are text tracks enabled by default.
*/
@Prop() enableTextTracksByDefault = true;
/** @internal */
@Prop() shouldRenderNativeTextTracks = true;
@Watch('shouldRenderNativeTextTracks')
onShouldRenderNativeTextTracks() {
if (this.shouldRenderNativeTextTracks) {
this.textTracksDisposal.empty();
} else {
this.hideCurrentTextTrack();
}
this.dash?.enableForcedTextStreaming(!this.shouldRenderNativeTextTracks);
}
/** @internal */
@Prop() isTextTrackVisible = true;
/** @internal */
@Prop() currentTextTrack = -1;
@Watch('isTextTrackVisible')
@Watch('currentTextTrack')
onTextTrackChange() {
if (!this.shouldRenderNativeTextTracks || isUndefined(this.dash)) return;
this.dash.setTextTrack(
!this.isTextTrackVisible ? -1 : this.currentTextTrack,
);
if (!this.isTextTrackVisible) {
const track = Array.from(this.mediaEl?.textTracks ?? [])[
this.currentTextTrack
];
if (track?.mode === 'hidden') this.dispatch('currentTextTrack', -1);
}
}
/** @internal */
@Event() vmLoadStart!: EventEmitter<void>;
/**
* Emitted when an error has occurred.
*/
@Event() vmError!: EventEmitter<any>;
constructor() {
withComponentRegistry(this);
withProviderConnect(this);
withPlayerContext(this, [
'autoplay',
'shouldRenderNativeTextTracks',
'isTextTrackVisible',
'currentTextTrack',
]);
}
connectedCallback() {
this.dispatch = createProviderDispatcher(this);
if (this.mediaEl) this.setupDash();
}
disconnectedCallback() {
this.textTracksDisposal.empty();
this.destroyDash();
}
private async setupDash() {
try {
const url =
this.libSrc ||
`https://cdn.jsdelivr.net/npm/dashjs@${this.version}/dist/dash.all.min.js`;
const DashSDK = (await loadSDK(url, 'dashjs')) as any;
this.dash = DashSDK.MediaPlayer(this.config).create();
this.dash.initialize(this.mediaEl, null, this.autoplay);
this.dash.setTextDefaultEnabled(this.enableTextTracksByDefault);
this.dash.enableForcedTextStreaming(!this.shouldRenderNativeTextTracks);
this.dash.on(DashSDK.MediaPlayer.events.PLAYBACK_METADATA_LOADED, () => {
this.dispatch('mediaType', MediaType.Video);
this.dispatch('currentSrc', this.src);
this.dispatchLevels();
this.listenToTextTracksForChanges();
this.dispatch('playbackReady', true);
});
this.dash.on(DashSDK.MediaPlayer.events.TRACK_CHANGE_RENDERED, () => {
if (!this.shouldRenderNativeTextTracks) this.hideCurrentTextTrack();
});
this.dash.on(DashSDK.MediaPlayer.events.ERROR, (e: any) => {
this.vmError.emit(e);
});
this.hasAttached = true;
} catch (e) {
this.vmError.emit(e);
}
}
private async destroyDash() {
this.dash?.reset();
this.hasAttached = false;
}
@Listen('vmMediaElChange')
async onMediaElChange(event: CustomEvent<HTMLVideoElement | undefined>) {
this.destroyDash();
if (isUndefined(event.detail)) return;
this.mediaEl = event.detail;
await this.setupDash();
}
private levelToPlaybackQuality(level: any) {
return level === -1 ? 'Auto' : `${level.height}p`;
}
private findLevelIndexFromQuality(quality: PlayerProps['playbackQuality']) {
return this.dash
.getBitrateInfoListFor('video')
.findIndex(
(level: any) => this.levelToPlaybackQuality(level) === quality,
);
}
private dispatchLevels() {
try {
const levels = this.dash.getBitrateInfoListFor('video');
if (levels?.length > 0) {
this.dispatch('playbackQualities', [
'Auto',
...levels.map(this.levelToPlaybackQuality),
]);
this.dispatch('playbackQuality', 'Auto');
}
} catch (e) {
this.vmError.emit(e);
}
}
private listenToTextTracksForChanges() {
this.textTracksDisposal.empty();
if (isUndefined(this.mediaEl) || this.shouldRenderNativeTextTracks) return;
// Init current track.
const currentTrack = this.dash?.getCurrentTrackFor('text')?.index - 1 ?? -1;
this.currentTextTrack = currentTrack;
this.dispatch('currentTextTrack', currentTrack);
this.textTracksDisposal.add(
listen(
this.mediaEl.textTracks,
'change',
this.onTextTracksChange.bind(this),
),
);
}
private getTextTracks() {
return Array.from(this.mediaEl?.textTracks ?? []);
}
private hideCurrentTextTrack() {
const textTracks = this.getTextTracks();
if (textTracks[this.currentTextTrack] && this.isTextTrackVisible) {
textTracks[this.currentTextTrack].mode = 'hidden';
}
}
private onTextTracksChange() {
this.hideCurrentTextTrack();
this.dispatch('textTracks', this.getTextTracks());
this.dispatch('isTextTrackVisible', this.isTextTrackVisible);
this.dispatch('currentTextTrack', this.currentTextTrack);
}
/** @internal */
@Method()
async getAdapter() {
const adapter = (await this.videoProvider?.getAdapter()) ?? {};
const canVideoProviderPlay = adapter.canPlay;
return {
...adapter,
getInternalPlayer: async () => this.dash,
canPlay: async (type: any) =>
(isString(type) && dashRegex.test(type)) ||
(canVideoProviderPlay?.(type) ?? false),
canSetPlaybackQuality: async () => {
try {
return this.dash?.getBitrateInfoListFor('video')?.length > 0;
} catch (e) {
this.vmError.emit(e);
return false;
}
},
setPlaybackQuality: async (quality: string) => {
if (!isUndefined(this.dash)) {
const index = this.findLevelIndexFromQuality(quality);
this.dash.updateSettings({
streaming: {
abr: {
autoSwitchBitrate: {
video: index === -1,
},
},
},
});
if (index >= 0) this.dash.setQualityFor('video', index);
// Update the provider cache.
this.dispatch('playbackQuality', quality);
}
},
setCurrentTextTrack: async (trackId: number) => {
if (this.shouldRenderNativeTextTracks) {
adapter.setCurrentTextTrack(trackId);
} else {
this.currentTextTrack = trackId;
this.dash?.setTextTrack(trackId);
this.onTextTracksChange();
}
},
setTextTrackVisibility: async (isVisible: boolean) => {
if (this.shouldRenderNativeTextTracks) {
adapter.setTextTrackVisibility(isVisible);
} else {
this.isTextTrackVisible = isVisible;
this.dash?.enableText(isVisible);
this.onTextTracksChange();
}
},
};
}
render() {
return (
<vm-video
willAttach
crossOrigin={this.crossOrigin}
preload={this.preload}
poster={this.poster}
controlsList={this.controlsList}
autoPiP={this.autoPiP}
disablePiP={this.disablePiP}
hasCustomTextManager={!this.shouldRenderNativeTextTracks}
disableRemotePlayback={this.disableRemotePlayback}
mediaTitle={this.mediaTitle}
ref={(el: any) => {
this.videoProvider = el;
}}
/>
);
}
} | the_stack |
import { jsx } from '@emotion/react'
import React from 'react'
import Utils from '../../../utils/utils'
import { CanvasPoint, CanvasRectangle } from '../../../core/shared/math-utils'
import { EditorDispatch } from '../../editor/action-types'
import {
setCanvasAnimationsEnabled,
setResizeOptionsTargetOptions,
} from '../../editor/actions/action-creators'
import { ControlFontSize } from '../canvas-controls-frame'
import {
CSSCursor,
ResizeDragState,
resizeDragState,
CanvasPositions,
EdgePosition,
EnabledDirection,
DirectionVertical,
DirectionHorizontal,
DirectionAll,
DragState,
updateResizeDragState,
} from '../canvas-types'
import { ResizeStatus } from './new-canvas-controls'
import { ElementPath } from '../../../core/shared/project-file-types'
import CanvasActions from '../canvas-actions'
import { OriginalCanvasAndLocalFrame, ResizeOptions } from '../../editor/store/editor-state'
import {
DetectedLayoutSystem,
ElementInstanceMetadata,
ElementInstanceMetadataMap,
} from '../../../core/shared/element-template'
import { isFeatureEnabled } from '../../../utils/feature-switches'
import { SizeBoxLabel } from './size-box-label'
//TODO: switch to functional component and make use of 'useColorTheme':
import { colorTheme as fixmeColorTheme, useColorTheme } from '../../../uuiui'
import { LayoutTargetableProp } from '../../../core/layout/layout-helpers-new'
import { PropertyTargetSelector } from './property-target-selector'
import { unless, when } from '../../../utils/react-conditionals'
import { isZeroSizedElement } from './outline-utils'
import { ZeroSizeResizeControl } from './zero-sized-element-controls'
import {
anyDragStarted,
getDragStateStart,
getResizeOptions,
isTargetPropertyHorizontal,
} from '../canvas-utils'
import { safeIndex } from '../../../core/shared/array-utils'
import { CSSPosition } from '../../inspector/common/css-utils'
import * as EP from '../../../core/shared/element-path'
interface ResizeControlProps extends ResizeRectangleProps {
cursor: CSSCursor
position: EdgePosition
enabledDirection: EnabledDirection
selectedViews: Array<ElementPath>
dragState: ResizeDragState | null
propertyTargetSelectedIndex: number
}
function layoutSystemForPositionOrFlex(
position: CSSPosition | null | undefined,
flexDirection: 'horizontal' | 'vertical' | null,
): 'flex-horizontal' | 'flex-vertical' | 'absolute' | null {
if (position === 'absolute') {
return 'absolute'
} else if (flexDirection === 'horizontal') {
return 'flex-horizontal'
} else if (flexDirection === 'vertical') {
return 'flex-vertical'
} else {
return null
}
}
class ResizeControl extends React.Component<ResizeControlProps> {
reference = React.createRef<HTMLDivElement>()
constructor(props: ResizeControlProps) {
super(props)
}
componentWillUnmount() {
this.props.dispatch([setCanvasAnimationsEnabled(true)], 'canvas')
}
onMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
event.stopPropagation()
if (event.buttons === 1) {
const beforeOrAfter =
this.props.position.y === 0.5 ? this.props.position.x : this.props.position.y
const edge = beforeOrAfter === 0 ? 'before' : 'after'
const centerBasedResize = event.altKey
const keepAspectRatio = event.shiftKey || this.props.elementAspectRatioLocked
const enableSnapping = !event.metaKey
const canvasPositions = this.props.windowToCanvasPosition(event.nativeEvent)
const start: CanvasPoint = canvasPositions.canvasPositionRaw
const originalFrames = this.props.getOriginalFrames()
const isMultiSelect = this.props.selectedViews.length !== 1
const enabledDirection = this.props.enabledDirection
let propertyTargetOptions: Array<LayoutTargetableProp> = []
const layoutSystem = layoutSystemForPositionOrFlex(
this.props.targetComponentMetadata?.specialSizeMeasurements.position,
this.props.flexDirection,
)
if (enabledDirection.x === 1 && enabledDirection.y === 0) {
// Left to right resize.
propertyTargetOptions = getResizeOptions(layoutSystem, 'vertical', edge)
} else if (enabledDirection.x === 0 && enabledDirection.y === 1) {
// Up to down resize.
propertyTargetOptions = getResizeOptions(layoutSystem, 'horizontal', edge)
} else {
// Diagonal resize of some kind.
}
const targetProperty = safeIndex(
propertyTargetOptions,
this.props.propertyTargetSelectedIndex,
)
const newDragState = updateResizeDragState(
resizeDragState(
this.props.measureSize,
originalFrames,
this.props.position,
this.props.enabledDirection,
this.props.metadata,
this.props.selectedViews,
isMultiSelect,
[],
),
start,
null,
targetProperty,
enableSnapping,
centerBasedResize,
keepAspectRatio,
)
this.props.dispatch(
[
CanvasActions.createDragState(newDragState),
setCanvasAnimationsEnabled(false),
setResizeOptionsTargetOptions(
propertyTargetOptions,
this.props.propertyTargetSelectedIndex,
),
],
'canvas',
)
this.props.onResizeStart(this.props.measureSize, this.props.position)
}
}
onMouseMove = (event: React.MouseEvent<any>) => {
this.props.maybeClearHighlightsOnHoverEnd()
event.stopPropagation()
}
render() {
return (
<React.Fragment>
{this.props.resizeStatus === 'enabled' ? (
<div onMouseDown={this.onMouseDown} onMouseMove={this.onMouseMove}>
{this.props.children}
</div>
) : (
this.props.children
)}
</React.Fragment>
)
}
}
interface ResizeEdgeProps {
dispatch: EditorDispatch
cursor: CSSCursor
direction: 'horizontal' | 'vertical'
canvasOffset: CanvasPoint
visualSize: CanvasRectangle
scale: number
position: EdgePosition
resizeStatus: ResizeStatus
targetComponentMetadata: ElementInstanceMetadata | null
dragState: DragState | null
}
interface ResizeEdgeState {}
function allowsInteractiveResize(layoutSystem: DetectedLayoutSystem): boolean {
switch (layoutSystem) {
case 'flex':
case 'flow':
return true
case 'grid':
case 'none':
return false
default:
const _exhaustiveCheck: never = layoutSystem
throw new Error(`Unhandled layoutSystem ${JSON.stringify(layoutSystem)}`)
}
}
function shiftPropertyTargetSelectorAxis(
primaryDirection: 'horizontal' | 'vertical',
actualDirection: 'horizontal' | 'vertical',
edge: 'before' | 'after',
): number {
if (actualDirection === primaryDirection) {
if (edge === 'before') {
return 25
} else {
return 10
}
} else {
return 10
}
}
class ResizeEdge extends React.Component<ResizeEdgeProps, ResizeEdgeState> {
constructor(props: ResizeEdgeProps) {
super(props)
}
reference = React.createRef<HTMLDivElement>()
render() {
if (this.props.resizeStatus != 'enabled') {
return null
}
const beforeOrAfter =
this.props.position.y === 0.5 ? this.props.position.x : this.props.position.y
const edge = beforeOrAfter === 0 ? 'before' : 'after'
const baseLeft =
this.props.canvasOffset.x +
this.props.visualSize.x +
this.props.position.x * this.props.visualSize.width
const baseTop =
this.props.canvasOffset.y +
this.props.visualSize.y +
this.props.position.y * this.props.visualSize.height
const lineSize = 10 / this.props.scale
const width = this.props.direction === 'horizontal' ? this.props.visualSize.width : lineSize
const height = this.props.direction === 'vertical' ? this.props.visualSize.height : lineSize
const left =
baseLeft +
(this.props.direction === 'horizontal' ? -this.props.visualSize.width / 2 : -lineSize / 2)
const top =
baseTop +
(this.props.direction === 'vertical' ? -this.props.visualSize.height / 2 : -lineSize / 2)
const displayResizeSelector =
this.props.dragState != null &&
this.props.dragState.type === 'RESIZE_DRAG_STATE' &&
anyDragStarted(this.props.dragState) &&
this.props.dragState.edgePosition.x === this.props.position.x &&
this.props.dragState.edgePosition.y === this.props.position.y
const interactiveResize =
this.props.targetComponentMetadata != null &&
allowsInteractiveResize(
this.props.targetComponentMetadata.specialSizeMeasurements.parentLayoutSystem,
)
const layoutSystem = layoutSystemForPositionOrFlex(
this.props.targetComponentMetadata?.specialSizeMeasurements.position,
null,
)
return (
<React.Fragment>
<div
ref={this.reference}
style={{
pointerEvents: 'initial',
position: 'absolute',
left: left,
top: top,
width: width,
height: height,
boxSizing: 'border-box',
backgroundColor: 'transparent',
cursor: this.props.resizeStatus === 'enabled' ? this.props.cursor : undefined,
}}
/>
{when(
displayResizeSelector && interactiveResize,
<PropertyTargetSelector
top={top + shiftPropertyTargetSelectorAxis('horizontal', this.props.direction, edge)}
left={left + shiftPropertyTargetSelectorAxis('vertical', this.props.direction, edge)}
options={getResizeOptions(layoutSystem, this.props.direction, edge)}
targetComponentMetadata={this.props.targetComponentMetadata}
key={
this.props.targetComponentMetadata != null
? EP.toString(this.props.targetComponentMetadata.elementPath)
: `${this.props.direction}-${this.props.position.x}-${this.props.position.y}`
}
/>,
)}
</React.Fragment>
)
}
}
interface ResizeLinesProps {
targetComponentMetadata: ElementInstanceMetadata | null
cursor: CSSCursor
direction: 'horizontal' | 'vertical'
canvasOffset: CanvasPoint
visualSize: CanvasRectangle
scale: number
position: EdgePosition
resizeStatus: ResizeStatus
dragState: DragState | null
color?: string
flexDirection: 'horizontal' | 'vertical' | null
}
const LineOffset = 6
const ResizeLines = React.memo((props: ResizeLinesProps) => {
const reference = React.createRef<HTMLDivElement>()
const LineSVGComponent =
props.position.y === 0.5 ? DimensionableControlVertical : DimensionableControlHorizontal
const beforeOrAfter = props.position.y === 0.5 ? props.position.x : props.position.y
const edge = beforeOrAfter === 0 ? 'before' : 'after'
const displayResizeSelector =
props.dragState != null &&
props.dragState.type === 'RESIZE_DRAG_STATE' &&
anyDragStarted(props.dragState) &&
props.dragState.edgePosition.x === props.position.x &&
props.dragState.edgePosition.y === props.position.y
const left = props.canvasOffset.x + props.visualSize.x + props.position.x * props.visualSize.width
const top = props.canvasOffset.y + props.visualSize.y + props.position.y * props.visualSize.height
const catchmentSize = 12 / props.scale
const mouseCatcher =
props.resizeStatus !== 'enabled' ? null : (
<div
ref={reference}
style={{
pointerEvents: 'initial',
position: 'absolute',
width: catchmentSize,
height: catchmentSize,
top: top - catchmentSize / 2,
left: left - catchmentSize / 2,
backgroundColor: 'transparent',
cursor: props.cursor,
}}
/>
)
const interactiveResize = React.useMemo(() => {
return (
props.targetComponentMetadata != null &&
allowsInteractiveResize(
props.targetComponentMetadata.specialSizeMeasurements.parentLayoutSystem,
)
)
}, [props.targetComponentMetadata])
const layoutSystem = layoutSystemForPositionOrFlex(
props.targetComponentMetadata?.specialSizeMeasurements.position,
props.flexDirection,
)
return (
<React.Fragment>
<LineSVGComponent
scale={props.scale}
centerX={left}
centerY={top}
edge={edge}
color={props.color}
/>
{when(
displayResizeSelector && interactiveResize,
<PropertyTargetSelector
top={top + shiftPropertyTargetSelectorAxis('horizontal', props.direction, edge)}
left={left + shiftPropertyTargetSelectorAxis('vertical', props.direction, edge)}
options={getResizeOptions(layoutSystem, props.direction, edge)}
targetComponentMetadata={props.targetComponentMetadata}
key={
props.targetComponentMetadata != null
? EP.toString(props.targetComponentMetadata.elementPath)
: `${props.direction}-${props.position.x}-${props.position.y}`
}
/>,
)}
{mouseCatcher}
</React.Fragment>
)
})
interface DimensionableControlProps {
centerX: number
centerY: number
edge: 'before' | 'after'
color?: string
scale: number
}
const ControlSideShort = 3
const ControlSideLong = 8
const DimensionableControlVertical = (props: DimensionableControlProps) => {
const colorTheme = useColorTheme()
const controlLength = 15
const controlWidth = ControlSideShort
const scaledControlLength = controlLength / props.scale
const scaledControlOffsetTop = -(scaledControlLength / 2)
return (
<div
className='label-dimensionableControlVertical'
style={{
position: 'absolute',
backgroundColor: colorTheme.primary.shade(10).value,
borderRadius: `${5 / props.scale}px`,
// These just about work. I can clean them up afterwards
boxShadow: `0px 0px 0px ${0.3 / props.scale}px ${colorTheme.primary.value}, 0px ${
1 / props.scale
}px ${3 / props.scale}px rgba(140,140,140,.9)`,
height: controlLength / props.scale,
width: controlWidth / props.scale,
left: props.centerX - 1,
top: props.centerY + scaledControlOffsetTop,
}}
/>
)
}
const DimensionableControlHorizontal = (props: DimensionableControlProps) => {
const colorTheme = useColorTheme()
const controlLength = ControlSideShort
const controlWidth = 15
const scaledControlWidth = controlWidth / props.scale
const scaledControlOffsetLeft = -(scaledControlWidth / 2)
return (
<div
className='label-dimensionableControlVertical'
style={{
position: 'absolute',
backgroundColor: colorTheme.primary.shade(10).value,
borderRadius: `${5 / props.scale}px`,
// These just about work. I can clean them up afterwards
boxShadow: `0px 0px 0px ${0.3 / props.scale}px ${colorTheme.primary.value}, 0px ${
1 / props.scale
}px ${3 / props.scale}px rgba(140,140,140,.9)`,
height: controlLength / props.scale,
width: controlWidth / props.scale,
left: props.centerX + scaledControlOffsetLeft,
top: props.centerY - 1,
}}
/>
)
}
interface ResizePointProps {
dispatch: EditorDispatch
cursor: CSSCursor
canvasOffset: CanvasPoint
visualSize: CanvasRectangle
scale: number
position: EdgePosition
resizeStatus: ResizeStatus
extraStyle?: React.CSSProperties
testID: string
}
class ResizePoint extends React.Component<ResizePointProps> {
reference = React.createRef<HTMLDivElement>()
render() {
const left =
this.props.canvasOffset.x +
this.props.visualSize.x +
this.props.position.x * this.props.visualSize.width
const top =
this.props.canvasOffset.y +
this.props.visualSize.y +
this.props.position.y * this.props.visualSize.height
const size = 6 / this.props.scale
const catchmentSize = 12 / this.props.scale
const mouseCatcher =
this.props.resizeStatus !== 'enabled' ? null : (
<div
ref={this.reference}
style={{
position: 'absolute',
width: catchmentSize,
height: catchmentSize,
top: top - catchmentSize / 2,
left: left - catchmentSize / 2,
backgroundColor: 'transparent',
cursor: this.props.cursor,
}}
data-testid={`${this.props.testID}-${this.props.position.x}-${this.props.position.y}`}
/>
)
return (
<React.Fragment>
<div
style={{
pointerEvents: 'initial',
position: 'absolute',
width: size,
height: size,
top: top - size / 2,
left: left - size / 2,
borderWidth: 1 / this.props.scale,
boxSizing: 'border-box',
backgroundColor: fixmeColorTheme.canvasControlsSizeBoxBackground.value,
borderRadius: '10%',
borderStyle: 'none',
borderColor: 'transparent',
boxShadow: `${fixmeColorTheme.canvasControlsSizeBoxShadowColor.o(50).value} 0px 0px ${
1 / this.props.scale
}px, ${fixmeColorTheme.canvasControlsSizeBoxShadowColor.o(21).value} 0px ${
1 / this.props.scale
}px ${2 / this.props.scale}px ${1 / this.props.scale}px `,
...this.props.extraStyle,
}}
/>
{mouseCatcher}
</React.Fragment>
)
}
}
interface ResizeRectangleProps {
targetComponentMetadata: ElementInstanceMetadata | null
dispatch: EditorDispatch
scale: number
canvasOffset: CanvasPoint
measureSize: CanvasRectangle // this is the size we want to adjust when the user drags
visualSize: CanvasRectangle // this is the canvas size of the selection (might not be the same as measureSize in case of Yoga)
resizeStatus: ResizeStatus
selectedViews: Array<ElementPath>
elementAspectRatioLocked: boolean
imageMultiplier: number | null
sideResizer: boolean
color?: string
dragState: ResizeDragState | null
windowToCanvasPosition: (event: MouseEvent) => CanvasPositions
getOriginalFrames: () => Array<OriginalCanvasAndLocalFrame>
metadata: ElementInstanceMetadataMap
onResizeStart: (originalSize: CanvasRectangle, draggedPoint: EdgePosition) => void
testID: string
maybeClearHighlightsOnHoverEnd: () => void
flexDirection: 'horizontal' | 'vertical' | null
propertyTargetSelectedIndex: number
}
export class ResizeRectangle extends React.Component<ResizeRectangleProps> {
render() {
const controlProps = this.props
if (isZeroSizedElement(this.props.measureSize)) {
return (
<ZeroSizeResizeControl
frame={this.props.measureSize}
canvasOffset={this.props.canvasOffset}
scale={this.props.scale}
color={null}
dispatch={this.props.dispatch}
element={this.props.targetComponentMetadata}
maybeClearHighlightsOnHoverEnd={this.props.maybeClearHighlightsOnHoverEnd}
/>
)
} else if (
this.props.resizeStatus === 'enabled' ||
this.props.resizeStatus === 'noninteractive'
) {
const pointControls = unless(
this.props.sideResizer,
<React.Fragment>
<ResizeControl
{...controlProps}
key={'resize-control-v-0.5-0.0'}
cursor={CSSCursor.ResizeNS}
position={{ x: 0.5, y: 0 }}
enabledDirection={DirectionVertical}
>
<ResizeEdge
{...controlProps}
cursor={CSSCursor.ResizeNS}
direction='horizontal'
position={{ x: 0.5, y: 0 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-v-0.5-1.0'}
cursor={CSSCursor.ResizeNS}
position={{ x: 0.5, y: 1 }}
enabledDirection={DirectionVertical}
>
<ResizeEdge
{...controlProps}
cursor={CSSCursor.ResizeNS}
direction='horizontal'
position={{ x: 0.5, y: 1 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-h-0.0-0.5'}
cursor={CSSCursor.ResizeEW}
position={{ x: 0, y: 0.5 }}
enabledDirection={DirectionHorizontal}
>
<ResizeEdge
{...controlProps}
cursor={CSSCursor.ResizeEW}
direction='vertical'
position={{ x: 0, y: 0.5 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-h-1.0-0.5'}
cursor={CSSCursor.ResizeEW}
position={{ x: 1, y: 0.5 }}
enabledDirection={DirectionHorizontal}
>
<ResizeEdge
{...controlProps}
cursor={CSSCursor.ResizeEW}
direction='vertical'
position={{ x: 1, y: 0.5 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-a-0.0-0.0'}
cursor={CSSCursor.ResizeNWSE}
position={{ x: 0, y: 0 }}
enabledDirection={DirectionAll}
>
<ResizePoint
{...controlProps}
cursor={CSSCursor.ResizeNWSE}
position={{ x: 0, y: 0 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-a-1.0-0.0'}
cursor={CSSCursor.ResizeNESW}
position={{ x: 1, y: 0 }}
enabledDirection={DirectionAll}
>
<ResizePoint
{...controlProps}
cursor={CSSCursor.ResizeNESW}
position={{ x: 1, y: 0 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-a-0.0-1.0'}
cursor={CSSCursor.ResizeNESW}
position={{ x: 0, y: 1 }}
enabledDirection={DirectionAll}
>
<ResizePoint
{...controlProps}
cursor={CSSCursor.ResizeNESW}
position={{ x: 0, y: 1 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-a-1.0-1.0'}
cursor={CSSCursor.ResizeNWSE}
position={{ x: 1, y: 1 }}
enabledDirection={DirectionAll}
>
<ResizePoint
{...controlProps}
cursor={CSSCursor.ResizeNWSE}
position={{ x: 1, y: 1 }}
/>
</ResizeControl>
</React.Fragment>,
)
const resizeLines = when(
this.props.sideResizer,
<React.Fragment>
<ResizeControl
{...controlProps}
key={'resize-control-v-0.5-1.0'}
cursor={CSSCursor.ResizeNS}
position={{ x: 0.5, y: 1 }}
enabledDirection={DirectionVertical}
>
<ResizeLines
{...controlProps}
cursor={CSSCursor.ResizeNS}
direction='horizontal'
position={{ x: 0.5, y: 1 }}
/>
</ResizeControl>
<ResizeControl
{...controlProps}
key={'resize-control-h-1.0-0.5'}
cursor={CSSCursor.ResizeEW}
position={{ x: 1, y: 0.5 }}
enabledDirection={DirectionHorizontal}
>
<ResizeLines
{...controlProps}
cursor={CSSCursor.ResizeEW}
direction='vertical'
position={{ x: 1, y: 0.5 }}
/>
</ResizeControl>
</React.Fragment>,
)
return (
<React.Fragment>
{resizeLines}
{pointControls}
</React.Fragment>
)
} else {
return null
}
}
} | the_stack |
import * as grpc from "grpc";
import * as commands_pb from "./commands_pb";
import * as common_pb from "./common_pb";
import * as board_pb from "./board_pb";
import * as compile_pb from "./compile_pb";
import * as core_pb from "./core_pb";
import * as upload_pb from "./upload_pb";
import * as lib_pb from "./lib_pb";
interface IArduinoCoreService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
init: IArduinoCoreService_IInit;
destroy: IArduinoCoreService_IDestroy;
rescan: IArduinoCoreService_IRescan;
updateIndex: IArduinoCoreService_IUpdateIndex;
updateLibrariesIndex: IArduinoCoreService_IUpdateLibrariesIndex;
version: IArduinoCoreService_IVersion;
boardDetails: IArduinoCoreService_IBoardDetails;
boardAttach: IArduinoCoreService_IBoardAttach;
boardList: IArduinoCoreService_IBoardList;
boardListAll: IArduinoCoreService_IBoardListAll;
compile: IArduinoCoreService_ICompile;
platformInstall: IArduinoCoreService_IPlatformInstall;
platformDownload: IArduinoCoreService_IPlatformDownload;
platformUninstall: IArduinoCoreService_IPlatformUninstall;
platformUpgrade: IArduinoCoreService_IPlatformUpgrade;
upload: IArduinoCoreService_IUpload;
platformSearch: IArduinoCoreService_IPlatformSearch;
platformList: IArduinoCoreService_IPlatformList;
libraryDownload: IArduinoCoreService_ILibraryDownload;
libraryInstall: IArduinoCoreService_ILibraryInstall;
libraryUninstall: IArduinoCoreService_ILibraryUninstall;
libraryUpgradeAll: IArduinoCoreService_ILibraryUpgradeAll;
librarySearch: IArduinoCoreService_ILibrarySearch;
libraryList: IArduinoCoreService_ILibraryList;
}
interface IArduinoCoreService_IInit extends grpc.MethodDefinition<commands_pb.InitReq, commands_pb.InitResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/Init"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<commands_pb.InitReq>;
requestDeserialize: grpc.deserialize<commands_pb.InitReq>;
responseSerialize: grpc.serialize<commands_pb.InitResp>;
responseDeserialize: grpc.deserialize<commands_pb.InitResp>;
}
interface IArduinoCoreService_IDestroy extends grpc.MethodDefinition<commands_pb.DestroyReq, commands_pb.DestroyResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/Destroy"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<commands_pb.DestroyReq>;
requestDeserialize: grpc.deserialize<commands_pb.DestroyReq>;
responseSerialize: grpc.serialize<commands_pb.DestroyResp>;
responseDeserialize: grpc.deserialize<commands_pb.DestroyResp>;
}
interface IArduinoCoreService_IRescan extends grpc.MethodDefinition<commands_pb.RescanReq, commands_pb.RescanResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/Rescan"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<commands_pb.RescanReq>;
requestDeserialize: grpc.deserialize<commands_pb.RescanReq>;
responseSerialize: grpc.serialize<commands_pb.RescanResp>;
responseDeserialize: grpc.deserialize<commands_pb.RescanResp>;
}
interface IArduinoCoreService_IUpdateIndex extends grpc.MethodDefinition<commands_pb.UpdateIndexReq, commands_pb.UpdateIndexResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/UpdateIndex"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<commands_pb.UpdateIndexReq>;
requestDeserialize: grpc.deserialize<commands_pb.UpdateIndexReq>;
responseSerialize: grpc.serialize<commands_pb.UpdateIndexResp>;
responseDeserialize: grpc.deserialize<commands_pb.UpdateIndexResp>;
}
interface IArduinoCoreService_IUpdateLibrariesIndex extends grpc.MethodDefinition<commands_pb.UpdateLibrariesIndexReq, commands_pb.UpdateLibrariesIndexResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/UpdateLibrariesIndex"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<commands_pb.UpdateLibrariesIndexReq>;
requestDeserialize: grpc.deserialize<commands_pb.UpdateLibrariesIndexReq>;
responseSerialize: grpc.serialize<commands_pb.UpdateLibrariesIndexResp>;
responseDeserialize: grpc.deserialize<commands_pb.UpdateLibrariesIndexResp>;
}
interface IArduinoCoreService_IVersion extends grpc.MethodDefinition<commands_pb.VersionReq, commands_pb.VersionResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/Version"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<commands_pb.VersionReq>;
requestDeserialize: grpc.deserialize<commands_pb.VersionReq>;
responseSerialize: grpc.serialize<commands_pb.VersionResp>;
responseDeserialize: grpc.deserialize<commands_pb.VersionResp>;
}
interface IArduinoCoreService_IBoardDetails extends grpc.MethodDefinition<board_pb.BoardDetailsReq, board_pb.BoardDetailsResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/BoardDetails"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<board_pb.BoardDetailsReq>;
requestDeserialize: grpc.deserialize<board_pb.BoardDetailsReq>;
responseSerialize: grpc.serialize<board_pb.BoardDetailsResp>;
responseDeserialize: grpc.deserialize<board_pb.BoardDetailsResp>;
}
interface IArduinoCoreService_IBoardAttach extends grpc.MethodDefinition<board_pb.BoardAttachReq, board_pb.BoardAttachResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/BoardAttach"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<board_pb.BoardAttachReq>;
requestDeserialize: grpc.deserialize<board_pb.BoardAttachReq>;
responseSerialize: grpc.serialize<board_pb.BoardAttachResp>;
responseDeserialize: grpc.deserialize<board_pb.BoardAttachResp>;
}
interface IArduinoCoreService_IBoardList extends grpc.MethodDefinition<board_pb.BoardListReq, board_pb.BoardListResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/BoardList"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<board_pb.BoardListReq>;
requestDeserialize: grpc.deserialize<board_pb.BoardListReq>;
responseSerialize: grpc.serialize<board_pb.BoardListResp>;
responseDeserialize: grpc.deserialize<board_pb.BoardListResp>;
}
interface IArduinoCoreService_IBoardListAll extends grpc.MethodDefinition<board_pb.BoardListAllReq, board_pb.BoardListAllResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/BoardListAll"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<board_pb.BoardListAllReq>;
requestDeserialize: grpc.deserialize<board_pb.BoardListAllReq>;
responseSerialize: grpc.serialize<board_pb.BoardListAllResp>;
responseDeserialize: grpc.deserialize<board_pb.BoardListAllResp>;
}
interface IArduinoCoreService_ICompile extends grpc.MethodDefinition<compile_pb.CompileReq, compile_pb.CompileResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/Compile"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<compile_pb.CompileReq>;
requestDeserialize: grpc.deserialize<compile_pb.CompileReq>;
responseSerialize: grpc.serialize<compile_pb.CompileResp>;
responseDeserialize: grpc.deserialize<compile_pb.CompileResp>;
}
interface IArduinoCoreService_IPlatformInstall extends grpc.MethodDefinition<core_pb.PlatformInstallReq, core_pb.PlatformInstallResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/PlatformInstall"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<core_pb.PlatformInstallReq>;
requestDeserialize: grpc.deserialize<core_pb.PlatformInstallReq>;
responseSerialize: grpc.serialize<core_pb.PlatformInstallResp>;
responseDeserialize: grpc.deserialize<core_pb.PlatformInstallResp>;
}
interface IArduinoCoreService_IPlatformDownload extends grpc.MethodDefinition<core_pb.PlatformDownloadReq, core_pb.PlatformDownloadResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/PlatformDownload"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<core_pb.PlatformDownloadReq>;
requestDeserialize: grpc.deserialize<core_pb.PlatformDownloadReq>;
responseSerialize: grpc.serialize<core_pb.PlatformDownloadResp>;
responseDeserialize: grpc.deserialize<core_pb.PlatformDownloadResp>;
}
interface IArduinoCoreService_IPlatformUninstall extends grpc.MethodDefinition<core_pb.PlatformUninstallReq, core_pb.PlatformUninstallResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/PlatformUninstall"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<core_pb.PlatformUninstallReq>;
requestDeserialize: grpc.deserialize<core_pb.PlatformUninstallReq>;
responseSerialize: grpc.serialize<core_pb.PlatformUninstallResp>;
responseDeserialize: grpc.deserialize<core_pb.PlatformUninstallResp>;
}
interface IArduinoCoreService_IPlatformUpgrade extends grpc.MethodDefinition<core_pb.PlatformUpgradeReq, core_pb.PlatformUpgradeResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/PlatformUpgrade"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<core_pb.PlatformUpgradeReq>;
requestDeserialize: grpc.deserialize<core_pb.PlatformUpgradeReq>;
responseSerialize: grpc.serialize<core_pb.PlatformUpgradeResp>;
responseDeserialize: grpc.deserialize<core_pb.PlatformUpgradeResp>;
}
interface IArduinoCoreService_IUpload extends grpc.MethodDefinition<upload_pb.UploadReq, upload_pb.UploadResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/Upload"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<upload_pb.UploadReq>;
requestDeserialize: grpc.deserialize<upload_pb.UploadReq>;
responseSerialize: grpc.serialize<upload_pb.UploadResp>;
responseDeserialize: grpc.deserialize<upload_pb.UploadResp>;
}
interface IArduinoCoreService_IPlatformSearch extends grpc.MethodDefinition<core_pb.PlatformSearchReq, core_pb.PlatformSearchResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/PlatformSearch"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<core_pb.PlatformSearchReq>;
requestDeserialize: grpc.deserialize<core_pb.PlatformSearchReq>;
responseSerialize: grpc.serialize<core_pb.PlatformSearchResp>;
responseDeserialize: grpc.deserialize<core_pb.PlatformSearchResp>;
}
interface IArduinoCoreService_IPlatformList extends grpc.MethodDefinition<core_pb.PlatformListReq, core_pb.PlatformListResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/PlatformList"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<core_pb.PlatformListReq>;
requestDeserialize: grpc.deserialize<core_pb.PlatformListReq>;
responseSerialize: grpc.serialize<core_pb.PlatformListResp>;
responseDeserialize: grpc.deserialize<core_pb.PlatformListResp>;
}
interface IArduinoCoreService_ILibraryDownload extends grpc.MethodDefinition<lib_pb.LibraryDownloadReq, lib_pb.LibraryDownloadResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/LibraryDownload"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<lib_pb.LibraryDownloadReq>;
requestDeserialize: grpc.deserialize<lib_pb.LibraryDownloadReq>;
responseSerialize: grpc.serialize<lib_pb.LibraryDownloadResp>;
responseDeserialize: grpc.deserialize<lib_pb.LibraryDownloadResp>;
}
interface IArduinoCoreService_ILibraryInstall extends grpc.MethodDefinition<lib_pb.LibraryInstallReq, lib_pb.LibraryInstallResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/LibraryInstall"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<lib_pb.LibraryInstallReq>;
requestDeserialize: grpc.deserialize<lib_pb.LibraryInstallReq>;
responseSerialize: grpc.serialize<lib_pb.LibraryInstallResp>;
responseDeserialize: grpc.deserialize<lib_pb.LibraryInstallResp>;
}
interface IArduinoCoreService_ILibraryUninstall extends grpc.MethodDefinition<lib_pb.LibraryUninstallReq, lib_pb.LibraryUninstallResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/LibraryUninstall"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<lib_pb.LibraryUninstallReq>;
requestDeserialize: grpc.deserialize<lib_pb.LibraryUninstallReq>;
responseSerialize: grpc.serialize<lib_pb.LibraryUninstallResp>;
responseDeserialize: grpc.deserialize<lib_pb.LibraryUninstallResp>;
}
interface IArduinoCoreService_ILibraryUpgradeAll extends grpc.MethodDefinition<lib_pb.LibraryUpgradeAllReq, lib_pb.LibraryUpgradeAllResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/LibraryUpgradeAll"
requestStream: boolean; // false
responseStream: boolean; // true
requestSerialize: grpc.serialize<lib_pb.LibraryUpgradeAllReq>;
requestDeserialize: grpc.deserialize<lib_pb.LibraryUpgradeAllReq>;
responseSerialize: grpc.serialize<lib_pb.LibraryUpgradeAllResp>;
responseDeserialize: grpc.deserialize<lib_pb.LibraryUpgradeAllResp>;
}
interface IArduinoCoreService_ILibrarySearch extends grpc.MethodDefinition<lib_pb.LibrarySearchReq, lib_pb.LibrarySearchResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/LibrarySearch"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<lib_pb.LibrarySearchReq>;
requestDeserialize: grpc.deserialize<lib_pb.LibrarySearchReq>;
responseSerialize: grpc.serialize<lib_pb.LibrarySearchResp>;
responseDeserialize: grpc.deserialize<lib_pb.LibrarySearchResp>;
}
interface IArduinoCoreService_ILibraryList extends grpc.MethodDefinition<lib_pb.LibraryListReq, lib_pb.LibraryListResp> {
path: string; // "/cc.arduino.cli.commands.ArduinoCore/LibraryList"
requestStream: boolean; // false
responseStream: boolean; // false
requestSerialize: grpc.serialize<lib_pb.LibraryListReq>;
requestDeserialize: grpc.deserialize<lib_pb.LibraryListReq>;
responseSerialize: grpc.serialize<lib_pb.LibraryListResp>;
responseDeserialize: grpc.deserialize<lib_pb.LibraryListResp>;
}
export const ArduinoCoreService: IArduinoCoreService;
export interface IArduinoCoreServer {
init: grpc.handleServerStreamingCall<commands_pb.InitReq, commands_pb.InitResp>;
destroy: grpc.handleUnaryCall<commands_pb.DestroyReq, commands_pb.DestroyResp>;
rescan: grpc.handleUnaryCall<commands_pb.RescanReq, commands_pb.RescanResp>;
updateIndex: grpc.handleServerStreamingCall<commands_pb.UpdateIndexReq, commands_pb.UpdateIndexResp>;
updateLibrariesIndex: grpc.handleServerStreamingCall<commands_pb.UpdateLibrariesIndexReq, commands_pb.UpdateLibrariesIndexResp>;
version: grpc.handleUnaryCall<commands_pb.VersionReq, commands_pb.VersionResp>;
boardDetails: grpc.handleUnaryCall<board_pb.BoardDetailsReq, board_pb.BoardDetailsResp>;
boardAttach: grpc.handleServerStreamingCall<board_pb.BoardAttachReq, board_pb.BoardAttachResp>;
boardList: grpc.handleUnaryCall<board_pb.BoardListReq, board_pb.BoardListResp>;
boardListAll: grpc.handleUnaryCall<board_pb.BoardListAllReq, board_pb.BoardListAllResp>;
compile: grpc.handleServerStreamingCall<compile_pb.CompileReq, compile_pb.CompileResp>;
platformInstall: grpc.handleServerStreamingCall<core_pb.PlatformInstallReq, core_pb.PlatformInstallResp>;
platformDownload: grpc.handleServerStreamingCall<core_pb.PlatformDownloadReq, core_pb.PlatformDownloadResp>;
platformUninstall: grpc.handleServerStreamingCall<core_pb.PlatformUninstallReq, core_pb.PlatformUninstallResp>;
platformUpgrade: grpc.handleServerStreamingCall<core_pb.PlatformUpgradeReq, core_pb.PlatformUpgradeResp>;
upload: grpc.handleServerStreamingCall<upload_pb.UploadReq, upload_pb.UploadResp>;
platformSearch: grpc.handleUnaryCall<core_pb.PlatformSearchReq, core_pb.PlatformSearchResp>;
platformList: grpc.handleUnaryCall<core_pb.PlatformListReq, core_pb.PlatformListResp>;
libraryDownload: grpc.handleServerStreamingCall<lib_pb.LibraryDownloadReq, lib_pb.LibraryDownloadResp>;
libraryInstall: grpc.handleServerStreamingCall<lib_pb.LibraryInstallReq, lib_pb.LibraryInstallResp>;
libraryUninstall: grpc.handleServerStreamingCall<lib_pb.LibraryUninstallReq, lib_pb.LibraryUninstallResp>;
libraryUpgradeAll: grpc.handleServerStreamingCall<lib_pb.LibraryUpgradeAllReq, lib_pb.LibraryUpgradeAllResp>;
librarySearch: grpc.handleUnaryCall<lib_pb.LibrarySearchReq, lib_pb.LibrarySearchResp>;
libraryList: grpc.handleUnaryCall<lib_pb.LibraryListReq, lib_pb.LibraryListResp>;
}
export interface IArduinoCoreClient {
init(request: commands_pb.InitReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.InitResp>;
init(request: commands_pb.InitReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.InitResp>;
destroy(request: commands_pb.DestroyReq, callback: (error: grpc.ServiceError | null, response: commands_pb.DestroyResp) => void): grpc.ClientUnaryCall;
destroy(request: commands_pb.DestroyReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: commands_pb.DestroyResp) => void): grpc.ClientUnaryCall;
destroy(request: commands_pb.DestroyReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: commands_pb.DestroyResp) => void): grpc.ClientUnaryCall;
rescan(request: commands_pb.RescanReq, callback: (error: grpc.ServiceError | null, response: commands_pb.RescanResp) => void): grpc.ClientUnaryCall;
rescan(request: commands_pb.RescanReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: commands_pb.RescanResp) => void): grpc.ClientUnaryCall;
rescan(request: commands_pb.RescanReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: commands_pb.RescanResp) => void): grpc.ClientUnaryCall;
updateIndex(request: commands_pb.UpdateIndexReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateIndexResp>;
updateIndex(request: commands_pb.UpdateIndexReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateIndexResp>;
updateLibrariesIndex(request: commands_pb.UpdateLibrariesIndexReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateLibrariesIndexResp>;
updateLibrariesIndex(request: commands_pb.UpdateLibrariesIndexReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateLibrariesIndexResp>;
version(request: commands_pb.VersionReq, callback: (error: grpc.ServiceError | null, response: commands_pb.VersionResp) => void): grpc.ClientUnaryCall;
version(request: commands_pb.VersionReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: commands_pb.VersionResp) => void): grpc.ClientUnaryCall;
version(request: commands_pb.VersionReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: commands_pb.VersionResp) => void): grpc.ClientUnaryCall;
boardDetails(request: board_pb.BoardDetailsReq, callback: (error: grpc.ServiceError | null, response: board_pb.BoardDetailsResp) => void): grpc.ClientUnaryCall;
boardDetails(request: board_pb.BoardDetailsReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: board_pb.BoardDetailsResp) => void): grpc.ClientUnaryCall;
boardDetails(request: board_pb.BoardDetailsReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: board_pb.BoardDetailsResp) => void): grpc.ClientUnaryCall;
boardAttach(request: board_pb.BoardAttachReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<board_pb.BoardAttachResp>;
boardAttach(request: board_pb.BoardAttachReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<board_pb.BoardAttachResp>;
boardList(request: board_pb.BoardListReq, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListResp) => void): grpc.ClientUnaryCall;
boardList(request: board_pb.BoardListReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListResp) => void): grpc.ClientUnaryCall;
boardList(request: board_pb.BoardListReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListResp) => void): grpc.ClientUnaryCall;
boardListAll(request: board_pb.BoardListAllReq, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListAllResp) => void): grpc.ClientUnaryCall;
boardListAll(request: board_pb.BoardListAllReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListAllResp) => void): grpc.ClientUnaryCall;
boardListAll(request: board_pb.BoardListAllReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListAllResp) => void): grpc.ClientUnaryCall;
compile(request: compile_pb.CompileReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<compile_pb.CompileResp>;
compile(request: compile_pb.CompileReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<compile_pb.CompileResp>;
platformInstall(request: core_pb.PlatformInstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformInstallResp>;
platformInstall(request: core_pb.PlatformInstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformInstallResp>;
platformDownload(request: core_pb.PlatformDownloadReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformDownloadResp>;
platformDownload(request: core_pb.PlatformDownloadReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformDownloadResp>;
platformUninstall(request: core_pb.PlatformUninstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUninstallResp>;
platformUninstall(request: core_pb.PlatformUninstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUninstallResp>;
platformUpgrade(request: core_pb.PlatformUpgradeReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUpgradeResp>;
platformUpgrade(request: core_pb.PlatformUpgradeReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUpgradeResp>;
upload(request: upload_pb.UploadReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<upload_pb.UploadResp>;
upload(request: upload_pb.UploadReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<upload_pb.UploadResp>;
platformSearch(request: core_pb.PlatformSearchReq, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformSearchResp) => void): grpc.ClientUnaryCall;
platformSearch(request: core_pb.PlatformSearchReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformSearchResp) => void): grpc.ClientUnaryCall;
platformSearch(request: core_pb.PlatformSearchReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformSearchResp) => void): grpc.ClientUnaryCall;
platformList(request: core_pb.PlatformListReq, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformListResp) => void): grpc.ClientUnaryCall;
platformList(request: core_pb.PlatformListReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformListResp) => void): grpc.ClientUnaryCall;
platformList(request: core_pb.PlatformListReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformListResp) => void): grpc.ClientUnaryCall;
libraryDownload(request: lib_pb.LibraryDownloadReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryDownloadResp>;
libraryDownload(request: lib_pb.LibraryDownloadReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryDownloadResp>;
libraryInstall(request: lib_pb.LibraryInstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryInstallResp>;
libraryInstall(request: lib_pb.LibraryInstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryInstallResp>;
libraryUninstall(request: lib_pb.LibraryUninstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUninstallResp>;
libraryUninstall(request: lib_pb.LibraryUninstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUninstallResp>;
libraryUpgradeAll(request: lib_pb.LibraryUpgradeAllReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUpgradeAllResp>;
libraryUpgradeAll(request: lib_pb.LibraryUpgradeAllReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUpgradeAllResp>;
librarySearch(request: lib_pb.LibrarySearchReq, callback: (error: grpc.ServiceError | null, response: lib_pb.LibrarySearchResp) => void): grpc.ClientUnaryCall;
librarySearch(request: lib_pb.LibrarySearchReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: lib_pb.LibrarySearchResp) => void): grpc.ClientUnaryCall;
librarySearch(request: lib_pb.LibrarySearchReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: lib_pb.LibrarySearchResp) => void): grpc.ClientUnaryCall;
libraryList(request: lib_pb.LibraryListReq, callback: (error: grpc.ServiceError | null, response: lib_pb.LibraryListResp) => void): grpc.ClientUnaryCall;
libraryList(request: lib_pb.LibraryListReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: lib_pb.LibraryListResp) => void): grpc.ClientUnaryCall;
libraryList(request: lib_pb.LibraryListReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: lib_pb.LibraryListResp) => void): grpc.ClientUnaryCall;
}
export class ArduinoCoreClient extends grpc.Client implements IArduinoCoreClient {
constructor(address: string, credentials: grpc.ChannelCredentials, options?: object);
public init(request: commands_pb.InitReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.InitResp>;
public init(request: commands_pb.InitReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.InitResp>;
public destroy(request: commands_pb.DestroyReq, callback: (error: grpc.ServiceError | null, response: commands_pb.DestroyResp) => void): grpc.ClientUnaryCall;
public destroy(request: commands_pb.DestroyReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: commands_pb.DestroyResp) => void): grpc.ClientUnaryCall;
public destroy(request: commands_pb.DestroyReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: commands_pb.DestroyResp) => void): grpc.ClientUnaryCall;
public rescan(request: commands_pb.RescanReq, callback: (error: grpc.ServiceError | null, response: commands_pb.RescanResp) => void): grpc.ClientUnaryCall;
public rescan(request: commands_pb.RescanReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: commands_pb.RescanResp) => void): grpc.ClientUnaryCall;
public rescan(request: commands_pb.RescanReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: commands_pb.RescanResp) => void): grpc.ClientUnaryCall;
public updateIndex(request: commands_pb.UpdateIndexReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateIndexResp>;
public updateIndex(request: commands_pb.UpdateIndexReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateIndexResp>;
public updateLibrariesIndex(request: commands_pb.UpdateLibrariesIndexReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateLibrariesIndexResp>;
public updateLibrariesIndex(request: commands_pb.UpdateLibrariesIndexReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<commands_pb.UpdateLibrariesIndexResp>;
public version(request: commands_pb.VersionReq, callback: (error: grpc.ServiceError | null, response: commands_pb.VersionResp) => void): grpc.ClientUnaryCall;
public version(request: commands_pb.VersionReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: commands_pb.VersionResp) => void): grpc.ClientUnaryCall;
public version(request: commands_pb.VersionReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: commands_pb.VersionResp) => void): grpc.ClientUnaryCall;
public boardDetails(request: board_pb.BoardDetailsReq, callback: (error: grpc.ServiceError | null, response: board_pb.BoardDetailsResp) => void): grpc.ClientUnaryCall;
public boardDetails(request: board_pb.BoardDetailsReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: board_pb.BoardDetailsResp) => void): grpc.ClientUnaryCall;
public boardDetails(request: board_pb.BoardDetailsReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: board_pb.BoardDetailsResp) => void): grpc.ClientUnaryCall;
public boardAttach(request: board_pb.BoardAttachReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<board_pb.BoardAttachResp>;
public boardAttach(request: board_pb.BoardAttachReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<board_pb.BoardAttachResp>;
public boardList(request: board_pb.BoardListReq, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListResp) => void): grpc.ClientUnaryCall;
public boardList(request: board_pb.BoardListReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListResp) => void): grpc.ClientUnaryCall;
public boardList(request: board_pb.BoardListReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListResp) => void): grpc.ClientUnaryCall;
public boardListAll(request: board_pb.BoardListAllReq, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListAllResp) => void): grpc.ClientUnaryCall;
public boardListAll(request: board_pb.BoardListAllReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListAllResp) => void): grpc.ClientUnaryCall;
public boardListAll(request: board_pb.BoardListAllReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: board_pb.BoardListAllResp) => void): grpc.ClientUnaryCall;
public compile(request: compile_pb.CompileReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<compile_pb.CompileResp>;
public compile(request: compile_pb.CompileReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<compile_pb.CompileResp>;
public platformInstall(request: core_pb.PlatformInstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformInstallResp>;
public platformInstall(request: core_pb.PlatformInstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformInstallResp>;
public platformDownload(request: core_pb.PlatformDownloadReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformDownloadResp>;
public platformDownload(request: core_pb.PlatformDownloadReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformDownloadResp>;
public platformUninstall(request: core_pb.PlatformUninstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUninstallResp>;
public platformUninstall(request: core_pb.PlatformUninstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUninstallResp>;
public platformUpgrade(request: core_pb.PlatformUpgradeReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUpgradeResp>;
public platformUpgrade(request: core_pb.PlatformUpgradeReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<core_pb.PlatformUpgradeResp>;
public upload(request: upload_pb.UploadReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<upload_pb.UploadResp>;
public upload(request: upload_pb.UploadReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<upload_pb.UploadResp>;
public platformSearch(request: core_pb.PlatformSearchReq, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformSearchResp) => void): grpc.ClientUnaryCall;
public platformSearch(request: core_pb.PlatformSearchReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformSearchResp) => void): grpc.ClientUnaryCall;
public platformSearch(request: core_pb.PlatformSearchReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformSearchResp) => void): grpc.ClientUnaryCall;
public platformList(request: core_pb.PlatformListReq, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformListResp) => void): grpc.ClientUnaryCall;
public platformList(request: core_pb.PlatformListReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformListResp) => void): grpc.ClientUnaryCall;
public platformList(request: core_pb.PlatformListReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: core_pb.PlatformListResp) => void): grpc.ClientUnaryCall;
public libraryDownload(request: lib_pb.LibraryDownloadReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryDownloadResp>;
public libraryDownload(request: lib_pb.LibraryDownloadReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryDownloadResp>;
public libraryInstall(request: lib_pb.LibraryInstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryInstallResp>;
public libraryInstall(request: lib_pb.LibraryInstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryInstallResp>;
public libraryUninstall(request: lib_pb.LibraryUninstallReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUninstallResp>;
public libraryUninstall(request: lib_pb.LibraryUninstallReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUninstallResp>;
public libraryUpgradeAll(request: lib_pb.LibraryUpgradeAllReq, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUpgradeAllResp>;
public libraryUpgradeAll(request: lib_pb.LibraryUpgradeAllReq, metadata?: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientReadableStream<lib_pb.LibraryUpgradeAllResp>;
public librarySearch(request: lib_pb.LibrarySearchReq, callback: (error: grpc.ServiceError | null, response: lib_pb.LibrarySearchResp) => void): grpc.ClientUnaryCall;
public librarySearch(request: lib_pb.LibrarySearchReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: lib_pb.LibrarySearchResp) => void): grpc.ClientUnaryCall;
public librarySearch(request: lib_pb.LibrarySearchReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: lib_pb.LibrarySearchResp) => void): grpc.ClientUnaryCall;
public libraryList(request: lib_pb.LibraryListReq, callback: (error: grpc.ServiceError | null, response: lib_pb.LibraryListResp) => void): grpc.ClientUnaryCall;
public libraryList(request: lib_pb.LibraryListReq, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: lib_pb.LibraryListResp) => void): grpc.ClientUnaryCall;
public libraryList(request: lib_pb.LibraryListReq, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: lib_pb.LibraryListResp) => void): grpc.ClientUnaryCall;
} | the_stack |
import { constants, describe, expect } from '@0x/contracts-test-utils';
import { SafeMathRevertErrors } from '@0x/contracts-utils';
import { BigNumber, LibMathRevertErrors } from '@0x/utils';
import * as _ from 'lodash';
import {
addFillResults,
getPartialAmountCeil,
getPartialAmountFloor,
isRoundingErrorCeil,
isRoundingErrorFloor,
safeGetPartialAmountCeil,
safeGetPartialAmountFloor,
} from '../src/reference_functions';
describe('Reference Functions', () => {
const { ONE_ETHER, MAX_UINT256, MAX_UINT256_ROOT, ZERO_AMOUNT } = constants;
describe('LibFillResults', () => {
describe('addFillResults', () => {
const DEFAULT_FILL_RESULTS = [
{
makerAssetFilledAmount: ONE_ETHER,
takerAssetFilledAmount: ONE_ETHER.times(2),
makerFeePaid: ONE_ETHER.times(0.001),
takerFeePaid: ONE_ETHER.times(0.002),
protocolFeePaid: ONE_ETHER.times(0.003),
},
{
makerAssetFilledAmount: ONE_ETHER.times(0.01),
takerAssetFilledAmount: ONE_ETHER.times(2).times(0.01),
makerFeePaid: ONE_ETHER.times(0.001).times(0.01),
takerFeePaid: ONE_ETHER.times(0.002).times(0.01),
protocolFeePaid: ONE_ETHER.times(0.003).times(0.01),
},
];
it('reverts if computing `makerAssetFilledAmount` overflows', () => {
const [a, b] = _.cloneDeep(DEFAULT_FILL_RESULTS);
b.makerAssetFilledAmount = MAX_UINT256;
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow,
a.makerAssetFilledAmount,
b.makerAssetFilledAmount,
);
expect(() => addFillResults(a, b)).to.throw(expectedError.message);
});
it('reverts if computing `takerAssetFilledAmount` overflows', () => {
const [a, b] = _.cloneDeep(DEFAULT_FILL_RESULTS);
b.takerAssetFilledAmount = MAX_UINT256;
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow,
a.takerAssetFilledAmount,
b.takerAssetFilledAmount,
);
expect(() => addFillResults(a, b)).to.throw(expectedError.message);
});
it('reverts if computing `makerFeePaid` overflows', () => {
const [a, b] = _.cloneDeep(DEFAULT_FILL_RESULTS);
b.makerFeePaid = MAX_UINT256;
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow,
a.makerFeePaid,
b.makerFeePaid,
);
expect(() => addFillResults(a, b)).to.throw(expectedError.message);
});
it('reverts if computing `takerFeePaid` overflows', () => {
const [a, b] = _.cloneDeep(DEFAULT_FILL_RESULTS);
b.takerFeePaid = MAX_UINT256;
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow,
a.takerFeePaid,
b.takerFeePaid,
);
expect(() => addFillResults(a, b)).to.throw(expectedError.message);
});
it('reverts if computing `protocolFeePaid` overflows', () => {
const [a, b] = _.cloneDeep(DEFAULT_FILL_RESULTS);
b.protocolFeePaid = MAX_UINT256;
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow,
a.protocolFeePaid,
b.protocolFeePaid,
);
expect(() => addFillResults(a, b)).to.throw(expectedError.message);
});
});
});
describe('LibMath', () => {
describe('getPartialAmountFloor', () => {
describe('explicit tests', () => {
it('reverts if `denominator` is zero', () => {
const numerator = ONE_ETHER;
const denominator = ZERO_AMOUNT;
const target = ONE_ETHER.times(0.01);
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.DivisionByZero,
numerator.times(target),
denominator,
);
return expect(() => getPartialAmountFloor(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `numerator * target` overflows', () => {
const numerator = MAX_UINT256;
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = MAX_UINT256_ROOT.times(2);
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow,
numerator,
target,
);
return expect(() => getPartialAmountFloor(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
});
});
describe('getPartialAmountCeil', () => {
describe('explicit tests', () => {
it('reverts if `denominator` is zero', () => {
const numerator = ONE_ETHER;
const denominator = ZERO_AMOUNT;
const target = ONE_ETHER.times(0.01);
// This will actually manifest as a subtraction underflow.
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.SubtractionUnderflow,
denominator,
new BigNumber(1),
);
return expect(() => getPartialAmountCeil(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `numerator * target` overflows', () => {
const numerator = MAX_UINT256;
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = MAX_UINT256_ROOT.times(2);
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow,
numerator,
target,
);
return expect(() => getPartialAmountCeil(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
});
});
describe('safeGetPartialAmountFloor', () => {
describe('explicit tests', () => {
it('reverts for a rounding error', () => {
const numerator = new BigNumber(1e3);
const denominator = new BigNumber(1e4);
const target = new BigNumber(333);
const expectedError = new LibMathRevertErrors.RoundingError(numerator, denominator, target);
return expect(() => safeGetPartialAmountFloor(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `denominator` is zero', () => {
const numerator = ONE_ETHER;
const denominator = ZERO_AMOUNT;
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(() => safeGetPartialAmountFloor(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `numerator * target` overflows', () => {
const numerator = MAX_UINT256;
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = MAX_UINT256_ROOT.times(2);
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow,
numerator,
target,
);
return expect(() => safeGetPartialAmountFloor(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
});
});
describe('safeGetPartialAmountCeil', () => {
describe('explicit tests', () => {
it('reverts for a rounding error', () => {
const numerator = new BigNumber(1e3);
const denominator = new BigNumber(1e4);
const target = new BigNumber(333);
const expectedError = new LibMathRevertErrors.RoundingError(numerator, denominator, target);
return expect(() => safeGetPartialAmountCeil(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `denominator` is zero', () => {
const numerator = ONE_ETHER;
const denominator = ZERO_AMOUNT;
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(() => safeGetPartialAmountCeil(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `numerator * target` overflows', () => {
const numerator = MAX_UINT256;
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = MAX_UINT256_ROOT.times(2);
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow,
numerator,
target,
);
return expect(() => safeGetPartialAmountCeil(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
});
});
describe('isRoundingErrorFloor', () => {
describe('explicit tests', () => {
it('returns true when `numerator * target / denominator` produces an error >= 0.1%', async () => {
const numerator = new BigNumber(100);
const denominator = new BigNumber(102);
const target = new BigNumber(52);
// tslint:disable-next-line: boolean-naming
const actual = isRoundingErrorFloor(numerator, denominator, target);
expect(actual).to.eq(true);
});
it('returns false when `numerator * target / denominator` produces an error < 0.1%', async () => {
const numerator = new BigNumber(100);
const denominator = new BigNumber(101);
const target = new BigNumber(92);
// tslint:disable-next-line: boolean-naming
const actual = isRoundingErrorFloor(numerator, denominator, target);
expect(actual).to.eq(false);
});
it('reverts if `denominator` is zero', () => {
const numerator = ONE_ETHER;
const denominator = ZERO_AMOUNT;
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(() => isRoundingErrorFloor(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `numerator * target` overflows', () => {
const numerator = MAX_UINT256;
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = MAX_UINT256_ROOT.times(2);
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow,
numerator,
target,
);
return expect(() => isRoundingErrorFloor(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
});
});
describe('isRoundingErrorCeil', () => {
describe('explicit tests', () => {
it('returns true when `numerator * target / (denominator - 1)` produces an error >= 0.1%', async () => {
const numerator = new BigNumber(100);
const denominator = new BigNumber(101);
const target = new BigNumber(92);
// tslint:disable-next-line: boolean-naming
const actual = isRoundingErrorCeil(numerator, denominator, target);
expect(actual).to.eq(true);
});
it('returns false when `numerator * target / (denominator - 1)` produces an error < 0.1%', async () => {
const numerator = new BigNumber(100);
const denominator = new BigNumber(102);
const target = new BigNumber(52);
// tslint:disable-next-line: boolean-naming
const actual = isRoundingErrorCeil(numerator, denominator, target);
expect(actual).to.eq(false);
});
it('reverts if `denominator` is zero', () => {
const numerator = ONE_ETHER;
const denominator = ZERO_AMOUNT;
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(() => isRoundingErrorCeil(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
it('reverts if `numerator * target` overflows', () => {
const numerator = MAX_UINT256;
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = MAX_UINT256_ROOT.times(2);
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow,
numerator,
target,
);
return expect(() => isRoundingErrorCeil(numerator, denominator, target)).to.throw(
expectedError.message,
);
});
});
});
});
}); | the_stack |
* @packageDocumentation
* @module std.ranges
*/
//================================================================
import * as base from "../../algorithm/iterations";
import { IForwardContainer } from "../container/IForwardContainer";
import { Pair } from "../../utility/Pair";
import { begin, end } from "../../iterator/factory";
import { size } from "../../iterator/global";
import { equal_to, less } from "../../functional/comparators";
import { UnaryPredicator } from "../../internal/functional/UnaryPredicator";
import { BinaryPredicator } from "../../internal/functional/BinaryPredicator";
import { Comparator } from "../../internal/functional/Comparator";
import { Temporary } from "../../internal/functional/Temporary";
type BinaryPredicatorInferrer<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
= BinaryPredicator<IForwardContainer.ValueType<Range1>, IForwardContainer.ValueType<Range2>>;
/* ---------------------------------------------------------
FOR_EACH
--------------------------------------------------------- */
/**
* Apply a function to elements in range.
*
* @param range An iterable ranged container.
* @param fn The function to apply.
*
* @return The function *fn* itself.
*/
export function for_each<
Range extends Array<any> | IForwardContainer<any>,
Func extends (val: IForwardContainer.ValueType<Range>) => any>
(range: Range, fn: Func) :Func
{
return base.for_each(begin(range), end(range), fn);
}
/**
* Apply a function to elements in steps.
*
* @param range An iterable ranged container.
* @param n Steps to maximum advance.
* @param fn The function to apply.
*
* @return Iterator advanced from *first* for *n* steps.
*/
export function for_each_n<
Range extends Array<any> | IForwardContainer<any>,
Func extends (val: IForwardContainer.ValueType<Range>) => any>
(range: Range, n: number, fn: Func): IForwardContainer.IteratorType<Range>
{
return base.for_each_n(begin(range), n, fn);
}
/* ---------------------------------------------------------
AGGREGATE CONDITIONS
--------------------------------------------------------- */
/**
* Test whether all elements meet a specific condition.
*
* @param range An iterable ranged container.
* @param pred A function predicates the specific condition.
*
* @return Whether the *pred* returns always `true` for all elements.
*/
export function all_of<Range extends Array<any> | IForwardContainer<any>>
(range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): boolean
{
return base.all_of(begin(range), end(range), pred);
}
/**
* Test whether any element meets a specific condition.
*
* @param range An iterable ranged container.
* @param pred A function predicates the specific condition.
*
* @return Whether the *pred* returns at least a `true` for all elements.
*/
export function any_of<Range extends Array<any> | IForwardContainer<any>>
(range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): boolean
{
return base.any_of(begin(range), end(range), pred);
}
/**
* Test whether any element doesn't meet a specific condition.
*
* @param range An iterable ranged container.
* @param pred A function predicates the specific condition.
*
* @return Whether the *pred* doesn't return `true` for all elements.
*/
export function none_of<Range extends Array<any> | IForwardContainer<any>>
(range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): boolean
{
return base.none_of(begin(range), end(range), pred);
}
/**
* Test whether two ranges are equal.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
* @param pred A binary function predicates two arguments are equal.
*
* @return Whether two ranges are equal.
*/
export function equal<
Range1 extends Array<any> | (IForwardContainer<any>),
Range2 extends IForwardContainer.SimilarType<Range1>>
(range1: Range1, range2: Range2): boolean;
/**
* Test whether two ranges are equal.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
* @param pred A binary function predicates two arguments are equal.
*
* @return Whether two ranges are equal.
*/
export function equal<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(range1: Range1, range2: Range2, pred: BinaryPredicatorInferrer<Range1, Range2>): boolean;
export function equal<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(range1: Range1, range2: Range2, pred: BinaryPredicatorInferrer<Range1, Range2> = <any>equal_to): boolean
{
if (size(range1) !== size(range2))
return false;
else
return base.equal(begin(range1), end(range1), begin(range2), pred);
}
/**
* Compare lexicographically.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
* @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}.
*
* @return Whether the 1st range precedes the 2nd.
*/
export function lexicographical_compare<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends IForwardContainer.SimilarType<Range1>>
(range1: Range1, range2: Range2, comp: BinaryPredicatorInferrer<Range1, Range1> = less): boolean
{
return base.lexicographical_compare(begin(range1), end(range1), <Temporary>begin(range2), end(range2), comp);
}
/* ---------------------------------------------------------
FINDERS
--------------------------------------------------------- */
/**
* Find a value in range.
*
* @param range An iterable ranged container.
* @param val The value to find.
*
* @return Iterator to the first element {@link equal to equal_to} the value.
*/
export function find<Range extends Array<any> | IForwardContainer<any>>
(range: Range, val: IForwardContainer.ValueType<Range>): IForwardContainer.IteratorType<Range>
{
return base.find(begin(range), end(range), val);
}
/**
* Find a matched condition in range.
*
* @param range An iterable ranged container.
* @param pred A function predicates the specific condition.
*
* @return Iterator to the first element *pred* returns `true`.
*/
export function find_if<Range extends Array<any> | IForwardContainer<any>>
(range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): IForwardContainer.IteratorType<Range>
{
return base.find_if(begin(range), end(range), pred);
}
/**
* Find a mismatched condition in range.
*
* @param range An iterable ranged container.
* @param pred A function predicates the specific condition.
*
* @return Iterator to the first element *pred* returns `false`.
*/
export function find_if_not<Range extends Array<any> | IForwardContainer<any>>
(range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): IForwardContainer.IteratorType<Range>
{
return base.find_if_not(begin(range), end(range), pred);
}
/**
* Find the last sub range.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
*
* @return Iterator to the first element of the last sub range.
*/
export function find_end<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends IForwardContainer.SimilarType<Range1>>
(range1: Range1, range2: Range2): IForwardContainer.IteratorType<Range1>;
/**
* Find the last sub range.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
* @param pred A binary function predicates two arguments are equal.
*
* @return Iterator to the first element of the last sub range.
*/
export function find_end<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2>
): IForwardContainer.IteratorType<Range1>;
export function find_end<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2> = <any>equal_to
): IForwardContainer.IteratorType<Range1>
{
return base.find_end(begin(range1), end(range1), begin(range2), end(range2), pred);
}
/**
* Find the first sub range.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
*
* @return Iterator to the first element of the first sub range.
*/
export function find_first_of<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends IForwardContainer.SimilarType<Range1>>
(range1: Range1, range2: Range2): IForwardContainer.IteratorType<Range1>;
/**
* Find the first sub range.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
* @param pred A binary function predicates two arguments are equal.
*
* @return Iterator to the first element of the first sub range.
*/
export function find_first_of<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2>
): IForwardContainer.IteratorType<Range1>;
export function find_first_of<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2> = <any>equal_to
): IForwardContainer.IteratorType<Range1>
{
return base.find_first_of(begin(range1), end(range1), begin(range2), end(range2), pred);
}
/**
* Find the first adjacent element.
*
* @param range An iterable ranged container.
* @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}.
*
* @return Iterator to the first element of adjacent find.
*/
export function adjacent_find<Range extends Array<any> | IForwardContainer<any>>
(
range: Range,
pred: Comparator<IForwardContainer.ValueType<Range>> = equal_to
): IForwardContainer.IteratorType<Range>
{
return base.adjacent_find(begin(range), end(range), pred);
}
/**
* Search sub range.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
*
* @return Iterator to the first element of the sub range.
*/
export function search<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer.SimilarType<Range1>>
(range1: Range1, range2: Range2): IForwardContainer.IteratorType<Range1>;
/**
* Search sub range.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
* @param pred A binary function predicates two arguments are equal.
*
* @return Iterator to the first element of the sub range.
*/
export function search<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2>
): IForwardContainer.IteratorType<Range1>;
export function search<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2> = <any>equal_to
): IForwardContainer.IteratorType<Range1>
{
return base.search(begin(range1), end(range1), begin(range2), end(range2), pred);
}
/**
* Search specific and repeated elements.
*
* @param range An iterable ranged container.
* @param count Count to be repeated.
* @param val Value to search.
* @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}.
*
* @return Iterator to the first element of the repetition.
*/
export function search_n<Range extends Array<any> | IForwardContainer<any>>
(
range: Range,
count: number, val: IForwardContainer.ValueType<Range>,
pred: Comparator<IForwardContainer.ValueType<Range>> = equal_to
): IForwardContainer.IteratorType<Range>
{
return base.search_n(begin(range), end(range), count, val, pred);
}
/**
* Find the first mistmached position between two ranges.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
*
* @return A {@link Pair} of mismatched positions.
*/
export function mismatch<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer.SimilarType<Range1>>
(range1: Range1, range2: Range2): Pair<IForwardContainer.IteratorType<Range1>, IForwardContainer.IteratorType<Range2>>;
/**
* Find the first mistmached position between two ranges.
*
* @param range1 The 1st iterable ranged container.
* @param range2 The 2nd iterable ranged container.
* @param pred A binary function predicates two arguments are equal.
*
* @return A {@link Pair} of mismatched positions.
*/
export function mismatch<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2>
): Pair<IForwardContainer.IteratorType<Range1>, IForwardContainer.IteratorType<Range2>>;
export function mismatch<
Range1 extends Array<any> | IForwardContainer<any>,
Range2 extends Array<any> | IForwardContainer<any>>
(
range1: Range1,
range2: Range2,
pred: BinaryPredicatorInferrer<Range1, Range2> = <any>equal_to
): Pair<IForwardContainer.IteratorType<Range1>, IForwardContainer.IteratorType<Range2>>
{
if (size(range1) === size(range2))
return base.mismatch(begin(range1), end(range1), begin(range2), pred);
const limit: number = Math.min(size(range1), size(range2));
let x: IForwardContainer.IteratorType<Range1> = begin(range1);
let y: IForwardContainer.IteratorType<Range2> = begin(range2);
for (let i: number = 0; i < limit; ++i)
{
if (pred(x.value, y.value) === false)
break;
x = x.next();
y = y.next();
}
return new Pair(x, y);
}
/* ---------------------------------------------------------
COUNTERS
--------------------------------------------------------- */
/**
* Count matched value in range.
*
* @param range An iterable ranged container.
* @param val The value to count.
*
* @return The matched count.
*/
export function count<Range extends Array<any> | IForwardContainer<any>>
(range: Range, val: IForwardContainer.ValueType<Range>): number
{
return base.count(begin(range), end(range), val);
}
/**
* Count matched condition in range.
*
* @param range An iterable ranged container.
* @param pred A function predicates the specific condition.
*
* @return The matched count.
*/
export function count_if<Range extends Array<any> | IForwardContainer<any>>
(range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): number
{
return base.count_if(begin(range), end(range), pred);
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/replicationStorageClassificationMappingsMappers";
import * as Parameters from "../models/parameters";
import { SiteRecoveryManagementClientContext } from "../siteRecoveryManagementClientContext";
/** Class representing a ReplicationStorageClassificationMappings. */
export class ReplicationStorageClassificationMappings {
private readonly client: SiteRecoveryManagementClientContext;
/**
* Create a ReplicationStorageClassificationMappings.
* @param {SiteRecoveryManagementClientContext} client Reference to the service client.
*/
constructor(client: SiteRecoveryManagementClientContext) {
this.client = client;
}
/**
* Lists the storage classification mappings for the fabric.
* @summary Gets the list of storage classification mappings objects under a storage.
* @param fabricName Fabric name.
* @param storageClassificationName Storage classfication name.
* @param [options] The optional parameters
* @returns
* Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsResponse>
*/
listByReplicationStorageClassifications(fabricName: string, storageClassificationName: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsResponse>;
/**
* @param fabricName Fabric name.
* @param storageClassificationName Storage classfication name.
* @param callback The callback
*/
listByReplicationStorageClassifications(fabricName: string, storageClassificationName: string, callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
/**
* @param fabricName Fabric name.
* @param storageClassificationName Storage classfication name.
* @param options The optional parameters
* @param callback The callback
*/
listByReplicationStorageClassifications(fabricName: string, storageClassificationName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
listByReplicationStorageClassifications(fabricName: string, storageClassificationName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageClassificationMappingCollection>, callback?: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsResponse> {
return this.client.sendOperationRequest(
{
fabricName,
storageClassificationName,
options
},
listByReplicationStorageClassificationsOperationSpec,
callback) as Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsResponse>;
}
/**
* Gets the details of the specified storage classification mapping.
* @summary Gets the details of a storage classification mapping.
* @param fabricName Fabric name.
* @param storageClassificationName Storage classification name.
* @param storageClassificationMappingName Storage classification mapping name.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationStorageClassificationMappingsGetResponse>
*/
get(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationStorageClassificationMappingsGetResponse>;
/**
* @param fabricName Fabric name.
* @param storageClassificationName Storage classification name.
* @param storageClassificationMappingName Storage classification mapping name.
* @param callback The callback
*/
get(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, callback: msRest.ServiceCallback<Models.StorageClassificationMapping>): void;
/**
* @param fabricName Fabric name.
* @param storageClassificationName Storage classification name.
* @param storageClassificationMappingName Storage classification mapping name.
* @param options The optional parameters
* @param callback The callback
*/
get(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageClassificationMapping>): void;
get(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageClassificationMapping>, callback?: msRest.ServiceCallback<Models.StorageClassificationMapping>): Promise<Models.ReplicationStorageClassificationMappingsGetResponse> {
return this.client.sendOperationRequest(
{
fabricName,
storageClassificationName,
storageClassificationMappingName,
options
},
getOperationSpec,
callback) as Promise<Models.ReplicationStorageClassificationMappingsGetResponse>;
}
/**
* The operation to create a storage classification mapping.
* @summary Create storage classification mapping.
* @param fabricName Fabric name.
* @param storageClassificationName Storage classification name.
* @param storageClassificationMappingName Storage classification mapping name.
* @param pairingInput Pairing input.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationStorageClassificationMappingsCreateResponse>
*/
create(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: Models.StorageClassificationMappingInput, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationStorageClassificationMappingsCreateResponse> {
return this.beginCreate(fabricName,storageClassificationName,storageClassificationMappingName,pairingInput,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ReplicationStorageClassificationMappingsCreateResponse>;
}
/**
* The operation to delete a storage classification mapping.
* @summary Delete a storage classification mapping.
* @param fabricName Fabric name.
* @param storageClassificationName Storage classification name.
* @param storageClassificationMappingName Storage classification mapping name.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(fabricName,storageClassificationName,storageClassificationMappingName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Lists the storage classification mappings in the vault.
* @summary Gets the list of storage classification mappings objects under a vault.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationStorageClassificationMappingsListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.ReplicationStorageClassificationMappingsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageClassificationMappingCollection>, callback?: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): Promise<Models.ReplicationStorageClassificationMappingsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.ReplicationStorageClassificationMappingsListResponse>;
}
/**
* The operation to create a storage classification mapping.
* @summary Create storage classification mapping.
* @param fabricName Fabric name.
* @param storageClassificationName Storage classification name.
* @param storageClassificationMappingName Storage classification mapping name.
* @param pairingInput Pairing input.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, pairingInput: Models.StorageClassificationMappingInput, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
fabricName,
storageClassificationName,
storageClassificationMappingName,
pairingInput,
options
},
beginCreateOperationSpec,
options);
}
/**
* The operation to delete a storage classification mapping.
* @summary Delete a storage classification mapping.
* @param fabricName Fabric name.
* @param storageClassificationName Storage classification name.
* @param storageClassificationMappingName Storage classification mapping name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(fabricName: string, storageClassificationName: string, storageClassificationMappingName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
fabricName,
storageClassificationName,
storageClassificationMappingName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Lists the storage classification mappings for the fabric.
* @summary Gets the list of storage classification mappings objects under a storage.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns
* Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsNextResponse>
*/
listByReplicationStorageClassificationsNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByReplicationStorageClassificationsNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByReplicationStorageClassificationsNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
listByReplicationStorageClassificationsNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageClassificationMappingCollection>, callback?: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByReplicationStorageClassificationsNextOperationSpec,
callback) as Promise<Models.ReplicationStorageClassificationMappingsListByReplicationStorageClassificationsNextResponse>;
}
/**
* Lists the storage classification mappings in the vault.
* @summary Gets the list of storage classification mappings objects under a vault.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationStorageClassificationMappingsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationStorageClassificationMappingsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageClassificationMappingCollection>, callback?: msRest.ServiceCallback<Models.StorageClassificationMappingCollection>): Promise<Models.ReplicationStorageClassificationMappingsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.ReplicationStorageClassificationMappingsListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByReplicationStorageClassificationsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.storageClassificationName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageClassificationMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.storageClassificationName,
Parameters.storageClassificationMappingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageClassificationMapping
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationStorageClassificationMappings",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageClassificationMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.storageClassificationName,
Parameters.storageClassificationMappingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "pairingInput",
mapper: {
...Mappers.StorageClassificationMappingInput,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.StorageClassificationMapping
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.storageClassificationName,
Parameters.storageClassificationMappingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByReplicationStorageClassificationsNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageClassificationMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageClassificationMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
ServiceResource,
ServicesListBySubscriptionOptionalParams,
ServicesListOptionalParams,
ServicesGetOptionalParams,
ServicesGetResponse,
ServicesCreateOrUpdateOptionalParams,
ServicesCreateOrUpdateResponse,
ServicesDeleteOptionalParams,
ServicesUpdateOptionalParams,
ServicesUpdateResponse,
ServicesListTestKeysOptionalParams,
ServicesListTestKeysResponse,
RegenerateTestKeyRequestPayload,
ServicesRegenerateTestKeyOptionalParams,
ServicesRegenerateTestKeyResponse,
ServicesDisableTestEndpointOptionalParams,
ServicesEnableTestEndpointOptionalParams,
ServicesEnableTestEndpointResponse,
ServicesStopOptionalParams,
ServicesStartOptionalParams,
NameAvailabilityParameters,
ServicesCheckNameAvailabilityOptionalParams,
ServicesCheckNameAvailabilityResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a Services. */
export interface Services {
/**
* Handles requests to list all resources in a subscription.
* @param options The options parameters.
*/
listBySubscription(
options?: ServicesListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<ServiceResource>;
/**
* Handles requests to list all resources in a resource group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param options The options parameters.
*/
list(
resourceGroupName: string,
options?: ServicesListOptionalParams
): PagedAsyncIterableIterator<ServiceResource>;
/**
* Get a Service and its properties.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
options?: ServicesGetOptionalParams
): Promise<ServicesGetResponse>;
/**
* Create a new Service or update an exiting Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param resource Parameters for the create or update operation
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
serviceName: string,
resource: ServiceResource,
options?: ServicesCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<ServicesCreateOrUpdateResponse>,
ServicesCreateOrUpdateResponse
>
>;
/**
* Create a new Service or update an exiting Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param resource Parameters for the create or update operation
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
serviceName: string,
resource: ServiceResource,
options?: ServicesCreateOrUpdateOptionalParams
): Promise<ServicesCreateOrUpdateResponse>;
/**
* Operation to delete a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
serviceName: string,
options?: ServicesDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Operation to delete a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
serviceName: string,
options?: ServicesDeleteOptionalParams
): Promise<void>;
/**
* Operation to update an exiting Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param resource Parameters for the update operation
* @param options The options parameters.
*/
beginUpdate(
resourceGroupName: string,
serviceName: string,
resource: ServiceResource,
options?: ServicesUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<ServicesUpdateResponse>,
ServicesUpdateResponse
>
>;
/**
* Operation to update an exiting Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param resource Parameters for the update operation
* @param options The options parameters.
*/
beginUpdateAndWait(
resourceGroupName: string,
serviceName: string,
resource: ServiceResource,
options?: ServicesUpdateOptionalParams
): Promise<ServicesUpdateResponse>;
/**
* List test keys for a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
listTestKeys(
resourceGroupName: string,
serviceName: string,
options?: ServicesListTestKeysOptionalParams
): Promise<ServicesListTestKeysResponse>;
/**
* Regenerate a test key for a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param regenerateTestKeyRequest Parameters for the operation
* @param options The options parameters.
*/
regenerateTestKey(
resourceGroupName: string,
serviceName: string,
regenerateTestKeyRequest: RegenerateTestKeyRequestPayload,
options?: ServicesRegenerateTestKeyOptionalParams
): Promise<ServicesRegenerateTestKeyResponse>;
/**
* Disable test endpoint functionality for a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
disableTestEndpoint(
resourceGroupName: string,
serviceName: string,
options?: ServicesDisableTestEndpointOptionalParams
): Promise<void>;
/**
* Enable test endpoint functionality for a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
enableTestEndpoint(
resourceGroupName: string,
serviceName: string,
options?: ServicesEnableTestEndpointOptionalParams
): Promise<ServicesEnableTestEndpointResponse>;
/**
* Stop a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
beginStop(
resourceGroupName: string,
serviceName: string,
options?: ServicesStopOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Stop a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
beginStopAndWait(
resourceGroupName: string,
serviceName: string,
options?: ServicesStopOptionalParams
): Promise<void>;
/**
* Start a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
beginStart(
resourceGroupName: string,
serviceName: string,
options?: ServicesStartOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Start a Service.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
beginStartAndWait(
resourceGroupName: string,
serviceName: string,
options?: ServicesStartOptionalParams
): Promise<void>;
/**
* Checks that the resource name is valid and is not already in use.
* @param location the region
* @param availabilityParameters Parameters supplied to the operation.
* @param options The options parameters.
*/
checkNameAvailability(
location: string,
availabilityParameters: NameAvailabilityParameters,
options?: ServicesCheckNameAvailabilityOptionalParams
): Promise<ServicesCheckNameAvailabilityResponse>;
} | the_stack |
import { Map, Object as obj, VERSION } from 'ol';
import { ProjectionLike, transform } from 'ol/proj';
import Event from 'ol/events/Event';
import { Coordinate } from 'ol/coordinate';
import echarts from 'echarts';
import {
isObject, merge,
arrayAdd, bind,
uuid, bindAll,
removeNode,
mockEvent,
semver,
} from './utils';
import formatGeoJSON from './utils/formatGeoJSON';
import * as charts from './charts/index';
type charts = any;
const _options = {
forcedRerender: false, // Force re-rendering
forcedPrecomposeRerender: false, // force pre re-render
hideOnZooming: false, // when zooming hide chart
hideOnMoving: false, // when moving hide chart
hideOnRotating: false, // // when Rotating hide chart
convertTypes: ['pie', 'line', 'bar'],
insertFirst: false,
stopEvent: false,
polyfillEvents: semver(VERSION, '6.1.1') <= 0, // fix echarts mouse events
};
type Nullable<T> = T | null;
type NoDef<T> = T | undefined;
interface OptionsTypes {
source?: ProjectionLike;
destination?: ProjectionLike;
forcedRerender?: boolean;
forcedPrecomposeRerender?: boolean;
hideOnZooming?: boolean;
hideOnMoving?: boolean;
hideOnRotating?: boolean;
convertTypes?: string[] | number[];
insertFirst?: boolean;
stopEvent?: boolean;
polyfillEvents?: boolean;
[key: string]: any;
}
class EChartsLayer extends obj {
public static formatGeoJSON = formatGeoJSON;
public static bind = bind;
public static merge = merge;
public static uuid = uuid;
public static bindAll = bindAll;
public static arrayAdd = arrayAdd;
public static removeNode = removeNode;
public static isObject = isObject;
private _chartOptions: NoDef<Nullable<object>>;
private _isRegistered: boolean;
private _incremental: any[];
private _coordinateSystem: Nullable<any>;
private coordinateSystemId: string;
private readonly _options: OptionsTypes;
private _initEvent: boolean;
private prevVisibleState: string | null;
public $chart: Nullable<any>;
public $container: NoDef<HTMLElement>;
public _map: any;
constructor(chartOptions?: NoDef<Nullable<object>>, options?: NoDef<Nullable<OptionsTypes>>, map?: any) {
const opts = Object.assign(_options, options);
super(opts);
/**
* layer options
*/
this._options = opts;
/**
* chart options
*/
this._chartOptions = chartOptions;
this.set('chartOptions', chartOptions); // cache chart Options
/**
* chart instance
* @type {null}
*/
this.$chart = null;
/**
* chart element
* @type {undefined}
*/
this.$container = undefined;
/**
* Whether the relevant configuration has been registered
* @type {boolean}
* @private
*/
this._isRegistered = false;
/**
* check if init
*/
this._initEvent = false;
/**
* 增量数据存放
* @type {Array}
* @private
*/
this._incremental = [];
/**
* coordinate system
* @type {null}
* @private
*/
this._coordinateSystem = null;
/**
* coordinateSystemId
*/
this.coordinateSystemId = '';
this.prevVisibleState = '';
bindAll([
'redraw', 'onResize', 'onZoomEnd', 'onCenterChange',
'onDragRotateEnd', 'onMoveStart', 'onMoveEnd',
'mouseDown', 'mouseUp', 'onClick', 'mouseMove',
], this);
if (map) this.setMap(map);
}
/**
* append layer to map
* @param map
*/
public appendTo(map: any) {
this.setMap(map);
}
/**
* get ol map
* @returns {ol.Map}
*/
public getMap() {
return this._map;
}
/**
* set map
* @param map
*/
public setMap(map: any) {
if (map && map instanceof Map) {
this._map = map;
this._map.once('postrender', () => {
this.handleMapChanged();
});
this._map.renderSync();
} else {
throw new Error('not ol map object');
}
}
/**
* get echarts options
*/
public getChartOptions(): object | undefined | null {
return this.get('chartOptions');
}
/**
* set echarts options and redraw
* @param options
* @returns {EChartsLayer}
*/
public setChartOptions(options: object = {}) {
this._chartOptions = options;
this.set('chartOptions', options);
this.clearAndRedraw();
return this;
}
/**
* append data
* @param data
* @param save
* @returns {EChartsLayer}
*/
public appendData(data: any, save: boolean | undefined | null = true) {
if (data) {
if (save) {
this._incremental = arrayAdd(this._incremental, {
index: this._incremental.length,
data: data.data,
seriesIndex: data.seriesIndex,
});
}
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/copyWithin
this.$chart.appendData({
data: data.data.copyWithin(),
seriesIndex: data.seriesIndex,
});
}
return this;
}
/**
* clear layer
*/
public clear(keep?: boolean) {
if (!keep) {
this._incremental = [];
}
if (this.$chart) {
this.$chart.clear();
}
}
/**
* remove layer
*/
public remove() {
this.clear();
if (this.$chart) {
this.$chart.dispose();
}
if (this._initEvent && this.$container) {
this.$container && removeNode(this.$container);
this.unBindEvent();
}
delete this.$chart;
delete this._map;
}
/**
* show layer
*/
public show() {
this.setVisible(true);
}
private innerShow() {
if (this.$container) {
this.$container.style.display = this.prevVisibleState;
this.prevVisibleState = '';
}
}
/**
* hide layer
*/
public hide() {
this.setVisible(false);
}
private innerHide() {
if (this.$container) {
this.prevVisibleState = this.$container.style.display;
this.$container.style.display = 'none';
}
}
/**
* check layer is visible
*/
public isVisible() {
return this.$container && this.$container.style.display !== 'none';
}
/**
* show loading bar
*/
public showLoading() {
if (this.$chart) {
this.$chart.showLoading();
}
}
/**
* hide loading bar
*/
public hideLoading() {
if (this.$chart) {
this.$chart.hideLoading();
}
}
/**
* set zindex
* @param zIndex
*/
public setZIndex(zIndex: string | number | null) {
if (this.$container) {
if (typeof zIndex === 'number') {
zIndex = String(zIndex);
}
this.$container.style.zIndex = zIndex;
}
}
/**
* get zindex
*/
public getZIndex() {
return this.$container && this.$container.style.zIndex;
}
/**
* set visible
* from: https://github.com/sakitam-fdd/ol3Echarts/blob/3929ad72f562661ba3511d4d9e360dee5ac793c2/
* packages/ol-echarts/src/index.js
* author: https://github.com/ChenGuanglin0924
* @param visible
*/
public setVisible(visible: boolean) {
if (visible) {
if (this.$container) {
this.$container.style.display = '';
}
this._chartOptions = this.getChartOptions();
this.clearAndRedraw();
} else {
if (this.$container) {
this.$container.style.display = 'none';
}
this.clear(true);
this._chartOptions = {};
this.clearAndRedraw();
}
}
/**
* render
*/
public render() {
if (!this.$chart && this.$container) {
// @ts-ignore
this.$chart = echarts.init(this.$container);
if (this._chartOptions) {
this.registerMap();
this.$chart.setOption(this.convertData(this._chartOptions), false);
}
this.dispatchEvent({
type: 'load',
source: this,
value: this.$chart,
});
} else if (this.isVisible()) {
this.redraw();
}
}
/**
* redraw echarts layer
*/
public redraw() {
this.clearAndRedraw();
}
/**
* update container size
* @param size
*/
public updateViewSize(size: number[]): void {
if (!this.$container) return;
this.$container.style.width = `${size[0]}px`;
this.$container.style.height = `${size[1]}px`;
this.$container.setAttribute('width', String(size[0]));
this.$container.setAttribute('height', String(size[1]));
}
/**
* handle map view resize
*/
private onResize(event?: any) {
const map = this.getMap();
if (map) {
const size: number[] = map.getSize();
this.updateViewSize(size);
this.clearAndRedraw();
if (event) { // ignore events
this.dispatchEvent({
type: 'change:size',
source: this,
value: size,
});
}
}
}
/**
* handle zoom end events
*/
private onZoomEnd() {
this._options.hideOnZooming && this.innerShow();
const map = this.getMap();
if (map && map.getView()) {
this.clearAndRedraw();
this.dispatchEvent({
type: 'zoomend',
source: this,
value: map.getView().getZoom(),
});
}
}
/**
* handle rotate end events
*/
private onDragRotateEnd() {
this._options.hideOnRotating && this.innerShow();
const map = this.getMap();
if (map && map.getView()) {
this.clearAndRedraw();
this.dispatchEvent({
type: 'change:rotation',
source: this,
value: map.getView().getRotation(),
});
}
}
/**
* handle move start events
*/
private onMoveStart() {
this._options.hideOnMoving && this.innerHide();
const map = this.getMap();
if (map && map.getView()) {
this.dispatchEvent({
type: 'movestart',
source: this,
value: map.getView().getCenter(),
});
}
}
/**
* handle move end events
*/
private onMoveEnd() {
this._options.hideOnMoving && this.innerShow();
const map = this.getMap();
if (map && map.getView()) {
this.clearAndRedraw();
this.dispatchEvent({
type: 'moveend',
source: this,
value: map.getView().getCenter(),
});
}
}
/**
* on mouse click
* @param event
*/
private onClick(event: any) {
if (this.$chart) {
this.$chart.getZr().painter.getViewportRoot().dispatchEvent(mockEvent('click', event));
}
}
/**
* on mouse down
* @param event
*/
private mouseDown(event: any) {
if (this.$chart) {
this.$chart.getZr().painter.getViewportRoot().dispatchEvent(mockEvent('mousedown', event));
}
}
/**
* mouse up
* @param event
*/
private mouseUp(event: any) {
if (this.$chart) {
this.$chart.getZr().painter.getViewportRoot().dispatchEvent(mockEvent('mouseup', event));
}
}
/**
* mousemove 事件需要分两种情况处理:
* 1. ol-overlaycontainer-stopevent 有高度, 则 propagation path 是 ol-viewport -> ol-overlaycontainer-stopevent.
* 此时 ol-overlaycontainer 无法获得事件, 只能 mock 处理
* 2. ol-overlaycontainer-stopevent 没有高度, 则 propagation path 是 ol-viewport -> ol-overlaycontainer. 无需 mock
* @param event
*/
private mouseMove(event: any) {
if (this.$chart) {
let target = event.originalEvent.target;
while (target) {
if (target.className === 'ol-overlaycontainer-stopevent') {
this.$chart.getZr().painter.getViewportRoot().dispatchEvent(mockEvent('mousemove', event));
return;
}
target = target.parentElement;
}
}
}
/**
* handle center change
*/
private onCenterChange() {
const map = this.getMap();
if (map && map.getView()) {
this.clearAndRedraw();
this.dispatchEvent({
type: 'change:center',
source: this,
value: map.getView().getCenter(),
});
}
}
/**
* handle map change
*/
private handleMapChanged() {
const map = this.getMap();
if (this._initEvent && this.$container) {
this.$container && removeNode(this.$container);
this.unBindEvent();
}
if (!this.$container) {
this.createLayerContainer();
this.onResize(false);
}
if (map) {
const container = this._options.stopEvent ? map.getOverlayContainerStopEvent() : map.getOverlayContainer();
if (this._options.insertFirst) {
container.insertBefore(this.$container, container.childNodes[0] || null);
} else {
container.appendChild(this.$container);
}
this.render();
this.bindEvent(map);
}
}
/**
* create container
*/
private createLayerContainer() {
this.$container = document.createElement('div');
this.$container.style.position = 'absolute';
this.$container.style.top = '0px';
this.$container.style.left = '0px';
this.$container.style.right = '0px';
this.$container.style.bottom = '0px';
this.$container.style.pointerEvents = 'auto';
}
/**
* register events
* @private
*/
private bindEvent(map: any) {
// https://github.com/openlayers/openlayers/issues/7284
const view = map.getView();
if (this._options.forcedPrecomposeRerender) {
map.on('precompose', this.redraw);
}
map.on('change:size', this.onResize);
view.on('change:resolution', this.onZoomEnd);
view.on('change:center', this.onCenterChange);
view.on('change:rotation', this.onDragRotateEnd);
map.on('movestart', this.onMoveStart);
map.on('moveend', this.onMoveEnd);
if (this._options.polyfillEvents) {
map.on('pointerdown', this.mouseDown);
map.on('pointerup', this.mouseUp);
map.on('pointermove', this.mouseMove);
map.on('click', this.onClick);
}
this._initEvent = true;
}
/**
* un register events
* @private
*/
private unBindEvent() {
const map = this.getMap();
if (!map) return;
const view = map.getView();
if (!view) return;
map.un('precompose', this.redraw);
map.un('change:size', this.onResize);
view.un('change:resolution', this.onZoomEnd);
view.un('change:center', this.onCenterChange);
view.un('change:rotation', this.onDragRotateEnd);
map.un('movestart', this.onMoveStart);
map.un('moveend', this.onMoveEnd);
if (this._options.polyfillEvents) {
map.un('pointerdown', this.mouseDown);
map.un('pointerup', this.mouseUp);
map.un('pointermove', this.mouseMove);
map.un('click', this.onClick);
}
this._initEvent = false;
}
/**
* clear chart and redraw
* @private
*/
private clearAndRedraw() {
if (!this.$chart || !this.isVisible()) return;
if (this._options.forcedRerender) {
this.$chart.clear();
}
this.$chart.resize();
if (this._chartOptions) {
this.registerMap();
this.$chart.setOption(this.convertData(this._chartOptions), false);
if (this._incremental && this._incremental.length > 0) {
for (let i = 0; i < this._incremental.length; i++) {
this.appendData(this._incremental[i], false);
}
}
}
this.dispatchEvent({
type: 'redraw',
source: this,
});
}
/**
* register map coordinate system
* @private
*/
private registerMap() {
if (!this._isRegistered) {
this.coordinateSystemId = `openlayers_${uuid()}`;
// @ts-ignore
echarts.registerCoordinateSystem(this.coordinateSystemId, this.getCoordinateSystem(this._options));
this._isRegistered = true;
}
if (this._chartOptions) {
// @ts-ignore
const series = this._chartOptions.series;
if (series && isObject(series)) {
const convertTypes = this._options.convertTypes;
if (convertTypes) {
for (let i = series.length - 1; i >= 0; i--) {
if (!(convertTypes.indexOf(series[i].type) > -1)) {
series[i].coordinateSystem = this.coordinateSystemId;
}
series[i].animation = false;
}
}
}
}
}
/**
* 重新处理数据
* @param options
* @returns {*}
*/
private convertData(options: object) {
// @ts-ignore
const series = options.series;
if (series && series.length > 0) {
if (!this._coordinateSystem) {
const Rc = this.getCoordinateSystem(this._options);
// @ts-ignore
this._coordinateSystem = new Rc(this.getMap());
}
if (series && isObject(series)) {
const convertTypes = this._options.convertTypes;
if (convertTypes) {
for (let i = series.length - 1; i >= 0; i--) {
if (convertTypes.indexOf(series[i].type) > -1) {
if (series[i] && series[i].hasOwnProperty('coordinates')) {
// @ts-ignore
series[i] = charts[series[i].type](options, series[i], this._coordinateSystem);
}
}
}
}
}
}
return options;
}
/**
* register coordinateSystem
* @param options
*/
private getCoordinateSystem(options?: OptionsTypes) {
const map = this.getMap();
const coordinateSystemId = this.coordinateSystemId;
const RegisterCoordinateSystem = function (map: any) {
// @ts-ignore
this.map = map;
// @ts-ignore
this._mapOffset = [0, 0];
// @ts-ignore
this.dimensions = ['lng', 'lat'];
// @ts-ignore
this.projCode = RegisterCoordinateSystem.getProjectionCode(this.map);
};
RegisterCoordinateSystem.dimensions = RegisterCoordinateSystem.prototype.dimensions || ['lng', 'lat'];
/**
* get zoom
* @returns {number}
*/
RegisterCoordinateSystem.prototype.getZoom = function (): number {
return this.map.getView().getZoom();
};
/**
* set zoom
* @param zoom
*/
RegisterCoordinateSystem.prototype.setZoom = function (zoom: number): void {
return this.map.getView().setZoom(zoom);
};
RegisterCoordinateSystem.prototype.getViewRectAfterRoam = function () {
return this.getViewRect().clone();
};
/**
* 设置地图窗口的偏移
* @param mapOffset
*/
RegisterCoordinateSystem.prototype.setMapOffset = function (mapOffset: number[]): void {
this._mapOffset = mapOffset;
};
/**
* 跟据坐标转换成屏幕像素
* @param data
* @returns {}
*/
RegisterCoordinateSystem.prototype.dataToPoint = function (data: []): number[] {
let coords: Coordinate;
if (data && Array.isArray(data) && data.length > 0) {
coords = data.map((item: string | number): number => {
let res = 0;
if (typeof item === 'string') {
res = Number(item);
} else {
res = item;
}
return res;
});
const source: ProjectionLike = (options && options.source) || 'EPSG:4326';
const destination: ProjectionLike = (options && options.destination) || this.projCode;
const pixel = this.map.getPixelFromCoordinate(transform(coords, source, destination));
const mapOffset = this._mapOffset;
return [pixel[0] - mapOffset[0], pixel[1] - mapOffset[1]];
}
return [0, 0];
};
/**
* 跟据屏幕像素转换成坐标
* @param pixel
* @returns {}
*/
RegisterCoordinateSystem.prototype.pointToData = function (pixel: number[]): number[] {
const mapOffset: number[] = this._mapOffset;
return this.map.getCoordinateFromPixel([pixel[0] + mapOffset[0], pixel[1] + mapOffset[1]]);
};
/**
* 获取视图矩形范围
* @returns {*}
*/
RegisterCoordinateSystem.prototype.getViewRect = function () {
const size = this.map.getSize();
// @ts-ignore
return new echarts.graphic.BoundingRect(0, 0, size[0], size[1]);
};
/**
* create matrix
*/
RegisterCoordinateSystem.prototype.getRoamTransform = function () {
// @ts-ignore
return echarts.matrix.create();
};
/**
* 处理自定义图表类型
* @returns {{coordSys: {type: string, x, y, width, height}, api: {coord, size}}}
*/
RegisterCoordinateSystem.prototype.prepareCustoms = function () {
const rect = this.getViewRect();
return {
coordSys: {
type: coordinateSystemId,
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
},
api: {
coord: bind(this.dataToPoint, this),
size: bind(RegisterCoordinateSystem.dataToCoordsSize, this),
},
};
};
RegisterCoordinateSystem.create = function (echartsModel: any) {
echartsModel.eachSeries((seriesModel: any) => {
if (seriesModel.get('coordinateSystem') === coordinateSystemId) {
// @ts-ignore
seriesModel.coordinateSystem = new RegisterCoordinateSystem(map);
}
});
};
RegisterCoordinateSystem.getProjectionCode = function (map: any): string {
let code = '';
if (map) {
code = map.getView()
&& map
.getView()
.getProjection()
.getCode();
} else {
code = 'EPSG:3857';
}
return code;
};
RegisterCoordinateSystem.dataToCoordsSize = function (dataSize: number[], dataItem: number[] = [0, 0]) {
return [0, 1].map((dimIdx: number) => {
const val = dataItem[dimIdx];
const p1: number[] = [];
const p2: number[] = [];
const halfSize = dataSize[dimIdx] / 2;
p1[dimIdx] = val - halfSize;
p2[dimIdx] = val + halfSize;
p1[1 - dimIdx] = dataItem[1 - dimIdx];
p2[1 - dimIdx] = dataItem[1 - dimIdx];
// @ts-ignore
const offset: number = this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx];
return Math.abs(offset);
},
this);
};
return RegisterCoordinateSystem;
}
/**
* dispatch event
* @param event
*/
public dispatchEvent(event: object | Event | string) {
return super.dispatchEvent(event);
}
public set(key: string, value: any, optSilent?: boolean) {
return super.set(key, value, optSilent);
}
public get(key: string) {
return super.get(key);
}
public unset(key: string, optSilent?: boolean) {
return super.unset(key, optSilent);
}
// @ts-ignore
public on(type: (string | string[]), listener: (p0: any) => void) {
return super.on(type, listener);
}
public un(type: (string | string[]), listener: (p0: any) => void) {
return super.un(type, listener);
}
}
export default EChartsLayer; | the_stack |
import * as concaveman from 'concaveman';
import HTMLToPDF from 'convert-html-to-pdf';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { inspect } from 'util';
import { Extractor } from './input/Extractor';
import { PDFJsExtractor } from './input/pdf.js/PDFJsExtractor';
import { PdfminerExtractor } from './input/pdfminer/PdfminerExtractor';
import { Config } from './types/Config';
import {
BoundingBox,
Document,
Element,
Font,
Line,
Page,
Text,
} from './types/DocumentRepresentation';
import logger from './utils/Logger';
import Cache from './utils/CacheLayer';
import { AbbyyTools } from './input/abbyy/AbbyyTools';
import { AmazonTextractExtractor } from './input/amazon-textract/AmazonTextractExtractor';
import { GoogleVisionExtractor } from './input/google-vision/GoogleVisionExtractor';
import { MicrosoftCognitiveExtractor } from './input/ms-cognitive-services/MicrosoftCognitiveServices';
import { OcrExtractor } from './input/OcrExtractor';
import { TesseractExtractor } from './input/tesseract/TesseractExtractor';
import { SvgLine } from './types/DocumentRepresentation/SvgLine';
let mutoolExtractionFolder: string = '';
export function replaceObject<T extends Element, U extends T>(
doc: Document,
oldObj: T,
newObj: U,
): Document {
doc.pages.forEach((page: Page) => {
page.elements = page.elements.map((element: Element) => {
_replaceObject(element);
if (element === oldObj) {
element = newObj;
}
return element;
});
});
return doc;
function _replaceObject(element: Element) {
if (element.parent) {
if (element.parent === oldObj) {
element.parent = newObj;
}
}
element.children = element.children.map((child: Element) => {
if (child === oldObj) {
child = newObj;
}
return child;
});
if (Array.isArray(element.content)) {
element.content = element.content.map((elem: Element) => {
if (elem === oldObj) {
elem = newObj;
}
_replaceObject(elem);
return elem;
});
}
}
}
export function getMutoolExtractionFolder(): string {
if (!mutoolExtractionFolder) {
mutoolExtractionFolder = getTemporaryDirectory();
}
return mutoolExtractionFolder;
}
export function getTemporaryDirectory(): string {
const randFoldername = `${os.tmpdir()}/${crypto.randomBytes(15).toString('hex')}`;
fs.mkdirSync(randFoldername);
return path.resolve(`${randFoldername}`);
}
export function getTemporaryFile(extension: string): string {
const randFilename = `${os.tmpdir()}/${crypto.randomBytes(15).toString('hex') + extension}`;
return path.resolve(`${randFilename}`);
}
/**
* Sort function to sort elements by order
*/
export function sortElementsByOrder(elem1: Element, elem2: Element): number {
const orderA: number = getOrder(elem1);
const orderB: number = getOrder(elem2);
return orderA - orderB;
function getOrder(element: Element): number {
if (typeof element.properties.order !== 'undefined') {
return element.properties.order;
} else if (Array.isArray(element.content)) {
return element.content
.map((cont: Element) => getOrder(cont))
.reduce((a, b) => Math.min(a, b), Infinity);
} else {
return Infinity;
}
}
}
/**
* Make subCollections of a predetermined size based on a collection.
* @param collection The collection to be used as the basis for the division.
* @param subCollectionSize The size of the smaller subCollections to be made
*/
export function getSubCollections<T>(collection: T[], subCollectionSize: number): T[][] {
if (subCollectionSize >= collection.length) {
return [collection];
}
const max: number = collection.length;
const result: T[][] = [];
let j: number = 0;
for (j = subCollectionSize; j !== max + 1; ++j) {
const i: number = j - subCollectionSize;
result.push(collection.slice(i, j));
}
return result;
}
/**
* Merge paragraphs blocks together.
* Also handles properly bullet points.
* @param content Array of text block to be merged into a single one
*/
export function mergeElements<T extends Text, U extends Text>(parent: U, ...content: T[]): U {
if (content.length === 0) {
return parent;
}
content = content.filter(l => l !== null && typeof l !== 'undefined');
content.sort(sortElementsByOrder);
parent.content = content;
parent.box = BoundingBox.merge(content.map(c => c.box));
// FIXME Add font support
// paragraph.font = (lines.sort((a, b) => b.data.length - a.data.length)[0] || paragraph).font;
// TODO Find a clever way to handle that (or not)
// paragraph.metadata = utils.concatTags(...lines.map(l => l.metadata));
return parent;
}
/**
* The "median" is the "middle" value in the list of numbers.
*
* @param {Array} numbers An array of numbers.
* @return {Number} The calculated median value from the specified numbers.
*/
export function median(numbers: number[]): number {
numbers.sort((a, b) => a - b);
if (numbers.length % 2 === 0) {
return (numbers[numbers.length / 2 - 1] + numbers[numbers.length / 2]) / 2;
} else {
return numbers[(numbers.length - 1) / 2];
}
}
/**
* Check if text blocks are vertically aligned in the center.
*/
export function isAlignedCenter(texts: Text[], alignUncertainty: number = 0): boolean {
for (let i = 0; i < texts.length - 1; i++) {
const t1 = texts[i];
const t2 = texts[i + 1];
if (Math.abs(t1.left + t1.width / 2 - (t2.left + t2.width / 2)) > alignUncertainty) {
return false;
}
}
return true;
}
/**
* Check if text blocks are vertically aligned on the left or right side.
* Also handles bullet point with an uncertainty.
*/
export function isAligned(
texts: Text[],
alignUncertainty: number = 0,
bulletUncertainty: number = 40,
): boolean {
return (
isAlignedLeft(texts, alignUncertainty, bulletUncertainty) ||
isAlignedRight(texts, alignUncertainty)
);
}
export function isAlignedLeft(
texts: Text[],
alignUncertainty: number = 0,
bulletUncertainty: number = 40,
): boolean {
for (let i = 0; i < texts.length - 1; i++) {
const t1 = texts[i];
const t2 = texts[i + 1];
// if (!t1.metadata.bulletList && !t2.metadata.bulletList) {
// bulletUncertainty = 0;
// }
if (Math.abs(t1.left - t2.left) > alignUncertainty + bulletUncertainty) {
return false;
}
}
return true;
}
export function findElementIDInPageBySameBoundingBox(element: Element, page: Page): number {
let elementID: number = -1;
const elements: Element[] = page.getAllElements();
elements.forEach(e => {
if (BoundingBox.isEqual(e.box, element.box)) {
elementID = e.id;
}
});
return elementID;
}
export function isAlignedRight(texts: Text[], alignUncertainty: number = 0): boolean {
for (let i = 0; i < texts.length - 1; i++) {
const t1 = texts[i];
const t2 = texts[i + 1];
if (Math.abs(t1.left + t1.width - (t2.left + t2.width)) > alignUncertainty) {
return false;
}
}
return true;
}
/**
* Check if an element is contained inside a bounding box
* @param element Element that'll be checked
* @param box Containing box
* @param strict Will check if the element can stay strictly in the box without overstepping (Default: `true`)
*/
export function isInBox(element: Element, box: BoundingBox, strict: boolean = true): boolean {
if (strict) {
return (
element.box.top >= box.top &&
element.box.top + element.box.height <= box.top + box.height &&
element.box.left >= box.left &&
element.box.left + element.box.width <= box.left + box.width
);
} else {
return BoundingBox.getOverlap(element.box, box).jaccardIndex === 0;
}
}
/**
* Check if blocks are in the same location, but maybe on different pages
* @param uncertainty error margin in px
* @param texts text block that'll be compared
*/
export function hasSameLocation(uncertainty: number, ...texts: Text[]): boolean {
const top = Math.min(...texts.map(t => t.top));
const left = Math.min(...texts.map(t => t.left));
const bottom = Math.max(...texts.map(t => t.top + t.height));
const right = Math.max(...texts.map(t => t.left + t.width));
for (const t of texts) {
if (
t.top > top + uncertainty ||
t.left > left + uncertainty ||
top + t.height < bottom - uncertainty * 2 ||
left + t.width < right - uncertainty * 2
) {
return false;
}
}
return true;
}
/**
* generates 'count' number of elements from start
* @param start start number
* @param count number of elements
*/
export function range(start, count) {
return Array.apply(0, Array(count)).map((_element, index) => index + start);
}
/**
* Remove `null` or `undefined` elements
* @param doc
*/
export function removeNull(page: Page): Page {
const newElements: Element[] = page.elements.filter(e => e !== null && typeof e !== 'undefined');
if (page.elements.length - newElements.length !== 0) {
logger.debug(
`Null elements removed for page #${page.pageNumber}: ${page.elements.length -
newElements.length}`,
);
page.elements = newElements;
}
return page;
}
/**
* Get page from page number
* @param doc Document
* @param pageNumber Page number
*/
export function getPage(doc: Document, pageNumber: number): Page {
return doc.pages.filter(p => p.pageNumber === pageNumber)[0];
}
/**
* Build a RegExp that matches any page numbers (i.e. Page 3, -3-, 3 of 5, (iii), etc.)
*/
export function getPageRegex(): RegExp {
const pageWord = '(?:Pages?|Páginas?)';
const ofWord = '(?:of|de|-|/)';
const before = '[\\(\\[\\- ]*';
const after = '[\\]\\)\\- ]*';
const arabNumber = '[\\d]+';
const romanNumber = 'M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})';
const pageNumber = `(${arabNumber}|${romanNumber})`;
const pagePrefix = `${pageWord}\\s*(?:\\|\\s*)?`;
const pageRegex = new RegExp(
`^(?:` +
`(?:${pagePrefix}${pageNumber})|` +
`(?:${pageNumber}\\s*(?:\\|\\s*)?${pageWord})|` +
`(?:(?:${pageWord}\\s*)?${pageNumber}\\s*${ofWord}\\s*${pageNumber})|` +
`(?:${before}${pageNumber}${after})` +
`)$`,
'i',
);
return pageRegex;
}
/**
* Create a pool of promises with a maximal number of concurrent executions
* @param poolLimit Max number of concurrent executions
* @param args Arguments to give to the promiseConstructor
* @param promiseConstructor Function that will create promises
*/
export function promisePool<U, T>(
poolLimit: number,
args: U[],
promiseConstructor: (arg: U) => Promise<T>,
): Promise<T[]> {
return new Promise<T[]>((resolve, reject) => {
let i: number = 0;
const allPromises: Array<Promise<T>> = [];
const racingPromises: Array<Promise<T>> = [];
function enqueue(): void {
if (allPromises.length === args.length) {
// Every promise has been created, one just waits for them to resolve
Promise.all(allPromises)
.then(values => {
resolve(values);
})
.catch(e => reject(e));
} else {
// Create a new promise and add it to the running pool
const arg: U = args[i++];
const promise: Promise<T> = promiseConstructor(arg);
promise.then(() => racingPromises.splice(racingPromises.indexOf(promise), 1));
allPromises.push(promise);
racingPromises.push(promise);
if (racingPromises.length < poolLimit) {
enqueue();
} else {
Promise.race(racingPromises)
.then(() => {
enqueue();
})
.catch(e => reject(e));
}
}
}
enqueue();
});
}
/**
* Prettifies an object and returns the pretty string
* @param obj The object to be prettified
*/
export function prettifyObject(obj: object, compact: boolean = false): string {
return inspect(obj, { colors: true, compact });
}
export function round(n: number, decimals: number = 2): number {
return Math.round(n * Math.pow(10, decimals)) / Math.pow(10, decimals);
}
export function toKebabCase(str: string): string {
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
// converts a sentence to title case
export function toTitleCase(str: string): string {
return str
.split(' ')
.map(w => w[0].toUpperCase() + w.slice(1, w.length))
.join(' ');
}
/**
* Generates a convex hull from vertices
* @param vertices the list of vertices of type number[][], as [[x,y], ...]
* @return polygon as number[][]
*/
export function getConvexHull(vertices: number[][]): number[][] {
return concaveman(vertices);
}
/**
* Computes all the angles of a polygon
* @param orderedVertices list of vertices forming the segments as number[][]
* @return angles at each vertex as number[]
*/
export function getAnglesOfPolygon(orderedVertices: number[][]): number[] {
function computeAngle(dx: number, dy: number): number {
let theta = Math.atan2(dy, dx); // range (-PI, PI]
theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
// if (theta < 0) theta = 360 + theta; // range [0, 360)
return theta;
}
const angles: number[] = [];
orderedVertices.forEach((vertex, index) => {
if (index !== orderedVertices.length - 1) {
const from: number[] = vertex;
const to: number[] = orderedVertices[index + 1];
angles.push(computeAngle(to[0] - from[0], to[1] - from[1]));
}
});
return angles;
}
/**
* Computes addition of two vectors. If they're of different sizes, the extra
* dimensions are copied as-is at the trailing end of the result.
* @param vec1: first vector in n dimensions
* @param vec2: second vector in m dimensions
*/
export function addVectors(vec1: number[], vec2: number[]): number[] {
let smallerVector: number[];
let biggerVector: number[];
let result: number[] = [];
if (vec1.length < vec2.length) {
smallerVector = vec1;
biggerVector = vec2;
} else if (vec2.length < vec1.length) {
smallerVector = vec2;
biggerVector = vec1;
} else {
for (let i = 0; i !== vec1.length; ++i) {
result.push(vec1[i] + vec2[i]);
}
return result;
}
for (let i = 0; i !== smallerVector.length; ++i) {
result.push(smallerVector[i] + biggerVector[i]);
}
result = [...result, ...biggerVector.slice(smallerVector.length, biggerVector.length)];
return result;
}
/**
* Computes euclidean distance between two vectors.
* @param vec1: first vector in n dimensions
* @param vec2: second vector in n dimensions
*/
export function getEuclideanDistance(vec1: number[], vec2: number[]): number {
if (vec1.length !== vec2.length) {
return -1;
} // maybe resize? TODO
const subtracted = vec1.map((i, n) => i - vec2[n]);
const powered = subtracted.map(e => Math.pow(e, 2));
const sum = powered.reduce((total, current) => total + current, 0);
return Math.sqrt(sum);
}
/**
* Computes the magnitude of a vector.
* @param vec: the vector
*/
export function getMagnitude(vec: number[]): number {
let sumOfSquares: number = 0;
for (const n of vec) {
sumOfSquares += n * n;
}
return Math.sqrt(sumOfSquares);
}
/**
* Computes the dot product between two vectors.
* @param vec1: first vector in n dimensions
* @param vec2: second vector in n dimensions
*/
export function getDotProduct(vec1: number[], vec2: number[]): number {
let result: number = 0;
const lim: number = Math.min(vec1.length, vec2.length);
if (vec1.length !== vec2.length) {
logger.warn('[dotProduct] vectors have different sizes:', vec1.length, vec2.length);
logger.warn('[dotProduct] taking min size', lim);
}
for (let i = 0; i < lim; i++) {
result += vec1[i] * vec2[i];
}
return result;
}
/**
* Finds the occurrence of an element in an array and returns the positions.
* @param array: an array of type T
* @param element: element to be looked for in the array
* @return an array of position(s)
*/
export function findPositionsInArray<T>(array: T[], element: T): number[] {
const result: number[] = [];
array.forEach((value, position) => {
if (value === element) {
result.push(position);
}
});
return result;
}
export function isGeneralUpperCase(lineGroup: Line[]): boolean {
let generalUpperCase: boolean;
const upperCaseScores: boolean[] = lineGroup.map((l: Line) => {
if (l.toString().toUpperCase() === l.toString()) {
return true;
} else {
return false;
}
});
if (
upperCaseScores.filter((s: boolean) => s === true).length >
Math.floor(upperCaseScores.length / 2)
) {
generalUpperCase = true;
} else {
generalUpperCase = false;
}
return generalUpperCase;
}
export function isGeneralTitleCase(lineGroup: Line[]): boolean {
let generalTitleCase: boolean;
const titleCaseScores: boolean[] = lineGroup.map((l: Line) => {
if (toTitleCase(l.toString()) === l.toString()) {
return true;
} else {
return false;
}
});
if (
titleCaseScores.filter((s: boolean) => s === true).length >
Math.floor(titleCaseScores.length / 2)
) {
generalTitleCase = true;
} else {
generalTitleCase = false;
}
return generalTitleCase;
}
/***
* Finds the most common font among a list of fonts
*/
export function findMostCommonFont(fonts: Font[]): Font | undefined {
const baskets: Font[][] = [];
fonts.forEach((font: Font) => {
let basketFound: boolean = false;
baskets.forEach((basket: Font[]) => {
if (basket.length > 0 && basket[0].isEqual(font)) {
basket.push(font);
basketFound = true;
}
});
if (!basketFound) {
baskets.push([font]);
}
});
baskets.sort((a, b) => {
return b.length - a.length;
});
if (baskets.length > 0 && baskets[0].length > 0) {
return baskets[0][0];
} else {
return undefined;
}
}
/**
* Returns the grouping of consecutive numbers in an array
* @param theArray The input array of numbers
*/
export function groupConsecutiveNumbersInArray(theArray: number[]): number[][] {
let result: number[][] = [];
result = theArray
.sort((a, b) => a - b)
.reduce((r, n) => {
const lastSubArray = r[r.length - 1];
if (!lastSubArray || lastSubArray[lastSubArray.length - 1] !== n - 1) {
r.push([]);
}
r[r.length - 1].push(n);
return r;
}, []);
return result;
}
export function getEmphazisChars(text: string): string {
const boldRegexp = new RegExp(/^\*\*.+\*\*$/);
const italicRegexp = new RegExp(/^\*.+\*$/);
const boldItalicRegexp = new RegExp(/^\*\*\*.+\*\*\*$/);
if (boldRegexp.test(text)) {
return '**';
}
if (italicRegexp.test(text)) {
return '*';
}
if (boldItalicRegexp.test(text)) {
return '***';
}
return '';
}
/**
* Returns the ocr extractor depending on the extractor selected in the configuration.
*
* @returns The OcrExtractor instance
*/
export function getOcrExtractor(config: Config): OcrExtractor {
switch (config.extractor.ocr) {
case 'tesseract':
return new TesseractExtractor(config);
case 'google-vision':
return new GoogleVisionExtractor(config);
case 'ms-cognitive-services':
return new MicrosoftCognitiveExtractor(config);
case 'amazon-textract':
return new AmazonTextractExtractor(config);
default:
return new AbbyyTools(config);
}
}
/**
* Returns the pdf extraction orchestrator depending on the extractor selection made in the configuration.
*
* @returns The Extractor instance
*/
export function getPdfExtractor(config: Config): Extractor {
switch (config.extractor.pdf) {
case 'abbyy':
return new AbbyyTools(config);
case 'tesseract':
return new TesseractExtractor(config);
case 'pdfjs':
return new PDFJsExtractor(config);
default:
return new PdfminerExtractor(config);
}
}
export async function convertHTMLToPDF(html: string, outputFile?: string): Promise<string> {
let mainPDF = getTemporaryFile('.pdf');
if (outputFile) {
mainPDF = outputFile;
}
html = embedImagesInHTML(html);
const toPDF = new HTMLToPDF(html, {
browserOptions: {
args: ['--no-sandbox', '--font-render-hinting=none'],
},
pdfOptions: {
path: mainPDF,
width: '210mm',
height: '297mm',
margin: {
top: '5mm',
bottom: '5mm',
left: '5mm',
right: '5mm',
},
},
});
await toPDF.convert();
return mainPDF;
}
// converts the image tags in the HTML with absolute paths to tags with the data as base64
function embedImagesInHTML(html: string): string {
const regexp = new RegExp(/<img src="(\/.*?)"\s(?:style=.*?)*?\s\/>/);
let match = null;
// tslint:disable-next-line: no-conditional-assignment
while ((match = regexp.exec(html)) !== null) {
const imagePath = match[1];
const extension = path.extname(imagePath);
let base64 = '';
if (fs.existsSync(imagePath)) {
base64 = Buffer.from(fs.readFileSync(imagePath)).toString('base64');
}
html = html.replace(imagePath, `data:image/${extension};base64,${base64}`);
}
return html;
}
export function sanitizeXML(xmlPath: string): Promise<string> {
const startTime: number = Date.now();
const cacheKey = `sanitizeXML-${xmlPath}`;
if (Cache.has(cacheKey)) {
return Promise.resolve(Cache.get(cacheKey));
}
return new Promise<any>((resolve, _reject) => {
try {
// replace with empty char everything forbidden by XML 1.0 specifications,
// plus the unicode replacement character U+FFFD
// eslint-disable-next-line no-control-regex
const regex = /((?:[\0-\x08\x0B\f\x0E-\x1F\uFFFD\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|(?:&#\d*;)))/g;
const xml: string = fs.readFileSync(xmlPath, 'utf-8');
const outputFilePath = getTemporaryFile('.xml');
fs.writeFileSync(outputFilePath, xml.replace(new RegExp(regex), ' '));
logger.info(`Sanitize XML: ${(Date.now() - startTime) / 1000}s`);
Cache.set(cacheKey, outputFilePath);
resolve(outputFilePath);
} catch (error) {
logger.warn(`Error sanitizing XML ${error}`);
resolve(xmlPath);
}
});
}
// each value should be a number between 0 and 255
export function rgbToHex(r: number, g: number, b: number) {
return (
'#' +
[r, g, b]
.map(x => {
const hex = Math.ceil(x).toString(16);
return hex.length === 1 ? '0' + hex : hex;
})
.join('')
);
}
export function isPerimeterLine(l: SvgLine, box: BoundingBox): boolean {
const [fromX, fromY, toX, toY] = [l.fromX, l.fromY, l.toX, l.toY].map(n => Math.round(n));
const x = Math.min(fromX, toX);
const y = Math.min(fromY, toY);
const xMin = Math.floor(x - l.thickness / 2);
const xMax = Math.ceil(x + l.thickness / 2);
const yMin = Math.floor(y - l.thickness / 2);
const yMax = Math.ceil(y + l.thickness / 2);
return (l.isVertical() && (xMin <= 0 || xMax >= Math.floor(box.width)))
|| (l.isHorizontal() && (yMin <= 0 || yMax >= Math.floor(box.height)));
}
export function isPixelLine(l: SvgLine): boolean {
const w = Math.abs(l.fromX - l.toX);
const h = Math.abs(l.fromY - l.toY);
return w < 0.5 && h < 0.5;
}
export function minValue(arr: number[]) {
let len = arr.length;
let min = Infinity;
while (len--) {
min = arr[len] < min ? arr[len] : min;
}
return min;
}
export function maxValue(arr: number[]) {
let len = arr.length;
let max = -Infinity;
while (len--) {
max = arr[len] > max ? arr[len] : max;
}
return max;
} | the_stack |
import { Duration, SecretValue, Tokenization } from '@aws-cdk/core';
import { IConstruct } from 'constructs';
import { CfnListener } from '../elasticloadbalancingv2.generated';
import { IListenerAction } from '../shared/listener-action';
import { IApplicationListener } from './application-listener';
import { IApplicationTargetGroup } from './application-target-group';
// keep this import separate from other imports to reduce chance for merge conflicts with v2-main
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct } from 'constructs';
/**
* What to do when a client makes a request to a listener
*
* Some actions can be combined with other ones (specifically,
* you can perform authentication before serving the request).
*
* Multiple actions form a linked chain; the chain must always terminate in a
* *(weighted)forward*, *fixedResponse* or *redirect* action.
*
* If an action supports chaining, the next action can be indicated
* by passing it in the `next` property.
*
* (Called `ListenerAction` instead of the more strictly correct
* `ListenerAction` because this is the class most users interact
* with, and we want to make it not too visually overwhelming).
*/
export class ListenerAction implements IListenerAction {
/**
* Authenticate using an identity provider (IdP) that is compliant with OpenID Connect (OIDC)
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html#oidc-requirements
*/
public static authenticateOidc(options: AuthenticateOidcOptions): ListenerAction {
return new ListenerAction({
type: 'authenticate-oidc',
authenticateOidcConfig: {
authorizationEndpoint: options.authorizationEndpoint,
clientId: options.clientId,
clientSecret: options.clientSecret.unsafeUnwrap(), // Safe usage
issuer: options.issuer,
tokenEndpoint: options.tokenEndpoint,
userInfoEndpoint: options.userInfoEndpoint,
authenticationRequestExtraParams: options.authenticationRequestExtraParams,
onUnauthenticatedRequest: options.onUnauthenticatedRequest,
scope: options.scope,
sessionCookieName: options.sessionCookieName,
sessionTimeout: options.sessionTimeout?.toSeconds().toString(),
},
}, options.next);
}
/**
* Forward to one or more Target Groups
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#forward-actions
*/
public static forward(targetGroups: IApplicationTargetGroup[], options: ForwardOptions = {}): ListenerAction {
if (targetGroups.length === 0) {
throw new Error('Need at least one targetGroup in a ListenerAction.forward()');
}
if (targetGroups.length === 1 && options.stickinessDuration === undefined) {
// Render a "simple" action for backwards compatibility with old templates
return new TargetGroupListenerAction(targetGroups, {
type: 'forward',
targetGroupArn: targetGroups[0].targetGroupArn,
});
}
return new TargetGroupListenerAction(targetGroups, {
type: 'forward',
forwardConfig: {
targetGroups: targetGroups.map(g => ({ targetGroupArn: g.targetGroupArn })),
targetGroupStickinessConfig: options.stickinessDuration ? {
durationSeconds: options.stickinessDuration.toSeconds(),
enabled: true,
} : undefined,
},
});
}
/**
* Forward to one or more Target Groups which are weighted differently
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#forward-actions
*/
public static weightedForward(targetGroups: WeightedTargetGroup[], options: ForwardOptions = {}): ListenerAction {
if (targetGroups.length === 0) {
throw new Error('Need at least one targetGroup in a ListenerAction.weightedForward()');
}
return new TargetGroupListenerAction(targetGroups.map(g => g.targetGroup), {
type: 'forward',
forwardConfig: {
targetGroups: targetGroups.map(g => ({ targetGroupArn: g.targetGroup.targetGroupArn, weight: g.weight })),
targetGroupStickinessConfig: options.stickinessDuration ? {
durationSeconds: options.stickinessDuration.toSeconds(),
enabled: true,
} : undefined,
},
});
}
/**
* Return a fixed response
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#fixed-response-actions
*/
public static fixedResponse(statusCode: number, options: FixedResponseOptions = {}): ListenerAction {
return new ListenerAction({
type: 'fixed-response',
fixedResponseConfig: {
statusCode: Tokenization.stringifyNumber(statusCode),
contentType: options.contentType,
messageBody: options.messageBody,
},
});
}
/**
* Redirect to a different URI
*
* A URI consists of the following components:
* protocol://hostname:port/path?query. You must modify at least one of the
* following components to avoid a redirect loop: protocol, hostname, port, or
* path. Any components that you do not modify retain their original values.
*
* You can reuse URI components using the following reserved keywords:
*
* - `#{protocol}`
* - `#{host}`
* - `#{port}`
* - `#{path}` (the leading "/" is removed)
* - `#{query}`
*
* For example, you can change the path to "/new/#{path}", the hostname to
* "example.#{host}", or the query to "#{query}&value=xyz".
*
* @see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#redirect-actions
*/
public static redirect(options: RedirectOptions): ListenerAction {
if ([options.host, options.path, options.port, options.protocol, options.query].findIndex(x => x !== undefined) === -1) {
throw new Error('To prevent redirect loops, set at least one of \'protocol\', \'host\', \'port\', \'path\', or \'query\'.');
}
return new ListenerAction({
type: 'redirect',
redirectConfig: {
statusCode: options.permanent ? 'HTTP_301' : 'HTTP_302',
host: options.host,
path: options.path,
port: options.port,
protocol: options.protocol,
query: options.query,
},
});
}
/**
* Create an instance of ListenerAction
*
* The default class should be good enough for most cases and
* should be created by using one of the static factory functions,
* but allow overriding to make sure we allow flexibility for the future.
*/
protected constructor(private readonly actionJson: CfnListener.ActionProperty, protected readonly next?: ListenerAction) {
}
/**
* Render the actions in this chain
*/
public renderActions(): CfnListener.ActionProperty[] {
return this.renumber([this.actionJson, ...this.next?.renderActions() ?? []]);
}
/**
* Called when the action is being used in a listener
*/
public bind(scope: Construct, listener: IApplicationListener, associatingConstruct?: IConstruct) {
// Empty on purpose
Array.isArray(scope);
Array.isArray(listener);
Array.isArray(associatingConstruct);
}
/**
* Renumber the "order" fields in the actions array.
*
* We don't number for 0 or 1 elements, but otherwise number them 1...#actions
* so ELB knows about the right order.
*
* Do this in `ListenerAction` instead of in `Listener` so that we give
* users the opportunity to override by subclassing and overriding `renderActions`.
*/
protected renumber(actions: CfnListener.ActionProperty[]): CfnListener.ActionProperty[] {
if (actions.length < 2) { return actions; }
return actions.map((action, i) => ({ ...action, order: i + 1 }));
}
}
/**
* Options for `ListenerAction.forward()`
*/
export interface ForwardOptions {
/**
* For how long clients should be directed to the same target group
*
* Range between 1 second and 7 days.
*
* @default - No stickiness
*/
readonly stickinessDuration?: Duration;
}
/**
* A Target Group and weight combination
*/
export interface WeightedTargetGroup {
/**
* The target group
*/
readonly targetGroup: IApplicationTargetGroup;
/**
* The target group's weight
*
* Range is [0..1000).
*
* @default 1
*/
readonly weight?: number;
}
/**
* Options for `ListenerAction.fixedResponse()`
*/
export interface FixedResponseOptions {
/**
* Content Type of the response
*
* Valid Values: text/plain | text/css | text/html | application/javascript | application/json
*
* @default - Automatically determined
*/
readonly contentType?: string;
/**
* The response body
*
* @default - No body
*/
readonly messageBody?: string;
}
/**
* Options for `ListenerAction.redirect()`
*
* A URI consists of the following components:
* protocol://hostname:port/path?query. You must modify at least one of the
* following components to avoid a redirect loop: protocol, hostname, port, or
* path. Any components that you do not modify retain their original values.
*
* You can reuse URI components using the following reserved keywords:
*
* - `#{protocol}`
* - `#{host}`
* - `#{port}`
* - `#{path}` (the leading "/" is removed)
* - `#{query}`
*
* For example, you can change the path to "/new/#{path}", the hostname to
* "example.#{host}", or the query to "#{query}&value=xyz".
*/
export interface RedirectOptions {
/**
* The hostname.
*
* This component is not percent-encoded. The hostname can contain #{host}.
*
* @default - No change
*/
readonly host?: string;
/**
* The absolute path, starting with the leading "/".
*
* This component is not percent-encoded. The path can contain #{host}, #{path}, and #{port}.
*
* @default - No change
*/
readonly path?: string;
/**
* The port.
*
* You can specify a value from 1 to 65535 or #{port}.
*
* @default - No change
*/
readonly port?: string;
/**
* The protocol.
*
* You can specify HTTP, HTTPS, or #{protocol}. You can redirect HTTP to HTTP, HTTP to HTTPS, and HTTPS to HTTPS. You cannot redirect HTTPS to HTTP.
*
* @default - No change
*/
readonly protocol?: string;
/**
* The query parameters, URL-encoded when necessary, but not percent-encoded.
*
* Do not include the leading "?", as it is automatically added. You can specify any of the reserved keywords.
*
* @default - No change
*/
readonly query?: string;
/**
* The HTTP redirect code.
*
* The redirect is either permanent (HTTP 301) or temporary (HTTP 302).
*
* @default false
*/
readonly permanent?: boolean;
}
/**
* Options for `ListenerAction.authenciateOidc()`
*/
export interface AuthenticateOidcOptions {
/**
* What action to execute next
*/
readonly next: ListenerAction;
/**
* The query parameters (up to 10) to include in the redirect request to the authorization endpoint.
*
* @default - No extra parameters
*/
readonly authenticationRequestExtraParams?: Record<string, string>;
/**
* The authorization endpoint of the IdP.
*
* This must be a full URL, including the HTTPS protocol, the domain, and the path.
*/
readonly authorizationEndpoint: string;
/**
* The OAuth 2.0 client identifier.
*/
readonly clientId: string;
/**
* The OAuth 2.0 client secret.
*/
readonly clientSecret: SecretValue;
/**
* The OIDC issuer identifier of the IdP.
*
* This must be a full URL, including the HTTPS protocol, the domain, and the path.
*/
readonly issuer: string;
/**
* The behavior if the user is not authenticated.
*
* @default UnauthenticatedAction.AUTHENTICATE
*/
readonly onUnauthenticatedRequest?: UnauthenticatedAction;
/**
* The set of user claims to be requested from the IdP.
*
* To verify which scope values your IdP supports and how to separate multiple values, see the documentation for your IdP.
*
* @default "openid"
*/
readonly scope?: string;
/**
* The name of the cookie used to maintain session information.
*
* @default "AWSELBAuthSessionCookie"
*/
readonly sessionCookieName?: string;
/**
* The maximum duration of the authentication session.
*
* @default Duration.days(7)
*/
readonly sessionTimeout?: Duration;
/**
* The token endpoint of the IdP.
*
* This must be a full URL, including the HTTPS protocol, the domain, and the path.
*/
readonly tokenEndpoint: string;
/**
* The user info endpoint of the IdP.
*
* This must be a full URL, including the HTTPS protocol, the domain, and the path.
*/
readonly userInfoEndpoint: string;
}
/**
* What to do with unauthenticated requests
*/
export enum UnauthenticatedAction {
/**
* Return an HTTP 401 Unauthorized error.
*/
DENY = 'deny',
/**
* Allow the request to be forwarded to the target.
*/
ALLOW = 'allow',
/**
* Redirect the request to the IdP authorization endpoint.
*/
AUTHENTICATE = 'authenticate',
}
/**
* Listener Action that calls "registerListener" on TargetGroups
*/
class TargetGroupListenerAction extends ListenerAction {
constructor(private readonly targetGroups: IApplicationTargetGroup[], actionJson: CfnListener.ActionProperty) {
super(actionJson);
}
public bind(_scope: Construct, listener: IApplicationListener, associatingConstruct?: IConstruct) {
for (const tg of this.targetGroups) {
tg.registerListener(listener, associatingConstruct);
}
}
} | the_stack |
import '../../../test/common-test-setup-karma';
import '../../edit/gr-edit-constants';
import '../gr-thread-list/gr-thread-list';
import './gr-change-view';
import {
ChangeStatus,
CommentSide,
DefaultBase,
DiffViewMode,
HttpMethod,
MessageTag,
PrimaryTab,
createDefaultPreferences,
} from '../../../constants/constants';
import {GrEditConstants} from '../../edit/gr-edit-constants';
import {_testOnly_resetEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints';
import {GerritNav} from '../../core/gr-navigation/gr-navigation';
import {getPluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader';
import {EventType, PluginApi} from '../../../api/plugin';
import 'lodash/lodash';
import {
mockPromise,
queryAndAssert,
stubRestApi,
stubUsers,
waitQueryAndAssert,
waitUntil,
} from '../../../test/test-utils';
import {
createAppElementChangeViewParams,
createApproval,
createChange,
createChangeMessages,
createCommit,
createMergeable,
createPreferences,
createRevision,
createRevisions,
createServerInfo,
createUserConfig,
TEST_NUMERIC_CHANGE_ID,
TEST_PROJECT_NAME,
createEditRevision,
createAccountWithIdNameAndEmail,
createChangeViewChange,
createRelatedChangeAndCommitInfo,
createAccountDetailWithId,
createParsedChange,
} from '../../../test/test-data-generators';
import {ChangeViewPatchRange, GrChangeView} from './gr-change-view';
import {
AccountId,
ApprovalInfo,
BasePatchSetNum,
ChangeId,
ChangeInfo,
CommitId,
EditPatchSetNum,
NumericChangeId,
ParentPatchSetNum,
PatchRange,
PatchSetNum,
RelatedChangeAndCommitInfo,
ReviewInputTag,
RevisionInfo,
RevisionPatchSetNum,
RobotId,
RobotCommentInfo,
Timestamp,
UrlEncodedCommentId,
} from '../../../types/common';
import {
pressAndReleaseKeyOn,
tap,
} from '@polymer/iron-test-helpers/mock-interactions';
import {GrEditControls} from '../../edit/gr-edit-controls/gr-edit-controls';
import {AppElementChangeViewParams} from '../../gr-app-types';
import {SinonFakeTimers, SinonStubbedMember} from 'sinon';
import {RestApiService} from '../../../services/gr-rest-api/gr-rest-api';
import {CommentThread} from '../../../utils/comment-util';
import {GerritView} from '../../../services/router/router-model';
import {ParsedChangeInfo} from '../../../types/types';
import {GrRelatedChangesList} from '../gr-related-changes-list/gr-related-changes-list';
import {ChangeStates} from '../../shared/gr-change-status/gr-change-status';
import {LoadingStatus} from '../../../services/change/change-model';
import {FocusTarget, GrReplyDialog} from '../gr-reply-dialog/gr-reply-dialog';
import {GrOverlay} from '../../shared/gr-overlay/gr-overlay';
import {GrChangeStar} from '../../shared/gr-change-star/gr-change-star';
import {GrThreadList} from '../gr-thread-list/gr-thread-list';
const fixture = fixtureFromElement('gr-change-view');
suite('gr-change-view tests', () => {
let element: GrChangeView;
let navigateToChangeStub: SinonStubbedMember<
typeof GerritNav.navigateToChange
>;
const ROBOT_COMMENTS_LIMIT = 10;
// TODO: should have a mock service to generate VALID fake data
const THREADS: CommentThread[] = [
{
comments: [
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 2 as PatchSetNum,
robot_id: 'rb1' as RobotId,
id: 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId,
line: 5,
updated: '2018-02-08 18:49:18.000000000' as Timestamp,
message: 'test',
unresolved: true,
},
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 4 as PatchSetNum,
id: 'ecf0b9fa_fe1a5f62_1' as UrlEncodedCommentId,
line: 5,
updated: '2018-02-08 18:49:18.000000000' as Timestamp,
message: 'test',
unresolved: true,
},
{
id: '503008e2_0ab203ee' as UrlEncodedCommentId,
path: '/COMMIT_MSG',
line: 5,
in_reply_to: 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId,
updated: '2018-02-13 22:48:48.018000000' as Timestamp,
message: 'draft',
unresolved: false,
__draft: true,
patch_set: 2 as PatchSetNum,
},
],
patchNum: 4 as RevisionPatchSetNum,
path: '/COMMIT_MSG',
line: 5,
rootId: 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId,
commentSide: CommentSide.REVISION,
},
{
comments: [
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 3 as PatchSetNum,
id: 'ecf0b9fa_fe5f62' as UrlEncodedCommentId,
robot_id: 'rb2' as RobotId,
line: 5,
updated: '2018-02-08 18:49:18.000000000' as Timestamp,
message: 'test',
unresolved: true,
},
{
path: 'test.txt',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 3 as PatchSetNum,
id: '09a9fb0a_1484e6cf' as UrlEncodedCommentId,
side: CommentSide.PARENT,
updated: '2018-02-13 22:47:19.000000000' as Timestamp,
message: 'Some comment on another patchset.',
unresolved: false,
},
],
patchNum: 3 as PatchSetNum,
path: 'test.txt',
rootId: '09a9fb0a_1484e6cf' as UrlEncodedCommentId,
commentSide: CommentSide.PARENT,
},
{
comments: [
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 2 as PatchSetNum,
id: '8caddf38_44770ec1' as UrlEncodedCommentId,
line: 4,
updated: '2018-02-13 22:48:40.000000000' as Timestamp,
message: 'Another unresolved comment',
unresolved: true,
},
],
patchNum: 2 as RevisionPatchSetNum,
path: '/COMMIT_MSG',
line: 4,
rootId: '8caddf38_44770ec1' as UrlEncodedCommentId,
commentSide: CommentSide.REVISION,
},
{
comments: [
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 2 as PatchSetNum,
id: 'scaddf38_44770ec1' as UrlEncodedCommentId,
line: 4,
updated: '2018-02-14 22:48:40.000000000' as Timestamp,
message: 'Yet another unresolved comment',
unresolved: true,
},
],
patchNum: 2 as RevisionPatchSetNum,
path: '/COMMIT_MSG',
line: 4,
rootId: 'scaddf38_44770ec1' as UrlEncodedCommentId,
commentSide: CommentSide.REVISION,
},
{
comments: [
{
id: 'zcf0b9fa_fe1a5f62' as UrlEncodedCommentId,
path: '/COMMIT_MSG',
line: 6,
updated: '2018-02-15 22:48:48.018000000' as Timestamp,
message: 'resolved draft',
unresolved: false,
__draft: true,
patch_set: 2 as PatchSetNum,
},
],
patchNum: 4 as RevisionPatchSetNum,
path: '/COMMIT_MSG',
line: 6,
rootId: 'zcf0b9fa_fe1a5f62' as UrlEncodedCommentId,
commentSide: CommentSide.REVISION,
},
{
comments: [
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 4 as PatchSetNum,
id: 'rc1' as UrlEncodedCommentId,
line: 5,
updated: '2019-02-08 18:49:18.000000000' as Timestamp,
message: 'test',
unresolved: true,
robot_id: 'rc1' as RobotId,
},
],
patchNum: 4 as RevisionPatchSetNum,
path: '/COMMIT_MSG',
line: 5,
rootId: 'rc1' as UrlEncodedCommentId,
commentSide: CommentSide.REVISION,
},
{
comments: [
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 4 as PatchSetNum,
id: 'rc2' as UrlEncodedCommentId,
line: 5,
updated: '2019-03-08 18:49:18.000000000' as Timestamp,
message: 'test',
unresolved: true,
robot_id: 'rc2' as RobotId,
},
{
path: '/COMMIT_MSG',
author: {
_account_id: 1000000 as AccountId,
name: 'user',
username: 'user',
},
patch_set: 4 as PatchSetNum,
id: 'c2_1' as UrlEncodedCommentId,
line: 5,
updated: '2019-03-08 18:49:18.000000000' as Timestamp,
message: 'test',
unresolved: true,
},
],
patchNum: 4 as RevisionPatchSetNum,
path: '/COMMIT_MSG',
line: 5,
rootId: 'rc2' as UrlEncodedCommentId,
commentSide: CommentSide.REVISION,
},
];
setup(() => {
// Since pluginEndpoints are global, must reset state.
_testOnly_resetEndpoints();
navigateToChangeStub = sinon.stub(GerritNav, 'navigateToChange');
stubRestApi('getConfig').returns(
Promise.resolve({
...createServerInfo(),
user: {
...createUserConfig(),
anonymous_coward_name: 'test coward name',
},
})
);
stubRestApi('getAccount').returns(
Promise.resolve(createAccountDetailWithId(5))
);
stubRestApi('getDiffComments').returns(Promise.resolve({}));
stubRestApi('getDiffRobotComments').returns(Promise.resolve({}));
stubRestApi('getDiffDrafts').returns(Promise.resolve({}));
element = fixture.instantiate();
element._changeNum = TEST_NUMERIC_CHANGE_ID;
sinon.stub(element.$.actions, 'reload').returns(Promise.resolve());
getPluginLoader().loadPlugins([]);
window.Gerrit.install(
plugin => {
plugin.registerDynamicCustomComponent(
'change-view-tab-header',
'gr-checks-change-view-tab-header-view'
);
plugin.registerDynamicCustomComponent(
'change-view-tab-content',
'gr-checks-view'
);
},
'0.1',
'http://some/plugins/url.js'
);
});
teardown(async () => {
await flush();
});
test('_handleMessageAnchorTap', () => {
element._changeNum = 1 as NumericChangeId;
element._patchRange = {
basePatchNum: ParentPatchSetNum,
patchNum: 1 as RevisionPatchSetNum,
};
element._change = createChangeViewChange();
const getUrlStub = sinon.stub(GerritNav, 'getUrlForChange');
const replaceStateStub = sinon.stub(history, 'replaceState');
element._handleMessageAnchorTap(
new CustomEvent('message-anchor-tap', {detail: {id: 'a12345'}})
);
assert.equal(getUrlStub.lastCall.args[1]!.messageHash, '#message-a12345');
assert.isTrue(replaceStateStub.called);
});
test('_handleDiffAgainstBase', () => {
element._change = {
...createChangeViewChange(),
revisions: createRevisions(10),
};
element._patchRange = {
patchNum: 3 as RevisionPatchSetNum,
basePatchNum: 1 as BasePatchSetNum,
};
element._handleDiffAgainstBase();
assert(navigateToChangeStub.called);
const args = navigateToChangeStub.getCall(0).args;
assert.equal(args[0], element._change);
assert.equal(args[1]!.patchNum, 3 as PatchSetNum);
});
test('_handleDiffAgainstLatest', () => {
element._change = {
...createChangeViewChange(),
revisions: createRevisions(10),
};
element._patchRange = {
basePatchNum: 1 as BasePatchSetNum,
patchNum: 3 as RevisionPatchSetNum,
};
element._handleDiffAgainstLatest();
assert(navigateToChangeStub.called);
const args = navigateToChangeStub.getCall(0).args;
assert.equal(args[0], element._change);
assert.equal(args[1]!.patchNum, 10 as PatchSetNum);
assert.equal(args[1]!.basePatchNum, 1 as BasePatchSetNum);
});
test('_handleDiffBaseAgainstLeft', () => {
element._change = {
...createChangeViewChange(),
revisions: createRevisions(10),
};
element._patchRange = {
patchNum: 3 as RevisionPatchSetNum,
basePatchNum: 1 as BasePatchSetNum,
};
element._handleDiffBaseAgainstLeft();
assert(navigateToChangeStub.called);
const args = navigateToChangeStub.getCall(0).args;
assert.equal(args[0], element._change);
assert.equal(args[1]!.patchNum, 1 as PatchSetNum);
});
test('_handleDiffRightAgainstLatest', () => {
element._change = {
...createChangeViewChange(),
revisions: createRevisions(10),
};
element._patchRange = {
basePatchNum: 1 as BasePatchSetNum,
patchNum: 3 as RevisionPatchSetNum,
};
element._handleDiffRightAgainstLatest();
assert(navigateToChangeStub.called);
const args = navigateToChangeStub.getCall(0).args;
assert.equal(args[1]!.patchNum, 10 as PatchSetNum);
assert.equal(args[1]!.basePatchNum, 3 as BasePatchSetNum);
});
test('_handleDiffBaseAgainstLatest', () => {
element._change = {
...createChangeViewChange(),
revisions: createRevisions(10),
};
element._patchRange = {
basePatchNum: 1 as BasePatchSetNum,
patchNum: 3 as RevisionPatchSetNum,
};
element._handleDiffBaseAgainstLatest();
assert(navigateToChangeStub.called);
const args = navigateToChangeStub.getCall(0).args;
assert.equal(args[1]!.patchNum, 10 as PatchSetNum);
assert.isNotOk(args[1]!.basePatchNum);
});
test('toggle attention set status', async () => {
element._change = {
...createChangeViewChange(),
revisions: createRevisions(10),
};
const addToAttentionSetStub = stubRestApi('addToAttentionSet').returns(
Promise.resolve(new Response())
);
const removeFromAttentionSetStub = stubRestApi(
'removeFromAttentionSet'
).returns(Promise.resolve(new Response()));
element._patchRange = {
basePatchNum: 1 as BasePatchSetNum,
patchNum: 3 as RevisionPatchSetNum,
};
assert.isNotOk(element._change.attention_set);
await element._getLoggedIn();
await element.restApiService.getAccount();
element._handleToggleAttentionSet();
assert.isTrue(addToAttentionSetStub.called);
assert.isFalse(removeFromAttentionSetStub.called);
element._handleToggleAttentionSet();
assert.isTrue(removeFromAttentionSetStub.called);
});
suite('plugins adding to file tab', () => {
setup(async () => {
element._changeNum = TEST_NUMERIC_CHANGE_ID;
// Resolving it here instead of during setup() as other tests depend
// on flush() not being called during setup.
await flush();
});
test('plugin added tab shows up as a dynamic endpoint', () => {
assert(
element._dynamicTabHeaderEndpoints.includes(
'change-view-tab-header-url'
)
);
const primaryTabs = element.shadowRoot!.querySelector('#primaryTabs')!;
const paperTabs = primaryTabs.querySelectorAll<HTMLElement>('paper-tab');
// 4 Tabs are : Files, Comment Threads, Plugin, Findings
assert.equal(primaryTabs.querySelectorAll('paper-tab').length, 4);
assert.equal(paperTabs[2].dataset.name, 'change-view-tab-header-url');
});
test('_setActivePrimaryTab switched tab correctly', async () => {
element._setActivePrimaryTab(
new CustomEvent('', {
detail: {tab: 'change-view-tab-header-url'},
})
);
await flush();
assert.equal(element._activeTabs[0], 'change-view-tab-header-url');
});
test('show-primary-tab switched primary tab correctly', async () => {
element.dispatchEvent(
new CustomEvent('show-primary-tab', {
composed: true,
bubbles: true,
detail: {
tab: 'change-view-tab-header-url',
},
})
);
await flush();
assert.equal(element._activeTabs[0], 'change-view-tab-header-url');
});
test('param change should switch primary tab correctly', async () => {
assert.equal(element._activeTabs[0], PrimaryTab.FILES);
// view is required
element._changeNum = undefined;
element.params = {
...createAppElementChangeViewParams(),
...element.params,
tab: PrimaryTab.FINDINGS,
};
await flush();
assert.equal(element._activeTabs[0], PrimaryTab.FINDINGS);
});
test('invalid param change should not switch primary tab', async () => {
assert.equal(element._activeTabs[0], PrimaryTab.FILES);
// view is required
element.params = {
...createAppElementChangeViewParams(),
...element.params,
tab: 'random',
};
await flush();
assert.equal(element._activeTabs[0], PrimaryTab.FILES);
});
test('switching tab sets _selectedTabPluginEndpoint', async () => {
const paperTabs = element.shadowRoot!.querySelector('#primaryTabs')!;
tap(paperTabs.querySelectorAll('paper-tab')[2]);
await flush();
assert.equal(
element._selectedTabPluginEndpoint,
'change-view-tab-content-url'
);
});
});
suite('keyboard shortcuts', () => {
let clock: SinonFakeTimers;
setup(() => {
clock = sinon.useFakeTimers();
});
teardown(() => {
clock.restore();
sinon.restore();
});
test('t to add topic', () => {
const editStub = sinon.stub(element.$.metadata, 'editTopic');
pressAndReleaseKeyOn(element, 83, null, 't');
assert(editStub.called);
});
test('S should toggle the CL star', () => {
const starStub = sinon.stub(element.$.changeStar, 'toggleStar');
pressAndReleaseKeyOn(element, 83, null, 's');
assert(starStub.called);
});
test('toggle star is throttled', () => {
const starStub = sinon.stub(element.$.changeStar, 'toggleStar');
pressAndReleaseKeyOn(element, 83, null, 's');
assert(starStub.called);
pressAndReleaseKeyOn(element, 83, null, 's');
assert.equal(starStub.callCount, 1);
clock.tick(1000);
pressAndReleaseKeyOn(element, 83, null, 's');
assert.equal(starStub.callCount, 2);
});
test('U should navigate to root if no backPage set', () => {
const relativeNavStub = sinon.stub(GerritNav, 'navigateToRelativeUrl');
pressAndReleaseKeyOn(element, 85, null, 'u');
assert.isTrue(relativeNavStub.called);
assert.isTrue(
relativeNavStub.lastCall.calledWithExactly(GerritNav.getUrlForRoot())
);
});
test('U should navigate to backPage if set', () => {
const relativeNavStub = sinon.stub(GerritNav, 'navigateToRelativeUrl');
element.backPage = '/dashboard/self';
pressAndReleaseKeyOn(element, 85, null, 'u');
assert.isTrue(relativeNavStub.called);
assert.isTrue(
relativeNavStub.lastCall.calledWithExactly('/dashboard/self')
);
});
test('A fires an error event when not logged in', async () => {
sinon.stub(element, '_getLoggedIn').returns(Promise.resolve(false));
const loggedInErrorSpy = sinon.spy();
element.addEventListener('show-auth-required', loggedInErrorSpy);
pressAndReleaseKeyOn(element, 65, null, 'a');
await flush();
assert.isFalse(element.$.replyOverlay.opened);
assert.isTrue(loggedInErrorSpy.called);
});
test('shift A does not open reply overlay', async () => {
sinon.stub(element, '_getLoggedIn').returns(Promise.resolve(true));
pressAndReleaseKeyOn(element, 65, 'shift', 'a');
await flush();
assert.isFalse(element.$.replyOverlay.opened);
});
test('A toggles overlay when logged in', async () => {
sinon.stub(element, '_getLoggedIn').returns(Promise.resolve(true));
element._change = {
...createChangeViewChange(),
revisions: createRevisions(1),
messages: createChangeMessages(1),
};
element._change.labels = {};
const openSpy = sinon.spy(element, '_openReplyDialog');
pressAndReleaseKeyOn(element, 65, null, 'a');
await flush();
assert.isTrue(element.$.replyOverlay.opened);
element.$.replyOverlay.close();
assert.isFalse(element.$.replyOverlay.opened);
assert(
openSpy.lastCall.calledWithExactly(FocusTarget.ANY),
'_openReplyDialog should have been passed ANY'
);
assert.equal(openSpy.callCount, 1);
});
test('fullscreen-overlay-opened hides content', () => {
element._loggedIn = true;
element._loading = false;
element._change = {
...createChangeViewChange(),
labels: {},
actions: {
abandon: {
enabled: true,
label: 'Abandon',
method: HttpMethod.POST,
title: 'Abandon',
},
},
};
const handlerSpy = sinon.spy(element, '_handleHideBackgroundContent');
const overlay = queryAndAssert<GrOverlay>(element, '#replyOverlay');
overlay.dispatchEvent(
new CustomEvent('fullscreen-overlay-opened', {
composed: true,
bubbles: true,
})
);
assert.isTrue(handlerSpy.called);
assert.isTrue(element.$.mainContent.classList.contains('overlayOpen'));
assert.equal(getComputedStyle(element.$.actions).display, 'flex');
});
test('fullscreen-overlay-closed shows content', () => {
element._loggedIn = true;
element._loading = false;
element._change = {
...createChangeViewChange(),
labels: {},
actions: {
abandon: {
enabled: true,
label: 'Abandon',
method: HttpMethod.POST,
title: 'Abandon',
},
},
};
const handlerSpy = sinon.spy(element, '_handleShowBackgroundContent');
const overlay = queryAndAssert<GrOverlay>(element, '#replyOverlay');
overlay.dispatchEvent(
new CustomEvent('fullscreen-overlay-closed', {
composed: true,
bubbles: true,
})
);
assert.isTrue(handlerSpy.called);
assert.isFalse(element.$.mainContent.classList.contains('overlayOpen'));
});
test('expand all messages when expand-diffs fired', () => {
const handleExpand = sinon.stub(element.$.fileList, 'expandAllDiffs');
element.$.fileListHeader.dispatchEvent(
new CustomEvent('expand-diffs', {
composed: true,
bubbles: true,
})
);
assert.isTrue(handleExpand.called);
});
test('collapse all messages when collapse-diffs fired', () => {
const handleCollapse = sinon.stub(element.$.fileList, 'collapseAllDiffs');
element.$.fileListHeader.dispatchEvent(
new CustomEvent('collapse-diffs', {
composed: true,
bubbles: true,
})
);
assert.isTrue(handleCollapse.called);
});
test('X should expand all messages', async () => {
await flush();
const handleExpand = sinon.stub(
element.messagesList!,
'handleExpandCollapse'
);
pressAndReleaseKeyOn(element, 88, null, 'x');
assert(handleExpand.calledWith(true));
});
test('Z should collapse all messages', async () => {
await flush();
const handleExpand = sinon.stub(
element.messagesList!,
'handleExpandCollapse'
);
pressAndReleaseKeyOn(element, 90, null, 'z');
assert(handleExpand.calledWith(false));
});
test('d should open download overlay', () => {
const stub = sinon
.stub(element.$.downloadOverlay, 'open')
.returns(Promise.resolve());
pressAndReleaseKeyOn(element, 68, null, 'd');
assert.isTrue(stub.called);
});
test(', should open diff preferences', () => {
const stub = sinon.stub(
element.$.fileList.$.diffPreferencesDialog,
'open'
);
element._loggedIn = false;
pressAndReleaseKeyOn(element, 188, null, ',');
assert.isFalse(stub.called);
element._loggedIn = true;
pressAndReleaseKeyOn(element, 188, null, ',');
assert.isTrue(stub.called);
});
test('m should toggle diff mode', async () => {
const updatePreferencesStub = stubUsers('updatePreferences');
await flush();
const prefs = {
...createDefaultPreferences(),
diff_view: DiffViewMode.SIDE_BY_SIDE,
};
element.userModel.setPreferences(prefs);
element._handleToggleDiffMode();
assert.isTrue(
updatePreferencesStub.calledWith({diff_view: DiffViewMode.UNIFIED})
);
const newPrefs = {
...createDefaultPreferences(),
diff_view: DiffViewMode.UNIFIED,
};
element.userModel.setPreferences(newPrefs);
await flush();
element._handleToggleDiffMode();
assert.isTrue(
updatePreferencesStub.calledWith({diff_view: DiffViewMode.SIDE_BY_SIDE})
);
});
});
suite('thread list and change log tabs', () => {
setup(() => {
element._changeNum = TEST_NUMERIC_CHANGE_ID;
element._patchRange = {
basePatchNum: ParentPatchSetNum,
patchNum: 1 as RevisionPatchSetNum,
};
element._change = {
...createChangeViewChange(),
revisions: {
rev2: createRevision(2),
rev1: createRevision(1),
rev13: createRevision(13),
rev3: createRevision(3),
},
current_revision: 'rev3' as CommitId,
status: ChangeStatus.NEW,
labels: {
test: {
all: [],
default_value: 0,
values: {},
approved: {},
},
},
};
const relatedChanges = element.shadowRoot!.querySelector(
'#relatedChanges'
) as GrRelatedChangesList;
sinon.stub(relatedChanges, 'reload');
sinon.stub(element, 'loadData').returns(Promise.resolve());
sinon.spy(element, '_paramsChanged');
element.params = createAppElementChangeViewParams();
});
});
suite('Comments tab', () => {
setup(async () => {
element._changeNum = TEST_NUMERIC_CHANGE_ID;
element._change = {
...createChangeViewChange(),
revisions: {
rev2: createRevision(2),
rev1: createRevision(1),
rev13: createRevision(13),
rev3: createRevision(3),
rev4: createRevision(4),
},
current_revision: 'rev4' as CommitId,
};
element._commentThreads = THREADS;
await flush();
const paperTabs = element.shadowRoot!.querySelector('#primaryTabs')!;
tap(paperTabs.querySelectorAll('paper-tab')[1]);
await flush();
});
test('commentId overrides unresolveOnly default', async () => {
const threadList = queryAndAssert<GrThreadList>(
element,
'gr-thread-list'
);
assert.isTrue(element.unresolvedOnly);
assert.isNotOk(element.scrollCommentId);
assert.isTrue(threadList.unresolvedOnly);
element.scrollCommentId = 'abcd' as UrlEncodedCommentId;
await flush();
assert.isFalse(threadList.unresolvedOnly);
});
});
suite('Findings robot-comment tab', () => {
setup(async () => {
element._changeNum = TEST_NUMERIC_CHANGE_ID;
element._change = {
...createChangeViewChange(),
revisions: {
rev2: createRevision(2),
rev1: createRevision(1),
rev13: createRevision(13),
rev3: createRevision(3),
rev4: createRevision(4),
},
current_revision: 'rev4' as CommitId,
};
element._commentThreads = THREADS;
await flush();
const paperTabs = element.shadowRoot!.querySelector('#primaryTabs')!;
tap(paperTabs.querySelectorAll('paper-tab')[3]);
await flush();
});
test('robot comments count per patchset', () => {
const count = element._robotCommentCountPerPatchSet(THREADS);
const expectedCount = {
2: 1,
3: 1,
4: 2,
};
assert.deepEqual(count, expectedCount);
assert.equal(
element._computeText(createRevision(2), THREADS),
'Patchset 2 (1 finding)'
);
assert.equal(
element._computeText(createRevision(4), THREADS),
'Patchset 4 (2 findings)'
);
assert.equal(
element._computeText(createRevision(5), THREADS),
'Patchset 5'
);
});
test('only robot comments are rendered', () => {
assert.equal(element._robotCommentThreads!.length, 2);
assert.equal(
(element._robotCommentThreads![0].comments[0] as RobotCommentInfo)
.robot_id,
'rc1'
);
assert.equal(
(element._robotCommentThreads![1].comments[0] as RobotCommentInfo)
.robot_id,
'rc2'
);
});
test('changing patchsets resets robot comments', async () => {
element.set('_change.current_revision', 'rev3');
await flush();
assert.equal(element._robotCommentThreads!.length, 1);
});
test('Show more button is hidden', () => {
assert.isNull(element.shadowRoot!.querySelector('.show-robot-comments'));
});
suite('robot comments show more button', () => {
setup(async () => {
const arr = [];
for (let i = 0; i <= 30; i++) {
arr.push(...THREADS);
}
element._commentThreads = arr;
await flush();
});
test('Show more button is rendered', () => {
assert.isOk(element.shadowRoot!.querySelector('.show-robot-comments'));
assert.equal(
element._robotCommentThreads!.length,
ROBOT_COMMENTS_LIMIT
);
});
test('Clicking show more button renders all comments', async () => {
tap(element.shadowRoot!.querySelector('.show-robot-comments')!);
await flush();
assert.equal(element._robotCommentThreads!.length, 62);
});
});
});
test('reply button is not visible when logged out', () => {
assert.equal(getComputedStyle(element.$.replyBtn).display, 'none');
element._loggedIn = true;
assert.notEqual(getComputedStyle(element.$.replyBtn).display, 'none');
});
test('download tap calls _handleOpenDownloadDialog', () => {
const openDialogStub = sinon.stub(element, '_handleOpenDownloadDialog');
element.$.actions.dispatchEvent(
new CustomEvent('download-tap', {
composed: true,
bubbles: true,
})
);
assert.isTrue(openDialogStub.called);
});
test('fetches the server config on attached', async () => {
await flush();
assert.equal(
element._serverConfig!.user.anonymous_coward_name,
'test coward name'
);
});
test('_changeStatuses', () => {
element._loading = false;
element._change = {
...createChangeViewChange(),
revisions: {
rev2: createRevision(2),
rev1: createRevision(1),
rev13: createRevision(13),
rev3: createRevision(3),
},
current_revision: 'rev3' as CommitId,
status: ChangeStatus.MERGED,
work_in_progress: true,
labels: {
test: {
all: [],
default_value: 0,
values: {},
approved: {},
},
},
};
element._mergeable = true;
const expectedStatuses = [ChangeStates.MERGED, ChangeStates.WIP];
assert.deepEqual(element._changeStatuses, expectedStatuses);
flush();
const statusChips =
element.shadowRoot!.querySelectorAll('gr-change-status');
assert.equal(statusChips.length, 2);
});
suite('ChangeStatus revert', () => {
test('do not show any chip if no revert created', async () => {
const change = {
...createParsedChange(),
messages: createChangeMessages(2),
};
const getChangeStub = stubRestApi('getChange');
getChangeStub.onFirstCall().returns(
Promise.resolve({
...createChange(),
})
);
getChangeStub.onSecondCall().returns(
Promise.resolve({
...createChange(),
})
);
element._change = change;
element._mergeable = true;
element._submitEnabled = true;
await flush();
element.computeRevertSubmitted(element._change);
await flush();
assert.isFalse(
element._changeStatuses?.includes(ChangeStates.REVERT_SUBMITTED)
);
assert.isFalse(
element._changeStatuses?.includes(ChangeStates.REVERT_CREATED)
);
});
test('do not show any chip if all reverts are abandoned', async () => {
const change = {
...createParsedChange(),
messages: createChangeMessages(2),
};
change.messages[0].message = 'Created a revert of this change as 12345';
change.messages[0].tag = MessageTag.TAG_REVERT as ReviewInputTag;
change.messages[1].message = 'Created a revert of this change as 23456';
change.messages[1].tag = MessageTag.TAG_REVERT as ReviewInputTag;
const getChangeStub = stubRestApi('getChange');
getChangeStub.onFirstCall().returns(
Promise.resolve({
...createChange(),
status: ChangeStatus.ABANDONED,
})
);
getChangeStub.onSecondCall().returns(
Promise.resolve({
...createChange(),
status: ChangeStatus.ABANDONED,
})
);
element._change = change;
element._mergeable = true;
element._submitEnabled = true;
await flush();
element.computeRevertSubmitted(element._change);
await flush();
assert.isFalse(
element._changeStatuses?.includes(ChangeStates.REVERT_SUBMITTED)
);
assert.isFalse(
element._changeStatuses?.includes(ChangeStates.REVERT_CREATED)
);
});
test('show revert created if no revert is merged', async () => {
const change = {
...createParsedChange(),
messages: createChangeMessages(2),
};
change.messages[0].message = 'Created a revert of this change as 12345';
change.messages[0].tag = MessageTag.TAG_REVERT as ReviewInputTag;
change.messages[1].message = 'Created a revert of this change as 23456';
change.messages[1].tag = MessageTag.TAG_REVERT as ReviewInputTag;
const getChangeStub = stubRestApi('getChange');
getChangeStub.onFirstCall().returns(
Promise.resolve({
...createChange(),
})
);
getChangeStub.onSecondCall().returns(
Promise.resolve({
...createChange(),
})
);
element._change = change;
element._mergeable = true;
element._submitEnabled = true;
await flush();
element.computeRevertSubmitted(element._change);
await flush();
assert.isFalse(
element._changeStatuses?.includes(ChangeStates.REVERT_SUBMITTED)
);
assert.isTrue(
element._changeStatuses?.includes(ChangeStates.REVERT_CREATED)
);
});
test('show revert submitted if revert is merged', async () => {
const change = {
...createParsedChange(),
messages: createChangeMessages(2),
};
change.messages[0].message = 'Created a revert of this change as 12345';
change.messages[0].tag = MessageTag.TAG_REVERT as ReviewInputTag;
const getChangeStub = stubRestApi('getChange');
getChangeStub.onFirstCall().returns(
Promise.resolve({
...createChange(),
status: ChangeStatus.MERGED,
})
);
getChangeStub.onSecondCall().returns(
Promise.resolve({
...createChange(),
})
);
element._change = change;
element._mergeable = true;
element._submitEnabled = true;
await flush();
element.computeRevertSubmitted(element._change);
await flush();
assert.isFalse(
element._changeStatuses?.includes(ChangeStates.REVERT_CREATED)
);
assert.isTrue(
element._changeStatuses?.includes(ChangeStates.REVERT_SUBMITTED)
);
});
});
test('diff preferences open when open-diff-prefs is fired', () => {
const overlayOpenStub = sinon.stub(element.$.fileList, 'openDiffPrefs');
element.$.fileListHeader.dispatchEvent(
new CustomEvent('open-diff-prefs', {
composed: true,
bubbles: true,
})
);
assert.isTrue(overlayOpenStub.called);
});
test('_prepareCommitMsgForLinkify', () => {
let commitMessage = 'R=test@google.com';
let result = element._prepareCommitMsgForLinkify(commitMessage);
assert.equal(result, 'R=\u200Btest@google.com');
commitMessage = 'R=test@google.com\nR=test@google.com';
result = element._prepareCommitMsgForLinkify(commitMessage);
assert.equal(result, 'R=\u200Btest@google.com\nR=\u200Btest@google.com');
commitMessage = 'CC=test@google.com';
result = element._prepareCommitMsgForLinkify(commitMessage);
assert.equal(result, 'CC=\u200Btest@google.com');
});
test('_isSubmitEnabled', () => {
assert.isFalse(element._isSubmitEnabled({}));
assert.isFalse(element._isSubmitEnabled({submit: {}}));
assert.isTrue(element._isSubmitEnabled({submit: {enabled: true}}));
});
test('_reload is called when an approved label is removed', () => {
const vote: ApprovalInfo = {
...createApproval(),
_account_id: 1 as AccountId,
name: 'bojack',
value: 1,
};
element._changeNum = TEST_NUMERIC_CHANGE_ID;
element._patchRange = {
basePatchNum: ParentPatchSetNum,
patchNum: 1 as RevisionPatchSetNum,
};
const change = {
...createChangeViewChange(),
owner: createAccountWithIdNameAndEmail(),
revisions: {
rev2: createRevision(2),
rev1: createRevision(1),
rev13: createRevision(13),
rev3: createRevision(3),
},
current_revision: 'rev3' as CommitId,
status: ChangeStatus.NEW,
labels: {
test: {
all: [vote],
default_value: 0,
values: {},
approved: {},
},
},
};
element._change = change;
flush();
const reloadStub = sinon.stub(element, 'loadData');
element.splice('_change.labels.test.all', 0, 1);
assert.isFalse(reloadStub.called);
change.labels.test.all.push(vote);
change.labels.test.all.push(vote);
change.labels.test.approved = vote;
flush();
element.splice('_change.labels.test.all', 0, 2);
assert.isTrue(reloadStub.called);
assert.isTrue(reloadStub.calledOnce);
});
test('reply button has updated count when there are drafts', () => {
const getLabel = element._computeReplyButtonLabel;
assert.equal(getLabel(undefined, false), 'Reply');
assert.equal(getLabel(undefined, true), 'Reply');
let drafts = {};
assert.equal(getLabel(drafts, false), 'Reply');
drafts = {
'file1.txt': [{}],
'file2.txt': [{}, {}],
};
assert.equal(getLabel(drafts, false), 'Reply (3)');
assert.equal(getLabel(drafts, true), 'Start Review (3)');
});
test('change num change', () => {
const change = {
...createChangeViewChange(),
labels: {},
} as ParsedChangeInfo;
element._changeNum = undefined;
element._patchRange = {
basePatchNum: ParentPatchSetNum,
patchNum: 2 as RevisionPatchSetNum,
};
element._change = change;
element.viewState.changeNum = null;
element.viewState.diffMode = DiffViewMode.UNIFIED;
assert.equal(element.viewState.numFilesShown, 200);
assert.equal(element._numFilesShown, 200);
element._numFilesShown = 150;
flush();
assert.equal(element.viewState.diffMode, DiffViewMode.UNIFIED);
assert.equal(element.viewState.numFilesShown, 150);
element._changeNum = 1 as NumericChangeId;
element.params = {
...createAppElementChangeViewParams(),
changeNum: 1 as NumericChangeId,
};
flush();
assert.equal(element.viewState.diffMode, DiffViewMode.UNIFIED);
assert.equal(element.viewState.changeNum, 1);
element._changeNum = 2 as NumericChangeId;
element.params = {
...createAppElementChangeViewParams(),
changeNum: 2 as NumericChangeId,
};
flush();
assert.equal(element.viewState.diffMode, DiffViewMode.UNIFIED);
assert.equal(element.viewState.changeNum, 2);
assert.equal(element.viewState.numFilesShown, 200);
assert.equal(element._numFilesShown, 200);
});
test('don’t reload entire page when patchRange changes', async () => {
const reloadStub = sinon
.stub(element, 'loadData')
.callsFake(() => Promise.resolve());
const reloadPatchDependentStub = sinon
.stub(element, '_reloadPatchNumDependentResources')
.callsFake(() => Promise.resolve([undefined, undefined, undefined]));
flush();
const collapseStub = sinon.stub(element.$.fileList, 'collapseAllDiffs');
const value: AppElementChangeViewParams = {
...createAppElementChangeViewParams(),
view: GerritView.CHANGE,
patchNum: 1 as RevisionPatchSetNum,
};
element._changeNum = undefined;
element.params = value;
await flush();
assert.isTrue(reloadStub.calledOnce);
element._initialLoadComplete = true;
element._change = {
...createChangeViewChange(),
revisions: {
rev1: createRevision(1),
rev2: createRevision(2),
},
};
value.basePatchNum = 1 as BasePatchSetNum;
value.patchNum = 2 as RevisionPatchSetNum;
element.params = {...value};
await flush();
assert.isFalse(reloadStub.calledTwice);
assert.isTrue(reloadPatchDependentStub.calledOnce);
assert.isTrue(collapseStub.calledTwice);
});
test('reload ported comments when patchNum changes', async () => {
sinon.stub(element, 'loadData').callsFake(() => Promise.resolve());
sinon.stub(element, 'loadAndSetCommitInfo');
sinon.stub(element.$.fileList, 'reload');
flush();
const reloadPortedCommentsStub = sinon.stub(
element.getCommentsModel(),
'reloadPortedComments'
);
const reloadPortedDraftsStub = sinon.stub(
element.getCommentsModel(),
'reloadPortedDrafts'
);
sinon.stub(element.$.fileList, 'collapseAllDiffs');
const value: AppElementChangeViewParams = {
...createAppElementChangeViewParams(),
view: GerritView.CHANGE,
patchNum: 1 as RevisionPatchSetNum,
};
element.params = value;
await flush();
element._initialLoadComplete = true;
element._change = {
...createChangeViewChange(),
revisions: {
rev1: createRevision(1),
rev2: createRevision(2),
},
};
value.basePatchNum = 1 as BasePatchSetNum;
value.patchNum = 2 as RevisionPatchSetNum;
element.params = {...value};
await flush();
assert.isTrue(reloadPortedCommentsStub.calledOnce);
assert.isTrue(reloadPortedDraftsStub.calledOnce);
});
test('do not reload entire page when patchRange doesnt change', async () => {
const reloadStub = sinon
.stub(element, 'loadData')
.callsFake(() => Promise.resolve());
const collapseStub = sinon.stub(element.$.fileList, 'collapseAllDiffs');
const value: AppElementChangeViewParams =
createAppElementChangeViewParams();
element.params = value;
// change already loaded
assert.isOk(element._changeNum);
await flush();
assert.isFalse(reloadStub.calledOnce);
element._initialLoadComplete = true;
element.params = {...value};
await flush();
assert.isFalse(reloadStub.calledTwice);
assert.isFalse(collapseStub.calledTwice);
});
test('forceReload updates the change', async () => {
const getChangeStub = stubRestApi('getChangeDetail').returns(
Promise.resolve(createParsedChange())
);
const loadDataStub = sinon
.stub(element, 'loadData')
.callsFake(() => Promise.resolve());
const collapseStub = sinon.stub(element.$.fileList, 'collapseAllDiffs');
element.params = {...createAppElementChangeViewParams(), forceReload: true};
await flush();
assert.isTrue(getChangeStub.called);
assert.isTrue(loadDataStub.called);
assert.isTrue(collapseStub.called);
// patchNum is set by changeChanged, so this verifies that _change was set.
assert.isOk(element._patchRange?.patchNum);
});
test('do not handle new change numbers', async () => {
const recreateSpy = sinon.spy();
element.addEventListener('recreate-change-view', recreateSpy);
const value: AppElementChangeViewParams =
createAppElementChangeViewParams();
element.params = value;
await flush();
assert.isFalse(recreateSpy.calledOnce);
value.changeNum = 555111333 as NumericChangeId;
element.params = {...value};
await flush();
assert.isTrue(recreateSpy.calledOnce);
});
test('related changes are not updated after other action', async () => {
sinon.stub(element, 'loadData').callsFake(() => Promise.resolve());
await flush();
const relatedChanges = element.shadowRoot!.querySelector(
'#relatedChanges'
) as GrRelatedChangesList;
sinon.stub(relatedChanges, 'reload');
await element.loadData(true);
assert.isFalse(navigateToChangeStub.called);
});
test('_computeCopyTextForTitle', () => {
const change: ChangeInfo = {
...createChangeViewChange(),
_number: 123 as NumericChangeId,
subject: 'test subject',
revisions: {
rev1: createRevision(1),
rev3: createRevision(3),
},
current_revision: 'rev3' as CommitId,
};
sinon.stub(GerritNav, 'getUrlForChange').returns('/change/123');
assert.equal(
element._computeCopyTextForTitle(change),
`123: test subject | http://${location.host}/change/123`
);
});
test('get latest revision', () => {
let change: ChangeInfo = {
...createChange(),
revisions: {
rev1: createRevision(1),
rev3: createRevision(3),
},
current_revision: 'rev3' as CommitId,
};
assert.equal(element._getLatestRevisionSHA(change), 'rev3');
change = {
...createChange(),
revisions: {
rev1: createRevision(1),
},
current_revision: undefined,
};
assert.equal(element._getLatestRevisionSHA(change), 'rev1');
});
test('show commit message edit button', () => {
const change = createChange();
const mergedChanged: ChangeInfo = {
...createChangeViewChange(),
status: ChangeStatus.MERGED,
};
assert.isTrue(element._computeHideEditCommitMessage(false, false, change));
assert.isTrue(element._computeHideEditCommitMessage(true, true, change));
assert.isTrue(element._computeHideEditCommitMessage(false, true, change));
assert.isFalse(element._computeHideEditCommitMessage(true, false, change));
assert.isTrue(
element._computeHideEditCommitMessage(true, false, mergedChanged)
);
assert.isTrue(
element._computeHideEditCommitMessage(true, false, change, true)
);
assert.isFalse(
element._computeHideEditCommitMessage(true, false, change, false)
);
});
test('_handleCommitMessageSave trims trailing whitespace', () => {
element._change = createChangeViewChange();
// Response code is 500, because we want to avoid window reloading
const putStub = stubRestApi('putChangeCommitMessage').returns(
Promise.resolve(new Response(null, {status: 500}))
);
const mockEvent = (content: string) =>
new CustomEvent('', {detail: {content}});
element._handleCommitMessageSave(mockEvent('test \n test '));
assert.equal(putStub.lastCall.args[1], 'test\n test');
element._handleCommitMessageSave(mockEvent(' test\ntest'));
assert.equal(putStub.lastCall.args[1], ' test\ntest');
element._handleCommitMessageSave(mockEvent('\n\n\n\n\n\n\n\n'));
assert.equal(putStub.lastCall.args[1], '\n\n\n\n\n\n\n\n');
});
test('topic is coalesced to null', async () => {
sinon.stub(element, '_changeChanged');
element.changeModel.setState({
loadingStatus: LoadingStatus.LOADED,
change: {
...createChangeViewChange(),
labels: {},
current_revision: 'foo' as CommitId,
revisions: {foo: createRevision()},
},
});
await element.performPostChangeLoadTasks();
assert.isNull(element._change!.topic);
});
test('commit sha is populated from getChangeDetail', async () => {
sinon.stub(element, '_changeChanged');
element.changeModel.setState({
loadingStatus: LoadingStatus.LOADED,
change: {
...createChangeViewChange(),
labels: {},
current_revision: 'foo' as CommitId,
revisions: {foo: createRevision()},
},
});
await element.performPostChangeLoadTasks();
assert.equal('foo', element._commitInfo!.commit);
});
test('_getBasePatchNum', () => {
const _change: ChangeInfo = {
...createChangeViewChange(),
revisions: {
'98da160735fb81604b4c40e93c368f380539dd0e': createRevision(),
},
};
const _patchRange: ChangeViewPatchRange = {
basePatchNum: ParentPatchSetNum,
};
assert.equal(element._getBasePatchNum(_change, _patchRange), 'PARENT');
element._prefs = {
...createPreferences(),
default_base_for_merges: DefaultBase.FIRST_PARENT,
};
const _change2: ChangeInfo = {
...createChangeViewChange(),
revisions: {
'98da160735fb81604b4c40e93c368f380539dd0e': {
...createRevision(1),
commit: {
...createCommit(),
parents: [
{
commit: '6e12bdf1176eb4ab24d8491ba3b6d0704409cde8' as CommitId,
subject: 'test',
},
{
commit: '22f7db4754b5d9816fc581f3d9a6c0ef8429c841' as CommitId,
subject: 'test3',
},
],
},
},
},
};
assert.equal(element._getBasePatchNum(_change2, _patchRange), -1);
_patchRange.patchNum = 1 as RevisionPatchSetNum;
assert.equal(element._getBasePatchNum(_change2, _patchRange), 'PARENT');
});
test('_openReplyDialog called with `ANY` when coming from tap event', async () => {
await flush();
const openStub = sinon.stub(element, '_openReplyDialog');
tap(element.$.replyBtn);
assert(
openStub.lastCall.calledWithExactly(FocusTarget.ANY),
'_openReplyDialog should have been passed ANY'
);
assert.equal(openStub.callCount, 1);
});
test(
'_openReplyDialog called with `BODY` when coming from message reply' +
'event',
async () => {
await flush();
const openStub = sinon.stub(element, '_openReplyDialog');
element.messagesList!.dispatchEvent(
new CustomEvent('reply', {
detail: {message: {message: 'text'}},
composed: true,
bubbles: true,
})
);
assert.isTrue(openStub.calledOnce);
assert.equal(openStub.lastCall.args[0], FocusTarget.BODY);
}
);
test('reply dialog focus can be controlled', () => {
const openStub = sinon.stub(element, '_openReplyDialog');
const e = new CustomEvent('show-reply-dialog', {
detail: {value: {ccsOnly: false}},
});
element._handleShowReplyDialog(e);
assert(
openStub.lastCall.calledWithExactly(FocusTarget.REVIEWERS),
'_openReplyDialog should have been passed REVIEWERS'
);
assert.equal(openStub.callCount, 1);
e.detail.value = {ccsOnly: true};
element._handleShowReplyDialog(e);
assert(
openStub.lastCall.calledWithExactly(FocusTarget.CCS),
'_openReplyDialog should have been passed CCS'
);
assert.equal(openStub.callCount, 2);
});
test('getUrlParameter functionality', () => {
const locationStub = sinon.stub(element, '_getLocationSearch');
locationStub.returns('?test');
assert.equal(element._getUrlParameter('test'), 'test');
locationStub.returns('?test2=12&test=3');
assert.equal(element._getUrlParameter('test'), 'test');
locationStub.returns('');
assert.isNull(element._getUrlParameter('test'));
locationStub.returns('?');
assert.isNull(element._getUrlParameter('test'));
locationStub.returns('?test2');
assert.isNull(element._getUrlParameter('test'));
});
test('revert dialog opened with revert param', async () => {
const awaitPluginsLoadedStub = sinon
.stub(getPluginLoader(), 'awaitPluginsLoaded')
.callsFake(() => Promise.resolve());
element._patchRange = {
basePatchNum: ParentPatchSetNum,
patchNum: 2 as RevisionPatchSetNum,
};
element._change = {
...createChangeViewChange(),
revisions: {
rev1: createRevision(1),
rev2: createRevision(2),
},
current_revision: 'rev1' as CommitId,
status: ChangeStatus.MERGED,
labels: {},
actions: {},
};
sinon.stub(element, '_getUrlParameter').callsFake(param => {
assert.equal(param, 'revert');
return param;
});
const promise = mockPromise();
sinon
.stub(element.$.actions, 'showRevertDialog')
.callsFake(() => promise.resolve());
element._maybeShowRevertDialog();
assert.isTrue(awaitPluginsLoadedStub.called);
await promise;
});
suite('reply dialog tests', () => {
setup(() => {
element._change = {
...createChangeViewChange(),
// element has latest info
revisions: {rev1: createRevision()},
messages: createChangeMessages(1),
current_revision: 'rev1' as CommitId,
labels: {},
};
});
test('show reply dialog on open-reply-dialog event', async () => {
const openReplyDialogStub = sinon.stub(element, '_openReplyDialog');
element.dispatchEvent(
new CustomEvent('open-reply-dialog', {
composed: true,
bubbles: true,
detail: {},
})
);
await flush();
assert.isTrue(openReplyDialogStub.calledOnce);
});
test('reply from comment adds quote text', async () => {
const e = new CustomEvent('', {
detail: {message: {message: 'quote text'}},
});
element._handleMessageReply(e);
const dialog = await waitQueryAndAssert<GrReplyDialog>(
element,
'#replyDialog'
);
const openSpy = sinon.spy(dialog, 'open');
await flush();
await waitUntil(() => openSpy.called && !!openSpy.lastCall.args[1]);
assert.equal(openSpy.lastCall.args[1], '> quote text\n\n');
});
});
test('reply button is disabled until server config is loaded', async () => {
assert.isTrue(element._replyDisabled);
// fetches the server config on attached
await flush();
assert.isFalse(element._replyDisabled);
});
test('header class computation', () => {
assert.equal(element._computeHeaderClass(), 'header');
assert.equal(element._computeHeaderClass(true), 'header editMode');
});
test('_maybeScrollToMessage', async () => {
await flush();
const scrollStub = sinon.stub(element.messagesList!, 'scrollToMessage');
element._maybeScrollToMessage('');
assert.isFalse(scrollStub.called);
element._maybeScrollToMessage('message');
assert.isFalse(scrollStub.called);
element._maybeScrollToMessage('#message-TEST');
assert.isTrue(scrollStub.called);
assert.equal(scrollStub.lastCall.args[0], 'TEST');
});
test('topic update reloads related changes', () => {
flush();
const relatedChanges = element.shadowRoot!.querySelector(
'#relatedChanges'
) as GrRelatedChangesList;
const reloadStub = sinon.stub(relatedChanges, 'reload');
element.dispatchEvent(new CustomEvent('topic-changed'));
assert.isTrue(reloadStub.calledOnce);
});
test('_computeEditMode', () => {
const callCompute = (
range: PatchRange,
params: AppElementChangeViewParams
) =>
element._computeEditMode(
{base: range, path: '', value: range},
{base: params, path: '', value: params}
);
assert.isTrue(
callCompute(
{basePatchNum: ParentPatchSetNum, patchNum: 1 as RevisionPatchSetNum},
{...createAppElementChangeViewParams(), edit: true}
)
);
assert.isFalse(
callCompute(
{basePatchNum: ParentPatchSetNum, patchNum: 1 as RevisionPatchSetNum},
createAppElementChangeViewParams()
)
);
assert.isTrue(
callCompute(
{basePatchNum: 1 as BasePatchSetNum, patchNum: EditPatchSetNum},
createAppElementChangeViewParams()
)
);
});
test('_processEdit', () => {
element._patchRange = {};
const change: ParsedChangeInfo = {
...createChangeViewChange(),
current_revision: 'foo' as CommitId,
revisions: {
foo: {...createRevision()},
},
};
// With no edit, nothing happens.
element._processEdit(change);
assert.equal(element._patchRange.patchNum, undefined);
change.revisions['bar'] = {
_number: EditPatchSetNum,
basePatchNum: 1 as BasePatchSetNum,
commit: {
...createCommit(),
commit: 'bar' as CommitId,
},
fetch: {},
};
// When edit is set, but not patchNum, then switch to edit ps.
element._processEdit(change);
assert.equal(element._patchRange.patchNum, EditPatchSetNum);
// When edit is set, but patchNum as well, then keep patchNum.
element._patchRange.patchNum = 5 as RevisionPatchSetNum;
element.routerPatchNum = 5 as RevisionPatchSetNum;
element._processEdit(change);
assert.equal(element._patchRange.patchNum, 5 as RevisionPatchSetNum);
});
test('file-action-tap handling', () => {
element._patchRange = {
basePatchNum: ParentPatchSetNum,
patchNum: 1 as RevisionPatchSetNum,
};
element._change = {
...createChangeViewChange(),
};
const fileList = element.$.fileList;
const Actions = GrEditConstants.Actions;
element.$.fileListHeader.editMode = true;
flush();
const controls = element.$.fileListHeader.shadowRoot!.querySelector(
'#editControls'
) as GrEditControls;
const openDeleteDialogStub = sinon.stub(controls, 'openDeleteDialog');
const openRenameDialogStub = sinon.stub(controls, 'openRenameDialog');
const openRestoreDialogStub = sinon.stub(controls, 'openRestoreDialog');
const getEditUrlForDiffStub = sinon.stub(GerritNav, 'getEditUrlForDiff');
const navigateToRelativeUrlStub = sinon.stub(
GerritNav,
'navigateToRelativeUrl'
);
// Delete
fileList.dispatchEvent(
new CustomEvent('file-action-tap', {
detail: {action: Actions.DELETE.id, path: 'foo'},
bubbles: true,
composed: true,
})
);
flush();
assert.isTrue(openDeleteDialogStub.called);
assert.equal(openDeleteDialogStub.lastCall.args[0], 'foo');
// Restore
fileList.dispatchEvent(
new CustomEvent('file-action-tap', {
detail: {action: Actions.RESTORE.id, path: 'foo'},
bubbles: true,
composed: true,
})
);
flush();
assert.isTrue(openRestoreDialogStub.called);
assert.equal(openRestoreDialogStub.lastCall.args[0], 'foo');
// Rename
fileList.dispatchEvent(
new CustomEvent('file-action-tap', {
detail: {action: Actions.RENAME.id, path: 'foo'},
bubbles: true,
composed: true,
})
);
flush();
assert.isTrue(openRenameDialogStub.called);
assert.equal(openRenameDialogStub.lastCall.args[0], 'foo');
// Open
fileList.dispatchEvent(
new CustomEvent('file-action-tap', {
detail: {action: Actions.OPEN.id, path: 'foo'},
bubbles: true,
composed: true,
})
);
flush();
assert.isTrue(getEditUrlForDiffStub.called);
assert.equal(getEditUrlForDiffStub.lastCall.args[1], 'foo');
assert.equal(getEditUrlForDiffStub.lastCall.args[2], 1 as PatchSetNum);
assert.isTrue(navigateToRelativeUrlStub.called);
});
test('_selectedRevision updates when patchNum is changed', () => {
const revision1: RevisionInfo = createRevision(1);
const revision2: RevisionInfo = createRevision(2);
element.changeModel.setState({
loadingStatus: LoadingStatus.LOADED,
change: {
...createChangeViewChange(),
revisions: {
aaa: revision1,
bbb: revision2,
},
labels: {},
actions: {},
current_revision: 'bbb' as CommitId,
},
});
sinon
.stub(element, '_getPreferences')
.returns(Promise.resolve(createPreferences()));
element._patchRange = {patchNum: 2 as RevisionPatchSetNum};
return element.performPostChangeLoadTasks().then(() => {
assert.strictEqual(element._selectedRevision, revision2);
element.set('_patchRange.patchNum', '1');
assert.strictEqual(element._selectedRevision, revision1);
});
});
test('_selectedRevision is assigned when patchNum is edit', async () => {
const revision1 = createRevision(1);
const revision2 = createRevision(2);
const revision3 = createEditRevision();
element.changeModel.setState({
loadingStatus: LoadingStatus.LOADED,
change: {
...createChangeViewChange(),
revisions: {
aaa: revision1,
bbb: revision2,
ccc: revision3,
},
labels: {},
actions: {},
current_revision: 'ccc' as CommitId,
},
});
sinon
.stub(element, '_getPreferences')
.returns(Promise.resolve(createPreferences()));
element._patchRange = {patchNum: EditPatchSetNum};
await element.performPostChangeLoadTasks();
assert.strictEqual(element._selectedRevision, revision3);
});
test('_sendShowChangeEvent', () => {
const change = {...createChangeViewChange(), labels: {}};
element._change = {...change};
element._patchRange = {patchNum: 4 as RevisionPatchSetNum};
element._mergeable = true;
const showStub = sinon.stub(element.jsAPI, 'handleEvent');
element._sendShowChangeEvent();
assert.isTrue(showStub.calledOnce);
assert.equal(showStub.lastCall.args[0], EventType.SHOW_CHANGE);
assert.deepEqual(showStub.lastCall.args[1], {
change,
patchNum: 4,
info: {mergeable: true},
});
});
test('patch range changed', () => {
element._patchRange = undefined;
element._change = createChangeViewChange();
element._change!.revisions = createRevisions(4);
element._change.current_revision = '1' as CommitId;
element._change = {...element._change};
const params = createAppElementChangeViewParams();
assert.isFalse(element.hasPatchRangeChanged(params));
assert.isFalse(element.hasPatchNumChanged(params));
params.basePatchNum = ParentPatchSetNum;
// undefined means navigate to latest patchset
params.patchNum = undefined;
element._patchRange = {
patchNum: 2 as RevisionPatchSetNum,
basePatchNum: ParentPatchSetNum,
};
assert.isTrue(element.hasPatchRangeChanged(params));
assert.isTrue(element.hasPatchNumChanged(params));
element._patchRange = {
patchNum: 4 as RevisionPatchSetNum,
basePatchNum: ParentPatchSetNum,
};
assert.isFalse(element.hasPatchRangeChanged(params));
assert.isFalse(element.hasPatchNumChanged(params));
});
suite('_handleEditTap', () => {
let fireEdit: () => void;
setup(() => {
fireEdit = () => {
element.$.actions.dispatchEvent(new CustomEvent('edit-tap'));
};
navigateToChangeStub.restore();
element._change = {
...createChangeViewChange(),
revisions: {rev1: createRevision()},
};
});
test('edit exists in revisions', async () => {
const promise = mockPromise();
sinon.stub(GerritNav, 'navigateToChange').callsFake((...args) => {
assert.equal(args.length, 2);
assert.equal(args[1]!.patchNum, EditPatchSetNum); // patchNum
promise.resolve();
});
element.set('_change.revisions.rev2', {
_number: EditPatchSetNum,
});
await flush();
fireEdit();
await promise;
});
test('no edit exists in revisions, non-latest patchset', async () => {
const promise = mockPromise();
sinon.stub(GerritNav, 'navigateToChange').callsFake((...args) => {
assert.equal(args.length, 2);
assert.equal(args[1]!.patchNum, 1 as PatchSetNum); // patchNum
assert.equal(args[1]!.isEdit, true); // opt_isEdit
promise.resolve();
});
element.set('_change.revisions.rev2', {_number: 2});
element._patchRange = {patchNum: 1 as RevisionPatchSetNum};
await flush();
fireEdit();
await promise;
});
test('no edit exists in revisions, latest patchset', async () => {
const promise = mockPromise();
sinon.stub(GerritNav, 'navigateToChange').callsFake((...args) => {
assert.equal(args.length, 2);
// No patch should be specified when patchNum == latest.
assert.isNotOk(args[1]!.patchNum); // patchNum
assert.equal(args[1]!.isEdit, true); // opt_isEdit
promise.resolve();
});
element.set('_change.revisions.rev2', {_number: 2});
element._patchRange = {patchNum: 2 as RevisionPatchSetNum};
await flush();
fireEdit();
await promise;
});
});
test('_handleStopEditTap', async () => {
element._change = {
...createChangeViewChange(),
};
sinon.stub(element.$.metadata, '_computeLabelNames');
navigateToChangeStub.restore();
const promise = mockPromise();
sinon.stub(GerritNav, 'navigateToChange').callsFake((...args) => {
assert.equal(args.length, 2);
assert.equal(args[1]!.patchNum, 1 as PatchSetNum); // patchNum
promise.resolve();
});
element._patchRange = {patchNum: 1 as RevisionPatchSetNum};
element.$.actions.dispatchEvent(
new CustomEvent('stop-edit-tap', {bubbles: false})
);
await promise;
});
suite('plugin endpoints', () => {
test('endpoint params', async () => {
element._change = {...createChangeViewChange(), labels: {}};
element._selectedRevision = createRevision();
const promise = mockPromise();
window.Gerrit.install(
promise.resolve,
'0.1',
'http://some/plugins/url.js'
);
await flush();
const plugin: PluginApi = (await promise) as PluginApi;
const hookEl = await plugin
.hook('change-view-integration')
.getLastAttached();
assert.strictEqual((hookEl as any).plugin, plugin);
assert.strictEqual((hookEl as any).change, element._change);
assert.strictEqual((hookEl as any).revision, element._selectedRevision);
});
});
suite('_getMergeability', () => {
let getMergeableStub: SinonStubbedMember<RestApiService['getMergeable']>;
setup(() => {
element._change = {...createChangeViewChange(), labels: {}};
getMergeableStub = stubRestApi('getMergeable').returns(
Promise.resolve({...createMergeable(), mergeable: true})
);
});
test('merged change', () => {
element._mergeable = null;
element._change!.status = ChangeStatus.MERGED;
return element._getMergeability().then(() => {
assert.isFalse(element._mergeable);
assert.isFalse(getMergeableStub.called);
});
});
test('abandoned change', () => {
element._mergeable = null;
element._change!.status = ChangeStatus.ABANDONED;
return element._getMergeability().then(() => {
assert.isFalse(element._mergeable);
assert.isFalse(getMergeableStub.called);
});
});
test('open change', () => {
element._mergeable = null;
return element._getMergeability().then(() => {
assert.isTrue(element._mergeable);
assert.isTrue(getMergeableStub.called);
});
});
});
test('_handleToggleStar called when star is tapped', async () => {
element._change = {
...createChangeViewChange(),
owner: {_account_id: 1 as AccountId},
starred: false,
};
element._loggedIn = true;
await flush();
const stub = sinon.stub(element, '_handleToggleStar');
const changeStar = queryAndAssert<GrChangeStar>(element, '#changeStar');
tap(queryAndAssert<HTMLButtonElement>(changeStar, 'button')!);
assert.isTrue(stub.called);
});
suite('gr-reporting tests', () => {
setup(() => {
element._patchRange = {
basePatchNum: ParentPatchSetNum,
patchNum: 1 as RevisionPatchSetNum,
};
sinon
.stub(element, 'performPostChangeLoadTasks')
.returns(Promise.resolve(false));
sinon.stub(element, '_getProjectConfig').returns(Promise.resolve());
sinon.stub(element, '_getMergeability').returns(Promise.resolve());
sinon.stub(element, '_getLatestCommitMessage').returns(Promise.resolve());
sinon
.stub(element, '_reloadPatchNumDependentResources')
.returns(Promise.resolve([undefined, undefined, undefined]));
});
test("don't report changeDisplayed on reply", async () => {
const changeDisplayStub = sinon.stub(
element.reporting,
'changeDisplayed'
);
const changeFullyLoadedStub = sinon.stub(
element.reporting,
'changeFullyLoaded'
);
element._handleReplySent();
await flush();
assert.isFalse(changeDisplayStub.called);
assert.isFalse(changeFullyLoadedStub.called);
});
test('report changeDisplayed on _paramsChanged', async () => {
const changeDisplayStub = sinon.stub(
element.reporting,
'changeDisplayed'
);
const changeFullyLoadedStub = sinon.stub(
element.reporting,
'changeFullyLoaded'
);
// reset so reload is triggered
element._changeNum = undefined;
element.params = {
...createAppElementChangeViewParams(),
changeNum: TEST_NUMERIC_CHANGE_ID,
project: TEST_PROJECT_NAME,
};
element.changeModel.setState({
loadingStatus: LoadingStatus.LOADED,
change: {
...createChangeViewChange(),
labels: {},
current_revision: 'foo' as CommitId,
revisions: {foo: createRevision()},
},
});
await flush();
assert.isTrue(changeDisplayStub.called);
assert.isTrue(changeFullyLoadedStub.called);
});
});
test('_calculateHasParent', () => {
const changeId = '123' as ChangeId;
const relatedChanges: RelatedChangeAndCommitInfo[] = [];
assert.equal(element._calculateHasParent(changeId, relatedChanges), false);
relatedChanges.push({
...createRelatedChangeAndCommitInfo(),
change_id: '123' as ChangeId,
});
assert.equal(element._calculateHasParent(changeId, relatedChanges), false);
relatedChanges.push({
...createRelatedChangeAndCommitInfo(),
change_id: '234' as ChangeId,
});
assert.equal(element._calculateHasParent(changeId, relatedChanges), true);
});
}); | the_stack |
import { stripIndent } from 'common-tags'
import * as fs from 'fs-jetpack'
import * as Path from 'path'
import prompts from 'prompts'
import { PackageJson } from 'type-fest'
import { Command } from '../../../lib/cli'
import { rightOrFatal } from '../../../lib/utils'
import * as Layout from '../../../lib/layout'
import { tsconfigTemplate } from '../../../lib/layout/tsconfig'
import { rootLogger } from '../../../lib/nexus-logger'
import { ownPackage } from '../../../lib/own-package'
import * as PackageManager from '../../../lib/package-manager'
import * as PluginRuntime from '../../../lib/plugin'
import * as PluginWorktime from '../../../lib/plugin/worktime'
import * as proc from '../../../lib/process'
import { createGitRepository, CWDProjectNameOrGenerate } from '../../../lib/utils'
const log = rootLogger.child('cli').child('create').child('app')
const SQLITE_DEFAULT_CONNECTION_URI = 'file:./dev.db'
export default class App implements Command {
async parse() {
await run({})
}
}
interface ConfigInput {
projectName: string
}
interface InternalConfig {
projectName: string
projectRoot: string
sourceRoot: string
}
/**
* TODO
*/
export async function run(configInput?: Partial<ConfigInput>): Promise<void> {
if (process.env.NEXUS_CREATE_HANDOFF === 'true') {
await runLocalHandOff()
} else {
await runBootstrapper(configInput)
}
}
/**
* TODO
*/
export async function runLocalHandOff(): Promise<void> {
log.trace('start local handoff')
const parentData = await loadDataFromParentProcess()
const layout = rightOrFatal(await Layout.create())
const pluginM = await PluginWorktime.getUsedPlugins(layout)
const plugins = PluginRuntime.importAndLoadWorktimePlugins(pluginM, layout)
log.trace('plugins', { plugins })
// TODO select a template
for (const p of plugins) {
await p.hooks.create.onAfterBaseSetup?.({
database: parentData.database,
connectionURI: parentData.connectionURI,
})
}
}
/**
* TODO
*/
export async function runBootstrapper(configInput?: Partial<ConfigInput>): Promise<void> {
log.trace('start bootstrapper')
await assertIsCleanSlate()
const projectName = configInput?.projectName ?? CWDProjectNameOrGenerate()
const internalConfig: InternalConfig = {
projectName: projectName,
projectRoot: process.cwd(),
sourceRoot: Path.join(process.cwd(), 'api'),
...configInput,
}
const nexusVersion = getNexusVersion()
const packageManager = await getPackageManager(internalConfig.projectRoot)
if (packageManager === 'sigtermed') {
return
}
const database = await getDatabaseSelection()
if (database === 'sigtermed') {
return
}
// TODO in the future scan npm registry for nexus plugins, organize by
// github stars, and so on.
log.info('Scaffolding project')
await scaffoldBaseFiles(internalConfig)
log.info(`Installing dependencies`, {
nexusVersion,
})
await packageManager.addDeps([`nexus@${nexusVersion}`], {
require: true,
})
//
// install additional deps
//
const deps = []
const addDepsConfig: PackageManager.AddDepsOptions = {
envAdditions: {},
}
// [1]
// This allows installing prisma without a warning being emitted about there
// being a missing prisma schema. For more detail refer to
// https://prisma-company.slack.com/archives/CEYCG2MCN/p1575480721184700 and
// https://github.com/prisma/photonjs/blob/master/packages/photon/scripts/generate.js#L67
if (database) {
deps.push(`nexus-plugin-prisma@${getPrismaPluginVersion()}`)
addDepsConfig.envAdditions!.SKIP_GENERATE = 'true' // 1
saveDataForChildProcess({
database: database.choice,
connectionURI: database.connectionURI,
})
// Allow the plugin to be enabled so that nexus can run the `onAfterBaseSetup` hook
await scaffoldTemplate(templates.prisma(internalConfig))
} else {
await scaffoldTemplate(templates.helloWorld(internalConfig))
}
if (deps.length) {
await packageManager.addDeps(deps, {
...addDepsConfig,
require: true,
})
}
await packageManager.addDeps(['prettier'], {
require: true,
dev: true,
})
//
// pass off to local create
//
await packageManager
.runBin('nexus create', {
stdio: 'inherit',
envAdditions: { NEXUS_CREATE_HANDOFF: 'true' },
require: true,
})
.catch((error) => {
console.error(error.message)
process.exit(error.exitCode ?? 1)
})
//
// return to global create
//
// Any disk changes after this point will show up as dirty working directory
// for the user
await createGitRepository()
// If the user setup a db driver but not the connection URI yet, then do not
// enter dev mode yet. Dev mode will result in a runtime-crashing app.
if (!(database && !database.connectionURI)) {
// We will enter dev mode with the local version of nexus. This is a kind
// of cheat, but what we want users to have as their mental model. When they
// terminate this dev session, they will restart it typically with e.g. `$
// yarn dev`. This global-nexus-process-wrapping-local-nexus-process
// is unique to bootstrapping situations.
log.info('Starting dev mode')
await packageManager
.runScript('dev', {
stdio: 'inherit',
envAdditions: { NEXUS_CREATE_HANDOFF: 'true' },
require: true,
})
.catch((error) => {
console.error(error.message)
process.exit(error.exitCode ?? 1)
})
}
}
async function getPackageManager(projectRoot: string): Promise<PackageManager.PackageManager | 'sigtermed'> {
const packageManagerTypeEnvVar = process.env.CREATE_APP_CHOICE_PACKAGE_MANAGER_TYPE as
| PackageManager.PackageManagerType
| undefined
const packageManagerType = packageManagerTypeEnvVar ?? (await askForPackageManager())
if (packageManagerType === 'sigtermed') {
return 'sigtermed'
}
const packageManager = PackageManager.createPackageManager(packageManagerType, { projectRoot })
return packageManager
}
function getNexusVersion(): string {
const nexusVersionEnvVar = process.env.CREATE_APP_CHOICE_NEXUS_VERSION
const nexusVersion = nexusVersionEnvVar ?? `${ownPackage.version}`
return nexusVersion
}
async function getDatabaseSelection(): Promise<DatabaseSelection | 'sigtermed'> {
const envar = process.env.CREATE_APP_CHOICE_DATABASE_TYPE as Database | 'NO_DATABASE' | undefined
if (envar) {
if (envar === 'NO_DATABASE') {
return null
}
if (envar === 'SQLite') {
return {
database: true,
choice: envar,
connectionURI: SQLITE_DEFAULT_CONNECTION_URI,
}
}
return {
database: true,
choice: envar,
connectionURI: undefined,
}
}
return await askForDatabase()
}
// TODO this data should come from db driver
export type Database = 'SQLite' | 'PostgreSQL' | 'MySQL'
type DatabaseSelection =
| null
| 'sigtermed'
| {
database: true
choice: Database
connectionURI: string | undefined
}
/**
* Ask the user if they would like to use a database driver.
*/
async function askForDatabase(): Promise<DatabaseSelection> {
let {
usePrisma,
}: {
usePrisma?: boolean
} = await prompts({
type: 'confirm',
name: 'usePrisma',
message: 'Do you want to use a database? (https://prisma.io)',
})
if (usePrisma === undefined) {
return 'sigtermed'
}
if (usePrisma === false) {
return null
}
// TODO the supported databases should come from the plugin driver...
let { database }: { database?: Database } = await prompts({
type: 'select',
name: 'database',
message: 'Choose a database',
choices: [
{
title: 'PostgreSQL',
description: 'Requires running a PostgreSQL database',
value: 'PostgreSQL',
},
{
title: 'SQLite',
description: 'No operational overhead',
value: 'SQLite',
},
{
title: 'MySQL',
description: 'Requires running a MySQL database',
value: 'MySQL',
},
] as any, // Typings are missing the 'description' property...
initial: 0,
})
if (database === undefined) {
return 'sigtermed'
}
if (database === 'SQLite') {
return {
database: true,
choice: 'SQLite',
connectionURI: SQLITE_DEFAULT_CONNECTION_URI,
}
}
return { database: true, choice: database, connectionURI: undefined }
}
/**
* Ask the user if they would like to use npm or yarn.
* TODO if we detect that yarn is installed on the user's machine then we should
* default to that, otherwise default to npm.
*/
async function askForPackageManager(): Promise<PackageManager.PackageManagerType | 'sigtermed'> {
const choices: {
title: string
value: PackageManager.PackageManagerType
}[] = [
{ title: 'yarn', value: 'yarn' },
{ title: 'npm', value: 'npm' },
]
type Result = {
packageManagerType?: PackageManager.PackageManagerType
}
const result: Result = await prompts({
name: 'packageManagerType',
type: 'select',
message: 'What is your preferred package manager?',
choices,
})
if (result.packageManagerType === undefined) {
return 'sigtermed'
}
return result.packageManagerType
}
/**
* Check that the cwd is a suitable place to start a new nexus project.
*/
async function assertIsCleanSlate() {
log.trace('checking folder is in a clean state')
const contents = await fs.listAsync()
if (contents !== undefined && contents.length > 0) {
proc.fatal('Cannot create a new nexus project here because the directory is not empty', {
contents,
})
}
}
async function scaffoldTemplate(template: Template) {
return Promise.all(
template.files.map(({ path, content }) => {
return fs.writeAsync(path, content)
})
)
}
interface TemplateCreator {
(internalConfig: InternalConfig): Template
}
interface Template {
files: { path: string; content: string }[]
}
type TemplateName = 'helloWorld' | 'prisma'
const templates: Record<TemplateName, TemplateCreator> = {
helloWorld(internalConfig) {
return {
files: [
{
path: Path.join(internalConfig.sourceRoot, 'graphql.ts'),
content: stripIndent`
import { schema } from "nexus";
schema.addToContext(req => {
return {
memoryDB: {
worlds: [
{ id: "1", population: 6_000_000, name: "Earth" },
{ id: "2", population: 0, name: "Mars" }
]
}
}
})
schema.objectType({
name: "World",
definition(t) {
t.id("id")
t.string("name")
t.float("population")
}
})
schema.queryType({
definition(t) {
t.field("hello", {
type: "World",
args: {
world: schema.stringArg({ required: false })
},
resolve(_root, args, ctx) {
const worldToFindByName = args.world ?? "Earth"
const world = ctx.memoryDB.worlds.find(w => w.name === worldToFindByName)
if (!world) throw new Error(\`No such world named "\${args.world}"\`)
return world
}
})
t.list.field('worlds', {
type: 'World',
resolve(_root, _args, ctx) {
return ctx.memoryDB.worlds
}
})
}
})
`,
},
],
}
},
prisma(internalConfig) {
return {
files: [
{
path: Path.join(internalConfig.sourceRoot, 'app.ts'),
content: stripIndent`
import { use } from 'nexus'
import { prisma } from 'nexus-plugin-prisma'
use(prisma())
`,
},
],
}
},
}
/**
* Scaffold a new nexus project from scratch
*/
async function scaffoldBaseFiles(options: InternalConfig) {
const appEntrypointPath = Path.join(options.sourceRoot, 'app.ts')
const sourceRootRelative = Path.relative(options.projectRoot, options.sourceRoot)
await Promise.all([
// Empty app and graphql module.
// Having at least one of these satisfies minimum Nexus requirements.
// We put both to setup vscode debugger config with an entrypoint that is
// unlikely to change.
fs.writeAsync(
appEntrypointPath,
stripIndent`
/**
* This file is your server entrypoint. Don't worry about its emptyness, Nexus handles everything for you.
* However, if you need to add settings, enable plugins, schema middleware etc, this is place to do it.
* Below are some examples of what you can do. Uncomment them to try them out!
*/
/**
* Change a variety of settings
*/
// import { settings } from 'nexus'
//
// settings.change({
// server: {
// port: 4001
// }
// })
/**
* Add some schema middleware
*/
// import { schema } from 'nexus'
//
// schema.middleware((_config) => {
// return async (root, args, ctx, info, next) {
// ctx.log.trace('before resolver')
// await next(root, args, ctx, info)
// ctx.log.trace('after resolver')
// }
// })
/**
* Enable the Prisma plugin. (Needs \`nexus-plugin-prisma\` installed)
*/
// import { use } from 'nexus'
// import { prisma } from 'nexus-plugin-prisma'
//
// use(prisma())
`
),
fs.writeAsync(Path.join(options.sourceRoot, 'graphql.ts'), ''),
// An exhaustive .gitignore tailored for Node can be found here:
// https://github.com/github/gitignore/blob/master/Node.gitignore
// We intentionally stay minimal here, as we want the default ignore file
// to be as meaningful for nexus users as possible.
fs.writeAsync(
'.gitignore',
stripIndent`
# Node
node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
`
),
fs.writeAsync(Path.join(options.projectRoot, 'package.json'), {
name: options.projectName,
license: 'UNLICENSED',
version: '0.0.0',
dependencies: {},
scripts: {
format: "npx prettier --write './**/*.{ts,md}'",
dev: 'nexus dev',
build: 'nexus build',
start: `node .nexus/build/${sourceRootRelative}`,
},
prettier: {
semi: false,
singleQuote: true,
trailingComma: 'all',
},
} as PackageJson),
// todo should be supplied by the plugins
fs.writeAsync('.prettierignore', './prisma/**/*.md'),
fs.writeAsync(
'tsconfig.json',
tsconfigTemplate({
sourceRootRelative,
outRootRelative: Layout.DEFAULT_BUILD_DIR_PATH_RELATIVE_TO_PROJECT_ROOT,
})
),
fs.writeAsync(
'.vscode/launch.json',
stripIndent`
{
// Note: You can delete this file if you're not using vscode
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Nexus App",
"protocol": "inspector",
"runtimeExecutable": "\${workspaceRoot}/node_modules/.bin/nexus",
"runtimeArgs": ["dev"],
"args": ["${Path.relative(options.projectRoot, appEntrypointPath)}"],
"sourceMaps": true,
"console": "integratedTerminal"
}
]
}
`
),
])
}
const ENV_PARENT_DATA = 'NEXUS_CREATE_DATA'
type ParentData = {
database?: PluginRuntime.OnAfterBaseSetupLens['database']
connectionURI?: PluginRuntime.OnAfterBaseSetupLens['connectionURI']
}
async function loadDataFromParentProcess(): Promise<ParentData> {
if (process.env[ENV_PARENT_DATA]) {
const data = JSON.parse(process.env[ENV_PARENT_DATA]!)
log.trace('loaded parent data', { data })
return data
}
log.trace('no parent data found to load')
return {}
}
function saveDataForChildProcess(data: ParentData): void {
process.env[ENV_PARENT_DATA] = JSON.stringify(data)
}
/**
* Helper function for fetching the correct version of prisma plugin to
* install. Useful for development where we can override the version installed
* by environment variable NEXUS_PLUGIN_PRISMA_VERSION.
*/
function getPrismaPluginVersion(): string {
let prismaPluginVersion: string
if (process.env.NEXUS_PLUGIN_PRISMA_VERSION) {
log.warn(
'found NEXUS_PLUGIN_PRISMA_VERSION defined. This is only expected if you are actively developing on nexus right now',
{
NEXUS_PLUGIN_PRISMA_VERSION: process.env.NEXUS_PLUGIN_PRISMA_VERSION,
}
)
prismaPluginVersion = process.env.NEXUS_PLUGIN_PRISMA_VERSION
} else {
prismaPluginVersion = 'latest'
}
return prismaPluginVersion
} | the_stack |
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import Markdown from './Markdown';
const stories = storiesOf('src/components/Markdown', module);
stories.add('Basic HTML', () => <Markdown html={basicHTML} />);
stories.add('With Inline Code (with links too)', () => (
<Markdown html={withInlineCode} />
));
stories.add('With Basic List', () => <Markdown html={withBasicList} />);
stories.add('With Nested List', () => <Markdown html={withNestedList} />);
stories.add('With Quote', () => <Markdown html={withQuote} />);
stories.add('With Code Block', () => <Markdown html={withCodeBlock} />);
stories.add('With Plain Block', () => <Markdown html={withPlainBlock} />);
stories.add('With iFrame', () => <Markdown html={withIFrame} />);
stories.add('With Table', () => <Markdown html={withTable} />);
// From post 'The technology side of Agile'
const basicHTML = `
<h2 id="a-solid-foundation" style="position:relative;"><a href="#a-solid-foundation" aria-label="a solid foundation permalink" class="anchor before"><svg aria-hidden="true" focusable="false" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>A solid foundation</h2>
<p>Get creative! You’ll be surprised how much these low-level features change behavior. If you can roll out a mostly-complete feature for just a few customers with an easy avenue for feedback, iteration will just happen naturally! It won’t feel like <a href="http://www.thefreedictionary.com/bushwhacking">bushwhacking</a> to iterate - it will be the main trail!</p>
<p>It’s important to think holistically about <em>Agile</em> - sprints can feel pointless if your releases don’t actually go out the door afterwards. This infrastructure might even make your sprints seem too long!</p>
<hr>
<p>Now you’re ready for my next post in the series: <a href="/an-agile-organization/">An <em>Agile</em> organization</a>. It’s easy to be <em>Agile</em> within technical teams, but how to handle other parts of the organization still asking for specific features on specific dates?</p>
`;
// From post 'The dangerous cliffs of Node.js'
const withInlineCode = `
<ul>
<li>Prefer streams. <a href="http://nodejs.org/api/stream.html"><code>streams</code></a> are the way to handle large amounts of data without taking down the process. Put the time in to <a href="http://www.sitepoint.com/basics-node-js-streams/">learn how to</a> <a href="https://github.com/substack/stream-handbook">use them effectively</a>.</li>
<li>If you must get all the data up front, be sure that you include some kind of <strong>limit</strong> clause, and check any user-provided bounds input.</li>
<li>Monitor your request response times. <a href="http://newrelic.com/nodejs">New Relic</a> plugs into Express automatically, or you can use <a href="https://github.com/expressjs/morgan"><code>morgan</code></a> support for response times. The <code>good-console</code> plugin for <code>hapi</code> includes response times by default. Because one too-long synchronous code block will delay everything else, you’ll see very clear patterns in the data.</li>
</ul>
`;
// From post '12 things I learned from Microsoft'
const withBasicList = `
<h3 id="1-it-takes-a-lot-to-get-software-to-your-customers" style="position:relative;"><a href="#1-it-takes-a-lot-to-get-software-to-your-customers" aria-label="1 it takes a lot to get software to your customers permalink" class="anchor before"><svg aria-hidden="true" focusable="false" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>1. It takes a lot to get software to your customers</h3>
<p>When I worked at Hewlett-Packard and Terran Interactive in college, I just wrote code. I wasn’t exposed to all that it took to get that code onto users’ machines. In my first months as a Program Manager in Microsoft’s DevDiv, working on Visual Studio’s Debugger, I finally saw everything surrounding that core functionality:</p>
<ul>
<li>A wide range of testing: unit testing, integration testing, internal use (“dogfooding”), performance and stress testing, security “fuzzing,” etc.</li>
<li>Techniques to figure out if features addressed customer needs: usability studies, beta cycles and previews, design reviews.</li>
<li>Code quality metrics: cyclomatic complexity, code coverage, static analysis.</li>
<li>Support features: installers, localization, accessibility, the ability to ship patches, etc.</li>
</ul>
<h3 id="2-specs-should-have-expiration-dates" style="position:relative;"><a href="#2-specs-should-have-expiration-dates" aria-label="2 specs should have expiration dates permalink" class="anchor before"><svg aria-hidden="true" focusable="false" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>2. Specs should have expiration dates</h3>
`;
// From post 'Getting started with Elixir'
const withNestedList = `
<p><em>Resources:</em></p>
<ul>
<li>The excellent Elixir getting started tutorial: <a href="http://elixir-lang.org/getting-started/introduction.html">http://elixir-lang.org/getting-started/introduction.html</a></li>
<li>
<p>Elixir APIs:</p>
<ul>
<li>Docs: <a href="https://hexdocs.pm/elixir">https://hexdocs.pm/elixir</a></li>
<li>Source: <a href="https://github.com/elixir-lang/elixir/tree/master/lib/elixir/lib">https://github.com/elixir-lang/elixir/tree/master/lib/elixir/lib</a></li>
</ul>
</li>
<li>
<p>Erlang APIs:</p>
<ul>
<li>Docs: <a href="http://erlang.org/doc/apps/kernel/index.html">http://erlang.org/doc/apps/kernel/index.html</a></li>
<li>Source: <a href="https://github.com/erlang/otp/tree/master/lib/kernel/src">https://github.com/erlang/otp/tree/master/lib/kernel/src</a></li>
</ul>
</li>
<li><code>GenServer</code> and <code>Supervisor</code> cheat sheets: <a href="https://github.com/benjamintanweihao/elixir-cheatsheets">https://github.com/benjamintanweihao/elixir-cheatsheets</a></li>
<li>
<p>Related tools:</p>
<ul>
<li>Mix task runner: <a href="https://hexdocs.pm/mix/">https://hexdocs.pm/mix/</a></li>
<li>Hex package registry: <a href="https://hex.pm/">https://hex.pm/</a></li>
<li>ExUnit test runner: <a href="https://hexdocs.pm/ex_unit/">https://hexdocs.pm/ex_unit/</a></li>
<li>ExDoc documentation generator: <a href="https://github.com/elixir-lang/ex_doc">https://github.com/elixir-lang/ex_doc</a></li>
</ul>
</li>
<li>Huge list of Elixir/Erlang libraries: <a href="https://github.com/h4cc/awesome-elixir">https://github.com/h4cc/awesome-elixir</a></li>
<li>
<p>The high level:</p>
<ul>
<li>What’s the next big language? Javascript? Elixir? <a href="http://lebo.io/2015/03/02/steve-yegges-next-big-language-revisited.html">http://lebo.io/2015/03/02/steve-yegges-next-big-language-revisited.html</a></li>
<li>“I didn’t have this much fun programming on the server since I initially discovered django.” <a href="https://dvcrn.github.io/elixir/clojure/clojurescript/2016/01/22/sweet-sweet-elixir.html">https://dvcrn.github.io/elixir/clojure/clojurescript/2016/01/22/sweet-sweet-elixir.html</a></li>
<li>Comparing Elixir and Go <a href="https://blog.codeship.com/comparing-elixir-go/">https://blog.codeship.com/comparing-elixir-go/</a></li>
<li>Comparing Elixir and Clojure <a href="https://www.quora.com/Functional-Programming-Why-choose-Clojure-over-Elixir">https://www.quora.com/Functional-Programming-Why-choose-Clojure-over-Elixir</a></li>
<li>Using it in production, coming from Ruby: <a href="http://blog.carbonfive.com/2016/08/08/elixir-in-the-trenches/">http://blog.carbonfive.com/2016/08/08/elixir-in-the-trenches/</a></li>
</ul>
</li>
<li>
<p>Newsletters:</p>
<ul>
<li><a href="http://plataformatec.com.br/elixir-radar">http://plataformatec.com.br/elixir-radar</a></li>
<li><a href="https://elixirweekly.net/">https://elixirweekly.net/</a></li>
</ul>
</li>
</ul>
`;
// From post 'Starting on Signal'
const withQuote = `
<p>I’ve decided to put away my consultant hat for a while, because I’ve joined <a href="https://whispersystems.org/">Open Whisper Systems</a> to work on their <a href="https://en.wikipedia.org/wiki/Signal_(software)">Signal</a> <a href="https://whispersystems.org/blog/signal-desktop/">Desktop application</a>! I’m really excited to contribute to such an important mission.</p>
<blockquote>
<p><em>“I am regularly impressed with the thought and care put into both the security and the usability of this app. It’s my first choice for an encrypted conversation.”</em> - <a href="https://en.wikipedia.org/wiki/Bruce_Schneier">Bruce Schneier</a></p>
</blockquote>
<h2 id="what-is-signal" style="position:relative;"><a href="#what-is-signal" aria-label="what is signal permalink" class="anchor before"><svg aria-hidden="true" focusable="false" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>What is Signal?</h2>
`;
// From post 'What's a Monad? Digging into Haskell'
const withCodeBlock = `
<p>The functional concept of mapping an operation over the contents of something is now quite widely known thanks to libraries like <a href="https://lodash.com/">Lodash</a>. Lodash has the ability to map over JavaScript objects and arrays. A <code>Functor</code> is anything that can be mapped over with <code>fmap</code>. <code><$</code> is the simplest form of this, replacing all values inside the <code>Functor</code> with a single value:</p>
<pre><code class="hljs language-haskell"><span class="hljs-type">Prelude</span>> fmap (+ <span class="hljs-number">1</span>) (<span class="hljs-type">Just</span> <span class="hljs-number">4</span>)
<span class="hljs-type">Just</span> <span class="hljs-number">5</span>
<span class="hljs-type">Prelude</span>> <span class="hljs-number">5</span> <$ (<span class="hljs-type">Just</span> <span class="hljs-number">4</span>)
<span class="hljs-type">Just</span> <span class="hljs-number">5</span></code></pre>
<h3 id="2-applicative" style="position:relative;"><a href="#2-applicative" aria-label="2 applicative permalink" class="anchor before"><svg aria-hidden="true" focusable="false" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>2. <a href="https://en.wikibooks.org/wiki/Haskell/Applicative_functors">Applicative</a></h3>
`;
// From post 'Breaking the Node.js Event Loop'
const withPlainBlock = `<pre><code class="language-text">writeInterval: -
writeInterval: 141ms
getFile: start
getFile: done, 1ms
writeInterval: 104ms
writeInterval: 106ms
getFile: start
doSyncWork: start
doSyncWork: done
writeInterval: 1047ms
getFile: done, 1000ms
writeInterval: 102ms
writeInterval: 104ms
writeInterval: 104ms
writeInterval: 106ms
</code></pre>
`;
// From post 'Breaking the Node.js Event Loop'
const withIFrame = `
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/bMHB6zb9AXY?start=904"
frameborder="0"
allowfullscreen
></iframe>
`;
// From post 'ESLint Part 3: Analysis'
const withTable = `
<table>
<tbody><tr>
<td></td>
<td><a href="https://github.com/feross/eslint-config-standard">"Standard"</a></td>
<td><a href="https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb">AirBnB</a></td>
<td><a href="https://github.com/google/eslint-config-google">Google</a></td>
<td><a href="https://github.com/walmartlabs/eslint-config-defaults">defaults</a></td>
<td><a href="https://github.com/walmartlabs/eslint-config-defaults/blob/a464fed3c0d13e10b3c1f2f8a49298966658b325/configurations/walmart/es6-react.js">Walmart</a></td>
<td><a href="https://github.com/indentline/eslint-config-indent">indent</a></td>
</tr>
<tr>
<td><a href="https://github.com/scottnonnenberg/eslint-config-thehelp">thehelp</a></td>
<td>28%</td>
<td>42%</td>
<td>38%</td>
<td>10%</td>
<td>38%</td>
<td>72%</td>
</tr>
<tr>
<td>indent</td>
<td>29%</td>
<td>41%</td>
<td>43%</td>
<td>10%</td>
<td>38%</td>
<td>↵</td>
</tr>
<tr>
<td>Walmart</td>
<td>39%</td>
<td>39%</td>
<td>39%</td>
<td>21%</td>
<td>↵</td>
<td></td>
</tr>
<tr>
<td>defaults</td>
<td>22%</td>
<td>14%</td>
<td>17%</td>
<td>↵</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Google</td>
<td>52%</td>
<td>40%</td>
<td>↵</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>AirBnB</td>
<td>39%</td>
<td>↵</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
`; | the_stack |
const list = [
"#091E3A, #2F80ED, #2D9EE0",
"#9400D3, #4B0082",
"#c84e89, #F15F79",
"#00F5A0, #00D9F5",
"#F7941E, #72C6EF, #00A651",
"#F7941E, #004E8F",
"#72C6EF, #004E8F",
"#FD8112, #0085CA",
"#bf5ae0,#a811da",
"#00416A, #E4E5E6",
"#fbed96, #abecd6",
"#FFE000, #799F0C",
"#F7F8F8, #ACBB78",
"#00416A, #799F0C, #FFE000",
"#334d50, #cbcaa5",
"#0052D4, #4364F7, #6FB1FC",
"#5433FF, #20BDFF, #A5FECB",
"#799F0C, #ACBB78",
"#ffe259, #ffa751",
"#00416A, #E4E5E6",
"#FFE000, #799F0C",
"#acb6e5, #86fde8",
"#536976, #292E49",
"#BBD2C5, #536976, #292E49",
"#B79891, #94716B",
"#9796f0, #fbc7d4",
"#BBD2C5, #536976",
"#076585, #fff",
"#00467F, #A5CC82",
"#000C40, #607D8B",
"#1488CC, #2B32B2",
"#ec008c, #fc6767",
"#cc2b5e, #753a88",
"#2193b0, #6dd5ed",
"#e65c00, #F9D423",
"#2b5876, #4e4376",
"#314755, #26a0da",
"#77A1D3, #79CBCA, #E684AE",
"#ff6e7f, #bfe9ff",
"#e52d27, #b31217",
"#603813, #b29f94",
"#16A085, #F4D03F",
"#D31027, #EA384D",
"#EDE574, #E1F5C4",
"#02AAB0, #00CDAC",
"#DA22FF, #9733EE",
"#348F50, #56B4D3",
"#3CA55C, #B5AC49",
"#CC95C0, #DBD4B4, #7AA1D2",
"#003973, #E5E5BE",
"#E55D87, #5FC3E4",
"#403B4A, #E7E9BB",
"#F09819, #EDDE5D",
"#FF512F, #DD2476",
"#AA076B, #61045F",
"#1A2980, #26D0CE",
"#FF512F, #F09819",
"#1D2B64, #F8CDDA",
"#1FA2FF, #12D8FA, #A6FFCB",
"#4CB8C4, #3CD3AD",
"#DD5E89, #F7BB97",
// "#EB3349, #F45C43",
// "#1D976C, #93F9B9",
// "#FF8008, #FFC837",
// "#16222A, #3A6073",
// "#1F1C2C, #928DAB",
// "#614385, #516395",
// "#4776E6, #8E54E9",
// "#085078, #85D8CE",
// "#2BC0E4, #EAECC6",
// "#134E5E, #71B280",
// "#5C258D, #4389A2",
// "#757F9A, #D7DDE8",
// "#232526, #414345",
// "#1CD8D2, #93EDC7",
// "#3D7EAA, #FFE47A",
// "#283048, #859398",
// "#24C6DC, #514A9D",
// "#DC2424, #4A569D",
// "#ED4264, #FFEDBC",
// "#DAE2F8, #D6A4A4",
// "#ECE9E6, #FFFFFF",
// "#7474BF, #348AC7",
// "#EC6F66, #F3A183",
// "#5f2c82, #49a09d",
// "#C04848, #480048",
// "#e43a15, #e65245",
// "#414d0b, #727a17",
// "#FC354C, #0ABFBC",
// "#4b6cb7, #182848",
// "#f857a6, #ff5858",
// "#a73737, #7a2828",
// "#d53369, #cbad6d",
// "#e9d362, #333333",
// "#DE6262, #FFB88C",
// "#666600, #999966",
// "#FFEEEE, #DDEFBB",
// "#EFEFBB, #D4D3DD",
// "#c21500, #ffc500",
// "#215f00, #e4e4d9",
// "#50C9C3, #96DEDA",
// "#616161, #9bc5c3",
// "#ddd6f3, #faaca8",
// "#5D4157, #A8CABA",
// "#E6DADA, #274046",
// "#f2709c, #ff9472",
// "#DAD299, #B0DAB9",
// "#D3959B, #BFE6BA",
// "#00d2ff, #3a7bd5",
// "#870000, #190A05",
// "#B993D6, #8CA6DB",
// "#649173, #DBD5A4",
// "#C9FFBF, #FFAFBD",
// "#606c88, #3f4c6b",
// "#FBD3E9, #BB377D",
// "#ADD100, #7B920A",
// "#FF4E50, #F9D423",
// "#F0C27B, #4B1248",
// "#000000, #e74c3c",
// "#AAFFA9, #11FFBD",
// "#B3FFAB, #12FFF7",
// "#780206, #061161",
// "#9D50BB, #6E48AA",
// "#556270, #FF6B6B",
// "#70e1f5, #ffd194",
// "#00c6ff, #0072ff",
// "#fe8c00, #f83600",
// "#52c234, #061700",
// "#485563, #29323c",
// "#83a4d4, #b6fbff",
// "#FDFC47, #24FE41",
// "#abbaab, #ffffff",
// "#73C8A9, #373B44",
// "#D38312, #A83279",
// "#1e130c, #9a8478",
// "#948E99, #2E1437",
// "#360033, #0b8793",
// "#FFA17F, #00223E",
// "#43cea2, #185a9d",
// "#ffb347, #ffcc33",
// "#6441A5, #2a0845",
// "#FEAC5E, #C779D0, #4BC0C8",
// "#833ab4, #fd1d1d, #fcb045",
// "#ff0084, #33001b",
// "#00bf8f, #001510",
// "#136a8a, #267871",
// "#8e9eab, #eef2f3",
// "#7b4397, #dc2430",
// "#D1913C, #FFD194",
// "#F1F2B5, #135058",
// "#6A9113, #141517",
// "#004FF9, #FFF94C",
// "#525252, #3d72b4",
// "#BA8B02, #181818",
// "#ee9ca7, #ffdde1",
// "#304352, #d7d2cc",
// "#CCCCB2, #757519",
// "#2c3e50, #3498db",
// "#fc00ff, #00dbde",
// "#e53935, #e35d5b",
// "#005C97, #363795",
// "#f46b45, #eea849",
// "#00C9FF, #92FE9D",
// "#673AB7, #512DA8",
// "#76b852, #8DC26F",
// "#8E0E00, #1F1C18",
// "#FFB75E, #ED8F03",
// "#c2e59c, #64b3f4",
// "#403A3E, #BE5869",
// "#C02425, #F0CB35",
// "#B24592, #F15F79",
// "#457fca, #5691c8",
// "#6a3093, #a044ff",
// "#eacda3, #d6ae7b",
// "#fd746c, #ff9068",
// "#114357, #F29492",
// "#1e3c72, #2a5298",
// "#2F7336, #AA3A38",
// "#5614B0, #DBD65C",
// "#4DA0B0, #D39D38",
// "#5A3F37, #2C7744",
// "#2980b9, #2c3e50",
// "#0099F7, #F11712",
// "#834d9b, #d04ed6",
// "#4B79A1, #283E51",
// "#000000, #434343",
// "#4CA1AF, #C4E0E5",
// "#E0EAFC, #CFDEF3",
// "#BA5370, #F4E2D8",
// "#ff4b1f, #1fddff",
// "#f7ff00, #db36a4",
// "#a80077, #66ff00",
// "#1D4350, #A43931",
// "#EECDA3, #EF629F",
// "#16BFFD, #CB3066",
// "#ff4b1f, #ff9068",
// "#FF5F6D, #FFC371",
// "#2196f3, #f44336",
// "#00d2ff, #928DAB",
// "#3a7bd5, #3a6073",
// "#0B486B, #F56217",
// "#e96443, #904e95",
// "#2C3E50, #4CA1AF",
// "#2C3E50, #FD746C",
// "#F00000, #DC281E",
// "#141E30, #243B55",
// "#42275a, #734b6d",
// "#000428, #004e92",
// "#56ab2f, #a8e063",
// "#cb2d3e, #ef473a",
// "#f79d00, #64f38c",
// "#f85032, #e73827",
// "#fceabb, #f8b500",
// "#808080, #3fada8",
// "#ffd89b, #19547b",
// "#bdc3c7, #2c3e50",
// "#BE93C5, #7BC6CC",
// "#A1FFCE, #FAFFD1",
// "#4ECDC4, #556270",
// "#3a6186, #89253e",
// "#ef32d9, #89fffd",
// "#de6161, #2657eb",
// "#ff00cc, #333399",
// "#fffc00, #ffffff",
// "#ff7e5f, #feb47b",
// "#00c3ff, #ffff1c",
// "#f4c4f3, #fc67fa",
// "#41295a, #2F0743",
// "#A770EF, #CF8BF3, #FDB99B",
// "#ee0979, #ff6a00",
// "#F3904F, #3B4371",
// "#67B26F, #4ca2cd",
// "#3494E6, #EC6EAD",
// "#DBE6F6, #C5796D",
// "#9CECFB, #65C7F7, #0052D4",
// "#c0c0aa, #1cefff",
// "#DCE35B, #45B649",
// "#E8CBC0, #636FA4",
// "#F0F2F0, #000C40",
// "#FFAFBD, #ffc3a0",
// "#43C6AC, #F8FFAE",
// "#093028, #237A57",
// "#43C6AC, #191654",
// "#4568DC, #B06AB3",
// "#0575E6, #021B79",
// "#200122, #6f0000",
// "#44A08D, #093637",
// "#6190E8, #A7BFE8",
// "#34e89e, #0f3443",
// "#F7971E, #FFD200",
// "#C33764, #1D2671",
// "#20002c, #cbb4d4",
// "#D66D75, #E29587",
// "#30E8BF, #FF8235",
// "#B2FEFA, #0ED2F7",
// "#4AC29A, #BDFFF3",
// "#E44D26, #F16529",
// "#EB5757, #000000",
// "#F2994A, #F2C94C",
// "#56CCF2, #2F80ED",
// "#007991, #78ffd6",
// "#000046, #1CB5E0",
// "#159957, #155799",
// "#c0392b, #8e44ad",
// "#EF3B36, #FFFFFF",
// "#283c86, #45a247",
// "#3A1C71, #D76D77, #FFAF7B",
// "#CB356B, #BD3F32",
// "#36D1DC, #5B86E5",
// "#000000, #0f9b0f",
// "#1c92d2, #f2fcfe",
// "#642B73, #C6426E",
// "#06beb6, #48b1bf",
// "#0cebeb, #20e3b2, #29ffc6",
// "#d9a7c7, #fffcdc",
// "#396afc, #2948ff",
// "#C9D6FF, #E2E2E2",
// "#7F00FF, #E100FF",
// "#ff9966, #ff5e62",
// "#22c1c3, #fdbb2d",
// "#1a2a6c, #b21f1f, #fdbb2d",
// "#e1eec3, #f05053",
// "#ADA996, #F2F2F2, #DBDBDB, #EAEAEA",
// "#667db6, #0082c8, #0082c8, #667db6",
// "#03001e, #7303c0, #ec38bc, #fdeff9",
// "#6D6027, #D3CBB8",
// "#74ebd5,#ACB6E5",
// "#fc4a1a, #f7b733",
// "#00F260, #0575E6",
// "#800080, #ffc0cb",
// "#CAC531, #F3F9A7",
// "#3C3B3F, #605C3C",
// "#D3CCE3, #E9E4F0",
// "#00b09b, #96c93d",
// "#0f0c29, #302b63, #24243e",
// "#fffbd5, #b20a2c",
// "#23074d, #cc5333",
// "#c94b4b, #4b134f",
// "#FC466B, #3F5EFB",
// "#FC5C7D, #6A82FB",
// "#108dc7, #ef8e38",
// "#11998e, #38ef7d",
// "#3E5151, #DECBA4",
// "#40E0D0, #FF8C00, #FF0080",
// "#bc4e9c, #f80759",
// "#355C7D, #6C5B7B, #C06C84",
// "#4e54c8, #8f94fb",
// "#333333, #dd1818",
// "#a8c0ff, #3f2b96",
// "#ad5389, #3c1053",
// "#636363, #a2ab58",
// "#DA4453, #89216B",
// "#005AA7, #FFFDE4",
// "#59C173, #a17fe0, #5D26C1",
// "#FFEFBA, #FFFFFF",
// "#00B4DB, #0083B0",
// "#FDC830, #F37335",
// "#ED213A, #93291E",
// "#1E9600, #FFF200, #FF0000",
// "#a8ff78, #78ffd6",
// "#8A2387, #E94057, #F27121",
// "#FF416C, #FF4B2B",
// "#654ea3, #eaafc8",
// "#009FFF, #ec2F4B",
// "#544a7d, #ffd452",
// "#8360c3, #2ebf91",
// "#dd3e54, #6be585",
// "#659999, #f4791f",
// "#f12711, #f5af19",
// "#c31432, #240b36",
// "#7F7FD5, #86A8E7, #91EAE4",
// "#f953c6, #b91d73",
// "#1f4037, #99f2c8",
// "#8E2DE2, #4A00E0",
// "#aa4b6b, #6b6b83 , #3b8d99",
// "#FF0099, #493240",
// "#2980B9, #6DD5FA, #FFFFFF",
// "#373B44, #4286f4",
// "#b92b27, #1565C0",
// "#12c2e9, #c471ed, #f64f59",
// "#0F2027, #203A43, #2C5364",
// "#C6FFDD, #FBD786, #f7797d",
// "#2193b0, #6dd5ed",
// "#ee9ca7, #ffdde1",
// "#bdc3c7,#2c3e50",
// "#F36222, #5CB644, #007FC3",
// "#2A2D3E,#FECB6E",
// "#8a2be2,#0000cd,#228b22,#ccff00",
// "#051937,#004d7a,#008793,#00bf72,#a8eb12",
// "#6025F5,#FF5555",
// "#8a2be2,#ffa500,#f8f8ff",
// "#2774ae, #002E5D, #002E5D",
// "#004680,#4484BA",
// "#7ec6bc,#ebe717",
// "#ff1e56, #f9c942, #1e90ff",
// "#de8a41,#2ada53",
// "#f7f0ac,#acf7f0,#f0acf7",
// "#ff0000, #fdcf58",
// "#36B1C7, #960B33",
// "#1DA1F2, #009ffc",
// "#6da6be, #4b859e, #6da6be",
// "#B5B9FF, #2B2C49",
// "#9FA0A8, #5C7852",
// "#DCFFBD, #CC86D1",
// "#8BDEDA, #43ADD0, #998EE0, #E17DC2, #EF9393",
// "#E6AE8C, #A8CECF",
// "#00fff0,#0083fe",
// "#333333, #a2ab58, #A43931",
// "#0c0c6d, #de512b, #98d0c1, #5bb226, #023c0d",
// "#05386b,#5cdb95",
// "#4284DB, #29EAC4",
// "#554023, #c99846",
// "#516b8b, #056b3b",
// "#D70652, #FF025E",
// "#152331, #000000",
// "#f7f7f7, #b9a0a0, #794747, #4e2020, #111111",
// "#59CDE9, #0A2A88",
// "#EB0000,#95008A,#3300FC",
// "#ff75c3, #ffa647, #ffe83f, #9fff5b, #70e2ff, #cd93ff",
// "#81ff8a, #64965e",
// "#d4fc79, #96e6a1",
// "#003d4d, #00c996",
];
export const randomBackgroundGradient = (str: string | null | undefined) => {
let index = 0;
if (str == null || str.length === 0) return list[0];
for (let i = 0; i < str.length; i += 1) {
// eslint-disable-next-line no-bitwise
index = str.charCodeAt(i) + ((index << 5) - index);
// eslint-disable-next-line no-bitwise
index &= index;
}
index = ((index % list.length) + list.length) % list.length;
return `linear-gradient(to bottom, ${list[index]})`;
}; | the_stack |
import type { u64 } from "@saberhq/token-utils";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import type { Fees, RawFees } from "../state";
import { encodeFees, ZERO_FEES } from "../state";
import type { StableSwapConfig } from "./common";
import { buildInstruction } from "./common";
import {
DepositIXLayout,
InitializeSwapIXLayout,
SwapIXLayout,
WithdrawIXLayout,
WithdrawOneIXLayout,
} from "./layouts";
/**
* Instruction enum.
*/
export enum StableSwapInstruction {
INITIALIZE = 0,
SWAP = 1,
DEPOSIT = 2,
WITHDRAW = 3,
WITHDRAW_ONE = 4,
}
/**
* Info about the tokens to swap.
*/
export interface SwapTokenInfo {
/**
* The account that admin fees go to.
*/
adminFeeAccount: PublicKey;
/**
* Mint of the token.
*/
mint: PublicKey;
/**
* This swap's token reserves.
*/
reserve: PublicKey;
}
export interface InitializeSwapInstruction {
config: StableSwapConfig;
/**
* Account that can manage the swap.
*/
adminAccount: PublicKey;
tokenA: SwapTokenInfo;
tokenB: SwapTokenInfo;
poolTokenMint: PublicKey;
/**
* Destination account for the initial LP tokens.
*/
destinationPoolTokenAccount: PublicKey;
nonce: number;
ampFactor: u64;
fees?: Fees;
isPaused?: boolean;
}
export interface SwapInstruction {
config: StableSwapConfig;
/**
* User source authority
*/
userAuthority: PublicKey;
/**
* User source token account
*/
userSource: PublicKey;
/**
* Swap source token account
*/
poolSource: PublicKey;
/**
* Swap destination token account
*/
poolDestination: PublicKey;
/**
* User destination token account
*/
userDestination: PublicKey;
adminDestination: PublicKey;
amountIn: u64;
minimumAmountOut: u64;
}
export interface DepositInstruction {
config: StableSwapConfig;
/**
* Authority for user account
*/
userAuthority: PublicKey;
/**
* Depositor account for token A
*/
sourceA: PublicKey;
/**
* Depositor account for token B
*/
sourceB: PublicKey;
tokenAccountA: PublicKey;
tokenAccountB: PublicKey;
poolTokenMint: PublicKey;
poolTokenAccount: PublicKey;
tokenAmountA: u64;
tokenAmountB: u64;
minimumPoolTokenAmount: u64;
}
export interface WithdrawInstruction {
config: StableSwapConfig;
/**
* User source authority
*/
userAuthority: PublicKey;
poolMint: PublicKey;
tokenAccountA: PublicKey;
tokenAccountB: PublicKey;
adminFeeAccountA: PublicKey;
adminFeeAccountB: PublicKey;
/**
* Account which is the source of the pool tokens
* that is; the user's pool token account
*/
sourceAccount: PublicKey;
userAccountA: PublicKey;
userAccountB: PublicKey;
poolTokenAmount: u64;
minimumTokenA: u64;
minimumTokenB: u64;
}
export interface WithdrawOneInstruction {
config: StableSwapConfig;
/**
* User source authority
*/
userAuthority: PublicKey;
poolMint: PublicKey;
/**
* User account that holds the LP tokens
*/
sourceAccount: PublicKey;
/**
* Pool account that holds the tokens to withdraw
*/
baseTokenAccount: PublicKey;
/**
* Pool account that holds the other token
*/
quoteTokenAccount: PublicKey;
/**
* User base token account to withdraw to
*/
destinationAccount: PublicKey;
/**
* Admin base token account to send fees to
*/
adminDestinationAccount: PublicKey;
/**
* Amount of pool tokens to burn. User receives an output of token a
* or b based on the percentage of the pool tokens that are returned.
*/
poolTokenAmount: u64;
/**
* Minimum amount of base tokens to receive, prevents excessive slippage
*/
minimumTokenAmount: u64;
}
export const initializeSwapInstructionRaw = ({
config,
adminAccount,
tokenA: {
adminFeeAccount: adminFeeAccountA,
mint: tokenMintA,
reserve: tokenAccountA,
},
tokenB: {
adminFeeAccount: adminFeeAccountB,
mint: tokenMintB,
reserve: tokenAccountB,
},
poolTokenMint,
destinationPoolTokenAccount,
nonce,
ampFactor,
fees,
}: Omit<InitializeSwapInstruction, "fees"> & {
fees: RawFees;
}): TransactionInstruction => {
const keys = [
{ pubkey: config.swapAccount, isSigner: false, isWritable: false },
{ pubkey: config.authority, isSigner: false, isWritable: false },
{ pubkey: adminAccount, isSigner: false, isWritable: false },
{ pubkey: adminFeeAccountA, isSigner: false, isWritable: false },
{ pubkey: adminFeeAccountB, isSigner: false, isWritable: false },
{ pubkey: tokenMintA, isSigner: false, isWritable: false },
{ pubkey: tokenAccountA, isSigner: false, isWritable: false },
{ pubkey: tokenMintB, isSigner: false, isWritable: false },
{ pubkey: tokenAccountB, isSigner: false, isWritable: false },
{ pubkey: poolTokenMint, isSigner: false, isWritable: true },
{ pubkey: destinationPoolTokenAccount, isSigner: false, isWritable: true },
{ pubkey: config.tokenProgramID, isSigner: false, isWritable: false },
];
const data = Buffer.alloc(InitializeSwapIXLayout.span);
InitializeSwapIXLayout.encode(
{
instruction: StableSwapInstruction.INITIALIZE, // InitializeSwap instruction
nonce,
ampFactor: ampFactor.toBuffer(),
fees,
},
data
);
return buildInstruction({
config,
keys,
data,
});
};
export const initializeSwapInstruction = ({
fees = ZERO_FEES,
...args
}: InitializeSwapInstruction): TransactionInstruction => {
return initializeSwapInstructionRaw({ ...args, fees: encodeFees(fees) });
};
export const swapInstruction = ({
config,
userAuthority,
userSource,
poolSource,
poolDestination,
userDestination,
adminDestination,
amountIn,
minimumAmountOut,
}: SwapInstruction): TransactionInstruction => {
const data = Buffer.alloc(SwapIXLayout.span);
SwapIXLayout.encode(
{
instruction: StableSwapInstruction.SWAP, // Swap instruction
amountIn: amountIn.toBuffer(),
minimumAmountOut: minimumAmountOut.toBuffer(),
},
data
);
const keys = [
{ pubkey: config.swapAccount, isSigner: false, isWritable: false },
{ pubkey: config.authority, isSigner: false, isWritable: false },
{ pubkey: userAuthority, isSigner: true, isWritable: false },
{ pubkey: userSource, isSigner: false, isWritable: true },
{ pubkey: poolSource, isSigner: false, isWritable: true },
{ pubkey: poolDestination, isSigner: false, isWritable: true },
{ pubkey: userDestination, isSigner: false, isWritable: true },
{ pubkey: adminDestination, isSigner: false, isWritable: true },
{ pubkey: config.tokenProgramID, isSigner: false, isWritable: false },
];
return buildInstruction({
config,
keys,
data,
});
};
export const depositInstruction = ({
config,
userAuthority,
sourceA,
sourceB,
tokenAccountA,
tokenAccountB,
poolTokenMint,
poolTokenAccount,
tokenAmountA,
tokenAmountB,
minimumPoolTokenAmount,
}: DepositInstruction): TransactionInstruction => {
const data = Buffer.alloc(DepositIXLayout.span);
DepositIXLayout.encode(
{
instruction: StableSwapInstruction.DEPOSIT, // Deposit instruction
tokenAmountA: tokenAmountA.toBuffer(),
tokenAmountB: tokenAmountB.toBuffer(),
minimumPoolTokenAmount: minimumPoolTokenAmount.toBuffer(),
},
data
);
const keys = [
{ pubkey: config.swapAccount, isSigner: false, isWritable: false },
{ pubkey: config.authority, isSigner: false, isWritable: false },
{ pubkey: userAuthority, isSigner: true, isWritable: false },
{ pubkey: sourceA, isSigner: false, isWritable: true },
{ pubkey: sourceB, isSigner: false, isWritable: true },
{ pubkey: tokenAccountA, isSigner: false, isWritable: true },
{ pubkey: tokenAccountB, isSigner: false, isWritable: true },
{ pubkey: poolTokenMint, isSigner: false, isWritable: true },
{ pubkey: poolTokenAccount, isSigner: false, isWritable: true },
{ pubkey: config.tokenProgramID, isSigner: false, isWritable: false },
];
return buildInstruction({
config,
keys,
data,
});
};
export const withdrawInstruction = ({
config,
userAuthority,
poolMint,
sourceAccount,
tokenAccountA,
tokenAccountB,
userAccountA,
userAccountB,
adminFeeAccountA,
adminFeeAccountB,
poolTokenAmount,
minimumTokenA,
minimumTokenB,
}: WithdrawInstruction): TransactionInstruction => {
const data = Buffer.alloc(WithdrawIXLayout.span);
WithdrawIXLayout.encode(
{
instruction: StableSwapInstruction.WITHDRAW, // Withdraw instruction
poolTokenAmount: poolTokenAmount.toBuffer(),
minimumTokenA: minimumTokenA.toBuffer(),
minimumTokenB: minimumTokenB.toBuffer(),
},
data
);
const keys = [
{ pubkey: config.swapAccount, isSigner: false, isWritable: false },
{ pubkey: config.authority, isSigner: false, isWritable: false },
{ pubkey: userAuthority, isSigner: true, isWritable: false },
{ pubkey: poolMint, isSigner: false, isWritable: true },
{ pubkey: sourceAccount, isSigner: false, isWritable: true },
{ pubkey: tokenAccountA, isSigner: false, isWritable: true },
{ pubkey: tokenAccountB, isSigner: false, isWritable: true },
{ pubkey: userAccountA, isSigner: false, isWritable: true },
{ pubkey: userAccountB, isSigner: false, isWritable: true },
{ pubkey: adminFeeAccountA, isSigner: false, isWritable: true },
{ pubkey: adminFeeAccountB, isSigner: false, isWritable: true },
{ pubkey: config.tokenProgramID, isSigner: false, isWritable: false },
];
return buildInstruction({
config,
keys,
data,
});
};
export const withdrawOneInstruction = ({
config,
userAuthority,
poolMint,
sourceAccount,
baseTokenAccount,
quoteTokenAccount,
destinationAccount,
adminDestinationAccount,
poolTokenAmount,
minimumTokenAmount,
}: WithdrawOneInstruction): TransactionInstruction => {
const data = Buffer.alloc(WithdrawOneIXLayout.span);
WithdrawOneIXLayout.encode(
{
instruction: StableSwapInstruction.WITHDRAW_ONE, // Withdraw instruction
poolTokenAmount: poolTokenAmount.toBuffer(),
minimumTokenAmount: minimumTokenAmount.toBuffer(),
},
data
);
const keys = [
{ pubkey: config.swapAccount, isSigner: false, isWritable: false },
{ pubkey: config.authority, isSigner: false, isWritable: false },
{ pubkey: userAuthority, isSigner: true, isWritable: false },
{ pubkey: poolMint, isSigner: false, isWritable: true },
{ pubkey: sourceAccount, isSigner: false, isWritable: true },
{ pubkey: baseTokenAccount, isSigner: false, isWritable: true },
{ pubkey: quoteTokenAccount, isSigner: false, isWritable: true },
{ pubkey: destinationAccount, isSigner: false, isWritable: true },
{ pubkey: adminDestinationAccount, isSigner: false, isWritable: true },
{ pubkey: config.tokenProgramID, isSigner: false, isWritable: false },
];
return buildInstruction({
config,
keys,
data,
});
}; | the_stack |
'use strict';
import Char from 'typescript-char';
import { isBinary, isDecimal, isHex, isIdentifierChar, isIdentifierStartChar, isOctal } from './characters';
import { CharacterStream } from './characterStream';
import { TextRangeCollection } from './textRangeCollection';
import {
ICharacterStream,
ITextRangeCollection,
IToken,
ITokenizer,
TextRange,
TokenizerMode,
TokenType,
} from './types';
enum QuoteType {
None,
Single,
Double,
TripleSingle,
TripleDouble,
}
class Token extends TextRange implements IToken {
public readonly type: TokenType;
constructor(type: TokenType, start: number, length: number) {
super(start, length);
this.type = type;
}
}
export class Tokenizer implements ITokenizer {
private cs: ICharacterStream = new CharacterStream('');
private tokens: IToken[] = [];
private mode = TokenizerMode.Full;
public tokenize(text: string): ITextRangeCollection<IToken>;
public tokenize(text: string, start: number, length: number, mode: TokenizerMode): ITextRangeCollection<IToken>;
public tokenize(text: string, start?: number, length?: number, mode?: TokenizerMode): ITextRangeCollection<IToken> {
if (start === undefined) {
start = 0;
} else if (start < 0 || start >= text.length) {
throw new Error('Invalid range start');
}
if (length === undefined) {
length = text.length;
} else if (length < 0 || start + length > text.length) {
throw new Error('Invalid range length');
}
this.mode = mode !== undefined ? mode : TokenizerMode.Full;
this.cs = new CharacterStream(text);
this.cs.position = start;
const end = start + length;
while (!this.cs.isEndOfStream()) {
this.AddNextToken();
if (this.cs.position >= end) {
break;
}
}
return new TextRangeCollection(this.tokens);
}
private AddNextToken(): void {
this.cs.skipWhitespace();
if (this.cs.isEndOfStream()) {
return;
}
if (!this.handleCharacter()) {
this.cs.moveNext();
}
}
private handleCharacter(): boolean {
// f-strings, b-strings, etc
const stringPrefixLength = this.getStringPrefixLength();
if (stringPrefixLength >= 0) {
// Indeed a string
this.cs.advance(stringPrefixLength);
const quoteType = this.getQuoteType();
if (quoteType !== QuoteType.None) {
this.handleString(quoteType, stringPrefixLength);
return true;
}
}
if (this.cs.currentChar === Char.Hash) {
this.handleComment();
return true;
}
if (this.mode === TokenizerMode.CommentsAndStrings) {
return false;
}
switch (this.cs.currentChar) {
case Char.OpenParenthesis:
this.tokens.push(new Token(TokenType.OpenBrace, this.cs.position, 1));
break;
case Char.CloseParenthesis:
this.tokens.push(new Token(TokenType.CloseBrace, this.cs.position, 1));
break;
case Char.OpenBracket:
this.tokens.push(new Token(TokenType.OpenBracket, this.cs.position, 1));
break;
case Char.CloseBracket:
this.tokens.push(new Token(TokenType.CloseBracket, this.cs.position, 1));
break;
case Char.OpenBrace:
this.tokens.push(new Token(TokenType.OpenCurly, this.cs.position, 1));
break;
case Char.CloseBrace:
this.tokens.push(new Token(TokenType.CloseCurly, this.cs.position, 1));
break;
case Char.Comma:
this.tokens.push(new Token(TokenType.Comma, this.cs.position, 1));
break;
case Char.Semicolon:
this.tokens.push(new Token(TokenType.Semicolon, this.cs.position, 1));
break;
case Char.Colon:
this.tokens.push(new Token(TokenType.Colon, this.cs.position, 1));
break;
default:
if (this.isPossibleNumber()) {
if (this.tryNumber()) {
return true;
}
}
if (this.cs.currentChar === Char.Period) {
this.tokens.push(new Token(TokenType.Operator, this.cs.position, 1));
break;
}
if (!this.tryIdentifier()) {
if (!this.tryOperator()) {
this.handleUnknown();
}
}
return true;
}
return false;
}
private tryIdentifier(): boolean {
const start = this.cs.position;
if (isIdentifierStartChar(this.cs.currentChar)) {
this.cs.moveNext();
while (isIdentifierChar(this.cs.currentChar)) {
this.cs.moveNext();
}
}
if (this.cs.position > start) {
// const text = this.cs.getText().substr(start, this.cs.position - start);
// const type = this.keywords.find((value, index) => value === text) ? TokenType.Keyword : TokenType.Identifier;
this.tokens.push(new Token(TokenType.Identifier, start, this.cs.position - start));
return true;
}
return false;
}
private isPossibleNumber(): boolean {
if (isDecimal(this.cs.currentChar)) {
return true;
}
if (this.cs.currentChar === Char.Period && isDecimal(this.cs.nextChar)) {
return true;
}
const next = this.cs.currentChar === Char.Hyphen || this.cs.currentChar === Char.Plus ? 1 : 0;
// Next character must be decimal or a dot otherwise
// it is not a number. No whitespace is allowed.
if (isDecimal(this.cs.lookAhead(next)) || this.cs.lookAhead(next) === Char.Period) {
// Check what previous token is, if any
if (this.tokens.length === 0) {
// At the start of the file this can only be a number
return true;
}
const prev = this.tokens[this.tokens.length - 1];
if (
prev.type === TokenType.OpenBrace ||
prev.type === TokenType.OpenBracket ||
prev.type === TokenType.Comma ||
prev.type === TokenType.Colon ||
prev.type === TokenType.Semicolon ||
prev.type === TokenType.Operator
) {
return true;
}
}
if (this.cs.lookAhead(next) === Char._0) {
const nextNext = this.cs.lookAhead(next + 1);
if (nextNext === Char.x || nextNext === Char.X) {
return true;
}
if (nextNext === Char.b || nextNext === Char.B) {
return true;
}
if (nextNext === Char.o || nextNext === Char.O) {
return true;
}
}
return false;
}
private tryNumber(): boolean {
const start = this.cs.position;
let leadingSign = 0;
if (this.cs.currentChar === Char.Hyphen || this.cs.currentChar === Char.Plus) {
this.cs.moveNext(); // Skip leading +/-
leadingSign = 1;
}
if (this.cs.currentChar === Char._0) {
let radix = 0;
// Try hex => hexinteger: "0" ("x" | "X") (["_"] hexdigit)+
if ((this.cs.nextChar === Char.x || this.cs.nextChar === Char.X) && isHex(this.cs.lookAhead(2))) {
this.cs.advance(2);
while (isHex(this.cs.currentChar)) {
this.cs.moveNext();
}
radix = 16;
}
// Try binary => bininteger: "0" ("b" | "B") (["_"] bindigit)+
if ((this.cs.nextChar === Char.b || this.cs.nextChar === Char.B) && isBinary(this.cs.lookAhead(2))) {
this.cs.advance(2);
while (isBinary(this.cs.currentChar)) {
this.cs.moveNext();
}
radix = 2;
}
// Try octal => octinteger: "0" ("o" | "O") (["_"] octdigit)+
if ((this.cs.nextChar === Char.o || this.cs.nextChar === Char.O) && isOctal(this.cs.lookAhead(2))) {
this.cs.advance(2);
while (isOctal(this.cs.currentChar)) {
this.cs.moveNext();
}
radix = 8;
}
if (radix > 0) {
const text = this.cs.getText().substr(start + leadingSign, this.cs.position - start - leadingSign);
if (!isNaN(parseInt(text, radix))) {
this.tokens.push(new Token(TokenType.Number, start, text.length + leadingSign));
return true;
}
}
}
let decimal = false;
// Try decimal int =>
// decinteger: nonzerodigit (["_"] digit)* | "0" (["_"] "0")*
// nonzerodigit: "1"..."9"
// digit: "0"..."9"
if (this.cs.currentChar >= Char._1 && this.cs.currentChar <= Char._9) {
while (isDecimal(this.cs.currentChar)) {
this.cs.moveNext();
}
decimal =
this.cs.currentChar !== Char.Period && this.cs.currentChar !== Char.e && this.cs.currentChar !== Char.E;
}
if (this.cs.currentChar === Char._0) {
// "0" (["_"] "0")*
while (this.cs.currentChar === Char._0 || this.cs.currentChar === Char.Underscore) {
this.cs.moveNext();
}
decimal =
this.cs.currentChar !== Char.Period && this.cs.currentChar !== Char.e && this.cs.currentChar !== Char.E;
}
if (decimal) {
const text = this.cs.getText().substr(start + leadingSign, this.cs.position - start - leadingSign);
if (!isNaN(parseInt(text, 10))) {
this.tokens.push(new Token(TokenType.Number, start, text.length + leadingSign));
return true;
}
}
// Floating point. Sign was already skipped over.
if (
(this.cs.currentChar >= Char._0 && this.cs.currentChar <= Char._9) ||
(this.cs.currentChar === Char.Period && this.cs.nextChar >= Char._0 && this.cs.nextChar <= Char._9)
) {
if (this.skipFloatingPointCandidate(false)) {
const text = this.cs.getText().substr(start, this.cs.position - start);
if (!isNaN(parseFloat(text))) {
this.tokens.push(new Token(TokenType.Number, start, this.cs.position - start));
return true;
}
}
}
this.cs.position = start;
return false;
}
private tryOperator(): boolean {
let length = 0;
const nextChar = this.cs.nextChar;
switch (this.cs.currentChar) {
case Char.Plus:
case Char.Ampersand:
case Char.Bar:
case Char.Caret:
case Char.Equal:
case Char.ExclamationMark:
case Char.Percent:
case Char.Tilde:
length = nextChar === Char.Equal ? 2 : 1;
break;
case Char.Hyphen:
length = nextChar === Char.Equal || nextChar === Char.Greater ? 2 : 1;
break;
case Char.Asterisk:
if (nextChar === Char.Asterisk) {
length = this.cs.lookAhead(2) === Char.Equal ? 3 : 2;
} else {
length = nextChar === Char.Equal ? 2 : 1;
}
break;
case Char.Slash:
if (nextChar === Char.Slash) {
length = this.cs.lookAhead(2) === Char.Equal ? 3 : 2;
} else {
length = nextChar === Char.Equal ? 2 : 1;
}
break;
case Char.Less:
if (nextChar === Char.Greater) {
length = 2;
} else if (nextChar === Char.Less) {
length = this.cs.lookAhead(2) === Char.Equal ? 3 : 2;
} else {
length = nextChar === Char.Equal ? 2 : 1;
}
break;
case Char.Greater:
if (nextChar === Char.Greater) {
length = this.cs.lookAhead(2) === Char.Equal ? 3 : 2;
} else {
length = nextChar === Char.Equal ? 2 : 1;
}
break;
case Char.At:
length = nextChar === Char.Equal ? 2 : 1;
break;
default:
return false;
}
this.tokens.push(new Token(TokenType.Operator, this.cs.position, length));
this.cs.advance(length);
return length > 0;
}
private handleUnknown(): boolean {
const start = this.cs.position;
this.cs.skipToWhitespace();
const length = this.cs.position - start;
if (length > 0) {
this.tokens.push(new Token(TokenType.Unknown, start, length));
return true;
}
return false;
}
private handleComment(): void {
const start = this.cs.position;
this.cs.skipToEol();
this.tokens.push(new Token(TokenType.Comment, start, this.cs.position - start));
}
private getStringPrefixLength(): number {
if (this.cs.currentChar === Char.SingleQuote || this.cs.currentChar === Char.DoubleQuote) {
return 0; // Simple string, no prefix
}
if (this.cs.nextChar === Char.SingleQuote || this.cs.nextChar === Char.DoubleQuote) {
switch (this.cs.currentChar) {
case Char.f:
case Char.F:
case Char.r:
case Char.R:
case Char.b:
case Char.B:
case Char.u:
case Char.U:
return 1; // single-char prefix like u"" or r""
default:
break;
}
}
if (this.cs.lookAhead(2) === Char.SingleQuote || this.cs.lookAhead(2) === Char.DoubleQuote) {
const prefix = this.cs.getText().substr(this.cs.position, 2).toLowerCase();
switch (prefix) {
case 'rf':
case 'ur':
case 'br':
return 2;
default:
break;
}
}
return -1;
}
private getQuoteType(): QuoteType {
if (this.cs.currentChar === Char.SingleQuote) {
return this.cs.nextChar === Char.SingleQuote && this.cs.lookAhead(2) === Char.SingleQuote
? QuoteType.TripleSingle
: QuoteType.Single;
}
if (this.cs.currentChar === Char.DoubleQuote) {
return this.cs.nextChar === Char.DoubleQuote && this.cs.lookAhead(2) === Char.DoubleQuote
? QuoteType.TripleDouble
: QuoteType.Double;
}
return QuoteType.None;
}
private handleString(quoteType: QuoteType, stringPrefixLength: number): void {
const start = this.cs.position - stringPrefixLength;
if (quoteType === QuoteType.Single || quoteType === QuoteType.Double) {
this.cs.moveNext();
this.skipToSingleEndQuote(quoteType === QuoteType.Single ? Char.SingleQuote : Char.DoubleQuote);
} else {
this.cs.advance(3);
this.skipToTripleEndQuote(quoteType === QuoteType.TripleSingle ? Char.SingleQuote : Char.DoubleQuote);
}
this.tokens.push(new Token(TokenType.String, start, this.cs.position - start));
}
private skipToSingleEndQuote(quote: number): void {
while (!this.cs.isEndOfStream()) {
if (this.cs.currentChar === Char.LineFeed || this.cs.currentChar === Char.CarriageReturn) {
return; // Unterminated single-line string
}
if (this.cs.currentChar === Char.Backslash && this.cs.nextChar === quote) {
this.cs.advance(2);
continue;
}
if (this.cs.currentChar === quote) {
break;
}
this.cs.moveNext();
}
this.cs.moveNext();
}
private skipToTripleEndQuote(quote: number): void {
while (
!this.cs.isEndOfStream() &&
(this.cs.currentChar !== quote || this.cs.nextChar !== quote || this.cs.lookAhead(2) !== quote)
) {
this.cs.moveNext();
}
this.cs.advance(3);
}
private skipFloatingPointCandidate(allowSign: boolean): boolean {
// Determine end of the potential floating point number
const start = this.cs.position;
this.skipFractionalNumber(allowSign);
if (this.cs.position > start) {
if (this.cs.currentChar === Char.e || this.cs.currentChar === Char.E) {
this.cs.moveNext(); // Optional exponent sign
}
this.skipDecimalNumber(true); // skip exponent value
}
return this.cs.position > start;
}
private skipFractionalNumber(allowSign: boolean): void {
this.skipDecimalNumber(allowSign);
if (this.cs.currentChar === Char.Period) {
this.cs.moveNext(); // Optional period
}
this.skipDecimalNumber(false);
}
private skipDecimalNumber(allowSign: boolean): void {
if (allowSign && (this.cs.currentChar === Char.Hyphen || this.cs.currentChar === Char.Plus)) {
this.cs.moveNext(); // Optional sign
}
while (isDecimal(this.cs.currentChar)) {
this.cs.moveNext(); // skip integer part
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.