text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as assert from 'assert'; import { parse } from './../src/languageservice/parser/yamlParser07'; describe('YAML parser', () => { describe('YAML parser', function () { it('parse emtpy text', () => { const parsedDocument = parse(''); assert(parsedDocument.documents.length === 1, 'A document has been created for an empty text'); }); it('parse only comment', () => { const parsedDocument = parse('# a comment'); assert(parsedDocument.documents.length === 1, 'A document has been created when there is a comment'); }); it('parse single document with --- at the start of the file', () => { const parsedDocument = parse('---\n# a comment\ntest: test'); assert( parsedDocument.documents.length === 1, `A single document should be available but there are ${parsedDocument.documents.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); }); it('parse multi document with --- at the start of the file', () => { const parsedDocument = parse('---\n# a comment\ntest: test\n...\n---\n# second document\ntest2: test2'); assert( parsedDocument.documents.length === 2, `two documents should be available but there are ${parsedDocument.documents.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); assert(parsedDocument.documents[1].lineComments.length === 1); assert(parsedDocument.documents[1].lineComments[0] === '# second document'); }); it('parse single document with directives and line comments', () => { const parsedDocument = parse('%TAG !yaml! tag:yaml.org,2002:\n---\n# a comment\ntest'); assert( parsedDocument.documents.length === 1, `A single document should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); }); it('parse 2 documents with directives and line comments', () => { const parsedDocument = parse('%TAG !yaml! tag:yaml.org,2002:\n# a comment\ntest\n...\n---\ntest2'); assert( parsedDocument.documents.length === 2, `2 documents should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert( parsedDocument.documents[1].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[1].root.children.length}` ); assert(parsedDocument.documents[1].root.value === 'test2'); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); }); it('parse single document', () => { const parsedDocument = parse('test'); assert( parsedDocument.documents.length === 1, `A single document should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); }); it('parse single document with directives', () => { const parsedDocument = parse('%TAG !yaml! tag:yaml.org,2002:\n---\ntest'); assert( parsedDocument.documents.length === 1, `A single document should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); }); it('parse 2 documents', () => { const parsedDocument = parse('test\n---\ntest2'); assert( parsedDocument.documents.length === 2, `2 documents should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[0].root.value === 'test'); assert( parsedDocument.documents[1].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[1].root.children.length}` ); assert(parsedDocument.documents[1].root.value === 'test2'); }); it('parse 3 documents', () => { const parsedDocument = parse('test\n---\ntest2\n---\ntest3'); assert( parsedDocument.documents.length === 3, `3 documents should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[0].root.value === 'test'); assert( parsedDocument.documents[1].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[1].root.children.length}` ); assert(parsedDocument.documents[1].root.value === 'test2'); assert( parsedDocument.documents[2].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[2].root.children.length}` ); assert(parsedDocument.documents[2].root.value === 'test3'); }); it('parse single document with comment', () => { const parsedDocument = parse('# a comment\ntest'); assert( parsedDocument.documents.length === 1, `A single document should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); }); it('parse 2 documents with comment', () => { const parsedDocument = parse('---\n# a comment\ntest: test\n---\n# a second comment\ntest2'); assert( parsedDocument.documents.length === 2, `2 documents should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 1, `There should one children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); assert( parsedDocument.documents[1].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[1].lineComments.length === 1); assert(parsedDocument.documents[1].lineComments[0] === '# a second comment'); }); it('parse 2 documents with comment and a directive', () => { const parsedDocument = parse('%TAG !yaml! tag:yaml.org,2002:\n---\n# a comment\ntest\n---\n# a second comment\ntest2'); assert( parsedDocument.documents.length === 2, `2 documents should be available but there are ${parsedDocument.documents.length}` ); assert( parsedDocument.documents[0].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); assert( parsedDocument.documents[1].root.children.length === 0, `There should no children available but there are ${parsedDocument.documents[0].root.children.length}` ); assert(parsedDocument.documents[1].lineComments.length === 1); assert(parsedDocument.documents[1].lineComments[0] === '# a second comment'); }); it('parse document with comment first', () => { const parsedDocument = parse('# a comment\n---\ntest:test'); assert( parsedDocument.documents.length === 1, `1 document should be available but there are ${parsedDocument.documents.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); }); it('parse document with comment first and directive', () => { const parsedDocument = parse('# a comment\n%TAG !yaml! tag:yaml.org,2002:\ntest: test'); assert( parsedDocument.documents.length === 1, `1 document should be available but there are ${parsedDocument.documents.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); }); it('parse document with comment first, directive, and seperator', () => { const parsedDocument = parse('# a comment\n%TAG !yaml! tag:yaml.org,2002:\n---test: test'); assert( parsedDocument.documents.length === 1, `1 document should be available but there are ${parsedDocument.documents.length}` ); assert(parsedDocument.documents[0].lineComments.length === 1); assert(parsedDocument.documents[0].lineComments[0] === '# a comment'); }); it('parse document with "str" tag from recommended schema', () => { const parsedDocument = parse('"yes as a string with tag": !!str yes'); assert( parsedDocument.documents.length === 1, `1 document should be available but there are ${parsedDocument.documents.length}` ); assert(parsedDocument.documents[0].errors.length === 0); }); it('parse document with "int" tag from recommended schema', () => { const parsedDocument = parse('POSTGRES_PORT: !!int 54'); assert( parsedDocument.documents.length === 1, `1 document should be available but there are ${parsedDocument.documents.length}` ); assert(parsedDocument.documents[0].errors.length === 0, JSON.stringify(parsedDocument.documents[0].errors)); }); }); describe('YAML parser bugs', () => { it('should work with "Billion Laughs" attack', () => { const yaml = `apiVersion: v1 data: a: &a ["web","web","web","web","web","web","web","web","web"] b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a] c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b] d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c] e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d] f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e] g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f] h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g] i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h] kind: ConfigMap metadata: name: yaml-bomb namespace: defaul`; const parsedDocument = parse(yaml); assert.strictEqual( parsedDocument.documents.length, 1, `1 document should be available but there are ${parsedDocument.documents.length}` ); }); }); describe('YAML version', () => { it('should use yaml 1.2 by default', () => { const parsedDocument = parse('SOME_BOOLEAN : !!bool yes'); assert(parsedDocument.documents[0].warnings.length === 1); }); it('should respect yaml 1.1', () => { const parsedDocument = parse('SOME_BOOLEAN : !!bool yes', { customTags: [], yamlVersion: '1.1' }); assert(parsedDocument.documents[0].warnings.length === 0); }); }); });
the_stack
import { NodePath } from '@babel/core'; import * as t from '@babel/types'; import camelCase from 'lodash/camelCase'; import groupBy from 'lodash/groupBy'; import uniq from 'lodash/uniq'; import { NodeStyleMap, ResolvedOptions, Style } from '../types'; import cssUnits from './cssUnits'; import isCssTag from './isCssTag'; import hash from './murmurHash'; import processCss from './processCss'; import replaceComposes from './replaceComposes'; import resolveDependency, { Dependency } from './resolveDependency'; import trimEnd from './trimEnd'; import truthy from './truthy'; import wrapInClass, { hoistImports } from './wrapInClass'; const rPlaceholder = /###ASTROTURF_PLACEHOLDER_\d*?###/g; // Match any valid CSS units followed by a separator such as ;, newline etc. const rUnit = new RegExp(`^(${cssUnits.join('|')})(;|,|\n| |\\))`); const getPlaceholder = (idx: number) => `###ASTROTURF_PLACEHOLDER_${idx}###`; const toVarsArray = (interpolations: DynamicInterpolation[]) => { const vars = interpolations.map((i) => t.arrayExpression( trimEnd([ t.stringLiteral(i.id), i.expr.node, i.unit ? t.stringLiteral(i.unit) : null, ]), ), ); return t.arrayExpression(vars); }; /** * Build a logical expression returning a class, trying both the * kebab and camel case names: `s['fooBar']` * * @param {String} className */ const buildStyleExpression = (id: t.Identifier, className: string) => t.memberExpression( id, t.stringLiteral(className), // remove the `.` true, ); export type Vars = t.ArrayExpression[]; export type Variants = t.Expression[]; export type TagLocation = 'STYLESHEET' | 'RULE' | 'COMPONENT' | 'PROP'; export interface DynamicInterpolation { id: string; unit: string; expr: NodePath<t.Expression>; } function assertDynamicInterpolationsLocation( expr: NodePath<t.Expression>, location: TagLocation, opts: ResolvedOptions, ) { const parent = expr.findParent((p) => p.isTaggedTemplateExpression()) as any; // may be undefined in the `styled.button` case, or plain css prop case const tagName = parent?.node.tag?.name; const validLocation = location === 'COMPONENT' || location === 'PROP'; if (!validLocation) { const jsxAttr = expr.findParent((p) => p.isJSXAttribute()) as any; if (jsxAttr) { const propName = jsxAttr.node.name.name; throw jsxAttr.buildCodeFrameError( `This ${tagName} tag with dynamic expressions cannot be used with \`${propName}\` prop. ` + `Dynamic styles can only be passed to the \`css\` prop. Move the style to css={...} to fix the issue${ !opts.enableCssProp ? ' (and set the `enableCssProp` to `true` or `"cssProp"` in your astroturf options to allow this feature)' : '.' }`, ); } throw expr.buildCodeFrameError( 'The following expression could not be evaluated during compilation. ' + 'Dynamic expressions can only be used in the context of a component, ' + 'in a `css` prop, or styled() component helper', ); } // valid but not configured for this location if (validLocation) { if (!opts.enableDynamicInterpolations) throw expr.buildCodeFrameError( 'Dynamic expression compilation is not enabled. ' + 'To enable this usage set the the `enableDynamicInterpolations` to `true` or `"cssProp"` in your astroturf options', ); if ( opts.enableDynamicInterpolations === 'cssProp' && location === 'COMPONENT' ) throw expr.buildCodeFrameError( 'Dynamic expression compilation is not enabled. ' + 'To enable this usage set the `enableDynamicInterpolations` from `"cssProp"` to `true` in your astroturf options.', ); } } /** * Traverses an expression in a template string looking for additional astroturf * styles. Inline css tags are replaced with an identifier to the class name */ function resolveVariants( exprPath: NodePath<t.Expression>, opts: Options, state: any, ) { const { importId } = opts; const templates = [] as any[]; exprPath.traverse({ TaggedTemplateExpression(innerPath) { if (!isCssTag(innerPath.get('tag'), opts.pluginOptions)) { return; } if (opts.allowVariants === false) { throw innerPath.buildCodeFrameError( 'Nested Variants are not allowed here', ); } if (opts.location !== 'PROP') { throw exprPath.buildCodeFrameError( 'Dynamic variants are only allowed in css props', ); } // camel case so we don't need to check multiple cases at runtime const classId = camelCase( `${opts.style.identifier}-variant-${state.id++}`, ); // eslint-disable-next-line @typescript-eslint/no-use-before-define const { text, ...rest } = buildTemplateImpl( { ...opts, quasiPath: innerPath.get('quasi'), allowVariants: false, }, state, ); innerPath.replaceWith(buildStyleExpression(importId!, classId)); templates.push({ text: `.${classId} {\n${text}\n}`, ...rest, }); }, }); return templates; } function replaceDependencyPlaceholders( depInterpolations: Map<string, DependencyWithExpr>, text: string, dependencyImports: string, id: number, opts: ResolvedOptions, ) { text = replaceComposes(text, (composes, classList, fromPart) => { const composed = classList .map((className) => depInterpolations.get(className)) .filter(truthy); if (!composed.length) return composes; if (fromPart) { // don't want to deal with this case right now throw composed[0].expr.buildCodeFrameError( 'A styled interpolation found inside a `composes` rule with a "from". ' + 'Interpolated values should be in their own `composes` without specifying the file.', ); } if (composed.length < classList.length) { throw composed[0].expr.buildCodeFrameError( 'Mixing interpolated and non-interpolated classes in a `composes` rule is not allowed.', ); } return Object.entries(groupBy(composed, (i) => i.source)).reduce( (acc, [source, values]) => { const classes = uniq( // We need to to use the class with the styles for composes values.map((v) => (v.imported === 'cls1' ? 'cls2' : v.imported)), ).join(' '); return `${ acc ? `${acc};\n` : '' }composes: ${classes} from "${source}"`; }, '', ); }); text = text.replace(rPlaceholder, (match) => { const { imported, source } = depInterpolations.get(match)!; const localName = `a${id++}`; if (opts.experiments.modularCssExternals) { return `:external(${imported} from "${source}")`; } dependencyImports += `@value ${imported} as ${localName} from "${source}";\n`; return `.${localName}`; }); return [text, dependencyImports]; } interface Options { quasiPath: NodePath<t.TemplateLiteral>; importId?: t.Identifier; nodeMap: NodeStyleMap; location: TagLocation; allowVariants?: boolean; pluginOptions: ResolvedOptions; style: Style; } interface Rule { text: string; imports: string; vars: DynamicInterpolation[]; variants: Array<{ expr: any; rules: Rule[] }>; } type DependencyWithExpr = Dependency & { expr: NodePath<t.Expression>; }; function buildTemplateImpl(opts: Options, state = { id: 0 }) { const { quasiPath, nodeMap, pluginOptions, location, style: localStyle, } = opts; const quasi = quasiPath.node; const variants: Rule['variants'] = []; const depInterpolations = new Map<string, DependencyWithExpr>(); const dynamicInterpolations = new Set<DynamicInterpolation>(); const expressions = quasiPath.get('expressions'); let text = ''; let dependencyImports = ''; let lastDynamic: DynamicInterpolation | null = null; quasi.quasis.forEach((tmplNode, idx) => { const { raw } = tmplNode.value; const expr = expressions[idx] as NodePath<t.Expression>; let matches; // If the last quasi is a replaced dynamic import then see if there // was a trailing css unit and extract it as part of the interpolation if ( lastDynamic && text.endsWith(`var(--${lastDynamic.id})`) && // eslint-disable-next-line no-cond-assign (matches = raw.match(rUnit)) ) { const [, unit] = matches; lastDynamic.unit = unit; text += raw.replace(rUnit, '$2'); } else { text += raw; } if (!expr) { return; } const result = expr.evaluate(); if (result.confident) { text += result.value; return; } // TODO: dedupe the same expressions in a tag const resolvedDep = resolveDependency( expr, nodeMap, localStyle, pluginOptions, ); if (resolvedDep) { const ph = getPlaceholder(idx); depInterpolations.set(ph, { ...resolvedDep, expr }); text += ph; return; } const exprNode = expr.node; const resolvedInnerTemplates = resolveVariants(expr, opts, state); if (resolvedInnerTemplates.length) { variants.push({ expr: exprNode, rules: resolvedInnerTemplates }); return; } assertDynamicInterpolationsLocation(expr, location, pluginOptions); // custom properties need to start with a letter const id = `a${hash(`${localStyle.identifier}-${state.id++}`)}`; lastDynamic = { id, expr, unit: '' }; dynamicInterpolations.add(lastDynamic); text += `var(--${id})`; }); [text, dependencyImports] = replaceDependencyPlaceholders( depInterpolations, text, dependencyImports, state.id, opts.pluginOptions, ); if (dependencyImports) dependencyImports += '\n\n'; const [rule, imports] = hoistImports(text); return { variants, text: rule, imports: `${dependencyImports}${imports.join('\n')}`, vars: Array.from(dynamicInterpolations), }; } export default function buildTaggedTemplate(opts: Options) { const { location } = opts; const { text, vars, imports, variants } = buildTemplateImpl(opts, { id: 0 }); const allVars = vars; const allVariants = [] as any[]; let allImports = imports; let css = location === 'STYLESHEET' ? text : wrapInClass(text); for (const variant of variants) { allVariants.push(variant.expr); for (const rule of variant.rules) { allImports += rule.imports; allVars.push(...rule.vars); css += `\n${rule.text}`; } } css = `${allImports.trim()}\n\n${css}`.trim(); if ( location !== 'STYLESHEET' && opts.style.absoluteFilePath.endsWith('.css') ) { try { css = processCss(css, opts.style.absoluteFilePath).css; } catch { /* ignore */ } } return { css, interpolations: allVars.map(({ expr: _, ...i }) => i), vars: toVarsArray(allVars), variants: t.arrayExpression(allVariants), }; }
the_stack
import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/debounceTime'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Actions, Effect, toPayload } from '@ngrx/effects'; import { Store, Action } from '@ngrx/store'; import { ActivatedRoute, Router } from '@angular/router'; import { appAction } from '../../../actions'; import { global, authPayload, StorageService, pageNumber, ApiService } from '../../../services/common'; import { AppStore } from '../../../app.store'; import { chatAction } from '../actions'; import { mainAction } from '../../main/actions'; import { Util } from '../../../services/util'; import { contactAction } from '../../contact/actions'; @Injectable() export class ChatEffect { // 同步自己发送的消息 @Effect() private syncReceiveMessage$: Observable<Action> = this.actions$ .ofType(chatAction.syncReceiveMessage) .map(toPayload) .switchMap(async (info) => { let content = info.data.messages[0].content; let promises = []; // 如果是文件或者图片 this.getMediaUrl(info, promises); // 如果是名片 this.getCardResource(content, info, promises); await Promise.all(promises); this.store$.dispatch({ type: chatAction.receiveMessageSuccess, payload: info.data }); return { type: '[chat] sync receive message useless' }; }); // 接收到单聊新消息 @Effect() private receiveSingleMessage$: Observable<Action> = this.actions$ .ofType(chatAction.receiveSingleMessage) .map(toPayload) .switchMap(async (info) => { let promises = []; const content = info.data.messages[0].content; // 如果接收的是图片或者文件 this.getMediaUrl(info, promises); const result = info.conversation.filter((conversation) => { return info.data.messages[0].content.from_id === conversation.name; }); if (result.length === 0) { const messages = info.data.messages[0]; this.getMsgAvatarUrl(messages, promises); } else { // 给已有的单聊用户添加头像 content.avatarUrl = result[0].avatarUrl; } // 如果接收的是名片 this.getCardResource(content, info, promises); await Promise.all(promises); this.store$.dispatch({ type: chatAction.receiveMessageSuccess, payload: info.data }); return { type: '[chat] receive single message useless' }; }); // 接收到群聊新消息 @Effect() private receiveGroupMessage$: Observable<Action> = this.actions$ .ofType(chatAction.receiveGroupMessage) .map(toPayload) .switchMap(async (obj) => { let promises = []; const messages = obj.data.messages[0]; const messageList = obj.messageList; let flag = false; const content = messages.content; // 如果接收的是图片或者文件 this.getMediaUrl(obj, promises); // 如果接收的是名片 this.getCardResource(content, obj, promises); // 判断是否消息列表中已经加载过头像 for (let list of messageList) { if (list.type === 4 && Number(list.key) === Number(messages.key) && list.msgs.length > 0) { for (let i = list.msgs.length - 1; i >= 0; i--) { const hasLoadAvatar = list.msgs[i].content.hasOwnProperty('avatarUrl'); if (list.msgs[i].content.from_id === messages.content.from_id && hasLoadAvatar) { messages.content.avatarUrl = list.msgs[i].content.avatarUrl; flag = true; break; } } break; } } if (!flag) { this.getMsgAvatarUrl(messages, promises); } await Promise.all(promises); this.store$.dispatch({ type: chatAction.receiveMessageSuccess, payload: obj.data }); return { type: '[chat] receive message useless' }; }); // 获取storage里的voice状态 @Effect() private getVoiceState$: Observable<Action> = this.actions$ .ofType(chatAction.getVoiceState) .map(toPayload) .switchMap(async (key) => { const voiceState = this.storageService.get(key); if (voiceState) { this.store$.dispatch({ type: chatAction.getVoiceStateSuccess, payload: JSON.parse(voiceState) }); } return { type: '[chat] get voice state useless' }; }); // 获取好友列表 @Effect() private getFriendList$: Observable<Action> = this.actions$ .ofType(chatAction.getFriendList) .map(toPayload) .switchMap(async (info) => { const data: any = await this.apiService.getFriendList(); if (data.code) { this.errorFn(data); } else { let payload; if (info === 'api') { payload = { friendList: data.friend_list, type: info }; } else { payload = data.friend_list; } this.store$.dispatch({ type: chatAction.getFriendListSuccess, payload }); for (let friend of data.friend_list) { if (friend.avatar && friend.avatar !== '') { const urlObj = { media_id: friend.avatar }; this.apiService.getResource(urlObj).then((urlInfo: any) => { if (!urlInfo.code) { friend.avatarUrl = urlInfo.url; } }); } } } return { type: '[chat] get friend list useless' }; }); // 获取messageList 图片消息url @Effect() private getSourceUrl$: Observable<Action> = this.actions$ .ofType(chatAction.getSourceUrl) .map(toPayload) .switchMap(async (info) => { let resourceArray = []; const msgs = info.messageList[info.active.activeIndex].msgs; const end = msgs.length - (info.loadingCount - 1) * pageNumber; this.store$.dispatch({ type: chatAction.getAllMessageSuccess, payload: info.messageList }); // 滚动加载资源路径 if (end >= 1) { for (let i = end - 1; i >= end - pageNumber && i >= 0; i--) { if (msgs[i].hasLoad) { continue; } msgs[i].hasLoad = true; const msgBody = msgs[i].content.msg_body; if (msgBody.media_id && !msgBody.media_url) { const urlObj = { media_id: msgBody.media_id }; this.apiService.getResource(urlObj).then((urlInfo: any) => { if (urlInfo.code) { msgs[i].content.msg_body.media_url = ''; } else { msgs[i].content.msg_body.media_url = urlInfo.url; this.store$.dispatch({ type: chatAction.getAllMessageSuccess, payload: info.messageList }); } }); } else if (msgBody.extras && msgBody.extras.businessCard) { const userObj = { username: msgBody.extras.userName }; this.apiService.getUserInfo(userObj).then((data: any) => { if (!data.code) { msgBody.extras.nickName = data.user_info.nickname; msgBody.extras.media_url = ''; if (data.user_info.avatar !== '') { const urlObj = { media_id: data.user_info.avatar }; this.apiService.getResource(urlObj).then((urlInfo: any) => { if (!urlInfo.code) { msgBody.extras.media_url = urlInfo.url; } }); } } }); } } } return { type: '[chat] get source url useless' }; }); // 获取messageList avatar url @Effect() private getMemberAvatarUrl$: Observable<Action> = this.actions$ .ofType(chatAction.getMemberAvatarUrl) .map(toPayload) .switchMap(async (info) => { let userArr = []; const msgs = info.messageList[info.active.activeIndex].msgs; const end = msgs.length - (info.loadingCount - 1) * pageNumber; this.store$.dispatch({ type: chatAction.getAllMessageSuccess, payload: info.messageList }); for (let i = end - 1; i >= end - pageNumber && i >= 0 && end >= 1; i--) { // 如果是已经加载过头像的用户 if (info.loadingCount !== 1) { let flag = false; for (let j = end; j < msgs.length; j++) { if (msgs[i].content.from_id === msgs[j].content.from_id) { if (msgs[j].content.avatarUrl) { msgs[i].content.avatarUrl = msgs[j].content.avatarUrl; flag = true; } break; } } if (flag) { continue; } } msgs[i].content.avatarUrl = ''; // 第一次加载头像的用户 if (msgs[i].content.from_id !== global.user && userArr.indexOf(msgs[i].content.from_id) < 0) { userArr.push(msgs[i].content.from_id); } } for (let user of userArr) { const userObj = { username: user }; this.apiService.getUserInfo(userObj).then((data: any) => { if (!data.code && data.user_info.avatar !== '') { const urlObj = { media_id: data.user_info.avatar }; this.apiService.getResource(urlObj).then((urlInfo: any) => { if (!urlInfo.code) { for (let i = end - 1; i >= end - pageNumber && i >= 0 && end >= 1; i--) { if (msgs[i].content.from_id === user) { msgs[i].content.avatarUrl = urlInfo.url; } } } }); } }); } return { type: '[chat] get member avatar url useless' }; }); // 获取所有漫游同步消息、获取群屏蔽列表、获取免打扰列表 @Effect() private getAllMessage$: Observable<Action> = this.actions$ .ofType(chatAction.getAllMessage) .map(toPayload) .switchMap(async (data) => { for (let dataItem of data) { for (let j = 0; j < dataItem.msgs.length; j++) { if (j + 1 < dataItem.msgs.length || dataItem.msgs.length === 1) { if (j === 0) { dataItem.msgs[j].time_show = Util.reducerDate(dataItem.msgs[j].ctime_ms); } if (j + 1 !== dataItem.msgs.length) { if (Util.fiveMinutes(dataItem.msgs[j].ctime_ms, dataItem.msgs[j + 1].ctime_ms)) { dataItem.msgs[j + 1].time_show = Util.reducerDate(dataItem.msgs[j + 1].ctime_ms); } } } } for (let receiptMsg of dataItem.receipt_msgs) { for (let message of dataItem.msgs) { if (receiptMsg.msg_id === message.msg_id) { message.unread_count = receiptMsg.unread_count; break; } } } if (dataItem.msgs.length > 0) { if (dataItem.msgs[0].msg_type === 3) { dataItem.type = 3; if (dataItem.msgs[0].content.from_id === global.user) { dataItem.name = dataItem.msgs[0].content.target_id; dataItem.appkey = dataItem.msgs[0].content.target_appkey; } else if (dataItem.msgs[0].content.target_id === global.user) { dataItem.name = dataItem.msgs[0].content.from_id; dataItem.appkey = dataItem.msgs[0].content.from_appkey; } } else if (dataItem.msgs[0].msg_type === 4) { dataItem.type = 4; } } } const info: any = await this.apiService.getConversation(); if (info.code) { this.errorFn(info); } else { // 删除feedBack_ for (let i = 0; i < info.conversations.length; i++) { info.conversations[i].unreadNum = info.conversations[i].unread_msg_count; if (info.conversations[i].name.match(/^feedback_/g)) { info.conversations.splice(i, 1); } } info.conversations.reverse(); // 对置顶会话进行排序 let topArr = []; let notopArr = []; for (let conversation of info.conversations) { if (conversation.extras && conversation.extras.top_time_ms) { topArr.push(conversation); } else { notopArr.push(conversation); } } for (let i = 0; i < topArr.length; i++) { for (let j = i + 1; j < topArr.length; j++) { if (topArr[i].extras.top_time_ms > topArr[j].extras.top_time_ms) { let temp = topArr[i]; topArr[i] = topArr[j]; topArr[j] = temp; } } } info.conversations = topArr.concat(notopArr); // 获取头像url let promises = []; for (let conversation of info.conversations) { if (conversation.type === 4 && conversation.name === '') { const groupObj = { gid: conversation.key }; const pro = this.apiService.getGroupMembers(groupObj).then((group: any) => { if (group.code) { conversation.name = '#群名获取失败??'; this.errorFn(group); } else { let name = ''; for (let member of group.member_list) { name += (member.nickName || member.nickname || member.username || member.name) + '、'; } if (name.length > 20) { conversation.name = name.substr(0, 20); } else { conversation.name = name.substr(0, name.length - 1); } conversation.target_name = conversation.name; conversation.group_name = conversation.name; } }); promises.push(pro); } } // 获取免打扰列表 let noDisturb; const pro1 = this.apiService.getNoDisturb().then((noDisturbList: any) => { if (noDisturbList.code) { this.errorFn(noDisturbList); } else { noDisturb = noDisturbList.no_disturb; } }); let shield; // 获取屏蔽列表 const pro2 = this.apiService.groupShieldList().then((groupList: any) => { if (groupList.code) { this.errorFn(groupList); } else { shield = groupList.groups; } }); promises.push(pro1); promises.push(pro2); await Promise.all(promises); this.store$.dispatch({ type: chatAction.getConversationSuccess, payload: { conversation: info.conversations, storage: true, messageList: data, noDisturb, shield } }); this.store$.dispatch({ type: chatAction.getFriendList, payload: 'first' }); this.store$.dispatch({ type: contactAction.getGroupList, payload: 'first' }); // 加载会话头像 for (let conversation of info.conversations) { if (conversation.avatar && conversation.avatar !== '') { const urlObj = { media_id: conversation.avatar }; this.apiService.getResource(urlObj).then((urlInfo: any) => { if (!urlInfo.code) { conversation.avatarUrl = urlInfo.url; } }); } } } return { type: '[chat] get all messageList useless' }; }); // 发送单人文本消息 @Effect() private sendMessage$: Observable<Action> = this.actions$ .ofType(chatAction.sendSingleMessage) .map(toPayload) .filter((data) => { if (!data.singleMsg.content) { return false; } return data; }).switchMap(async (text) => { const msgs: any = await this.apiService.sendSingleMsg(text.singleMsg); if (msgs.code) { this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: text.msgs.msgKey, key: text.key, success: 3, name: text.active.name, type: 3 } }); this.errorFn(msgs); } else { msgs.unread_count = 1; msgs.msg_type = 3; this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: text.msgs.msgKey, key: text.key, success: 2, msgs, name: text.active.name, type: 3 } }); } return { type: '[chat] send single message useless' }; }); // 转发单人文本消息 @Effect() private transmitMessage$: Observable<Action> = this.actions$ .ofType(chatAction.transmitSingleMessage) .map(toPayload) .switchMap(async (text) => { const msgBody = { text: text.msgs.content.msg_body.text, extras: text.msgs.content.msg_body.extras }; const msgObj = { target_username: text.select.name, target_nickname: text.select.nickName, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendSingleMsg(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: text.msgs.msgKey, key: text.select.key, success: 3, name: text.select.name, type: 3 } }); if (text.transmitMsg) { msgs.text = text.select.memo_name || text.select.nickName || text.select.name; } this.errorFn(msgs); } else { msgs.unread_count = 1; msgs.msg_type = 3; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: text.msgs.msgKey, key: text.select.key, success: 2, msgs, name: text.select.name, type: 3 } }); } return { type: '[chat] transmit single message useless' }; }); // 发送群组文本消息 @Effect() private sendGroupMessage$: Observable<Action> = this.actions$ .ofType(chatAction.sendGroupMessage) .map(toPayload) .filter((data) => { if (!data.groupMsg.content) { return false; } return data; }).switchMap(async (text) => { const msgs: any = await this.apiService.sendGroupMsg(text.groupMsg); if (msgs.code) { this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: text.msgs.msgKey, key: text.key, success: 3, type: 4 } }); this.errorFn(msgs); } else { msgs.msg_type = 4; this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: text.msgs.msgKey, key: text.key, success: 2, msgs, type: 4 } }); } return { type: '[chat] send group message useless' }; }); // 转发群组文本消息 @Effect() private transmitGroupMessage$: Observable<Action> = this.actions$ .ofType(chatAction.transmitGroupMessage) .map(toPayload) .switchMap(async (text) => { const msgBody = { text: text.msgs.content.msg_body.text, extras: text.msgs.content.msg_body.extras }; const msgObj = { target_gid: text.select.key, target_gname: text.select.name, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendGroupMsg(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: text.msgs.msgKey, key: text.select.key, success: 3, type: 4 } }); if (text.transmitMsg) { msgs.text = text.select.name; } this.errorFn(msgs); } else { msgs.msg_type = 4; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: text.msgs.msgKey, key: text.select.key, success: 2, msgs, type: 4 } }); } return { type: '[chat] transmit group message useless' }; }); // 发送单聊图片消息 @Effect() private sendSinglePic$: Observable<Action> = this.actions$ .ofType(chatAction.sendSinglePic) .map(toPayload) .switchMap(async (img) => { const msgs: any = await this.apiService.sendSinglePic(img.singlePicFormData); if (msgs.code) { this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 3, name: img.active.name, type: 3 } }); this.errorFn(msgs); } else { msgs.unread_count = 1; msgs.msg_type = 3; this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 2, msgs, name: img.active.name, type: 3 } }); } return { type: '[chat] send single picture useless' }; }); // 转发单聊图片消息 @Effect() private transmitSinglePic$: Observable<Action> = this.actions$ .ofType(chatAction.transmitSinglePic) .map(toPayload) .switchMap(async (img) => { const body = img.msgs.content.msg_body; const msgBody = { media_id: body.media_id, media_crc32: body.media_crc32, width: body.width, height: body.height, format: body.format, fsize: body.fsize, extras: body.extras }; const msgObj = { target_username: img.select.name, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendSinglePic(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 3, name: img.select.name, type: 3 } }); if (img.transmitMsg) { msgs.text = img.select.memo_name || img.select.nickName || img.select.name; } this.errorFn(msgs); } else { msgs.unread_count = 1; msgs.msg_type = 3; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 2, msgs, name: img.select.name, type: 3 } }); } return { type: '[chat] transmit single picture useless' }; }); // 发送群组图片消息 @Effect() private sendGroupPic$: Observable<Action> = this.actions$ .ofType(chatAction.sendGroupPic) .map(toPayload) .switchMap(async (img) => { const msgs: any = await this.apiService.sendGroupPic(img.groupPicFormData); if (msgs.code) { this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 3, type: 4 } }); this.errorFn(msgs); } else { msgs.msg_type = 4; this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 2, msgs, type: 4 } }); } return { type: '[chat] send group pic useless' }; }); // 转发群组图片消息 @Effect() private transmitGroupPic$: Observable<Action> = this.actions$ .ofType(chatAction.transmitGroupPic) .map(toPayload) .switchMap(async (img) => { const body = img.msgs.content.msg_body; const msgBody = { media_id: body.media_id, media_crc32: body.media_crc32, width: body.width, height: body.height, format: body.format, fsize: body.fsize, extras: body.extras }; const msgObj = { target_gid: img.select.key, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendGroupPic(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 3, type: 4 } }); if (img.transmitMsg) { msgs.text = img.select.name; } this.errorFn(msgs); } else { msgs.msg_type = 4; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: img.msgs.msgKey, key: img.key, success: 2, msgs, type: 4 } }); } return { type: '[chat] transmit group pic useless' }; }); // 发送单聊文件消息 @Effect() private sendSingleFile$: Observable<Action> = this.actions$ .ofType(chatAction.sendSingleFile) .map(toPayload) .switchMap(async (file) => { const msgs: any = await this.apiService.sendSingleFile(file.singleFile); if (msgs.code) { this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 3, type: 3, name: file.active.name } }); this.errorFn(msgs); } else { msgs.unread_count = 1; msgs.msg_type = 3; this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 2, msgs, type: 3, name: file.active.name } }); } return { type: '[chat] send single file useless' }; }); // 转发单聊文件消息 @Effect() private transmitSingleFile$: Observable<Action> = this.actions$ .ofType(chatAction.transmitSingleFile) .map(toPayload) .switchMap(async (file) => { const body = file.msgs.content.msg_body; const msgBody = { media_id: body.media_id, media_crc32: body.media_crc32, hash: body.hash, fname: body.fname, fsize: body.fsize, extras: body.extras }; const msgObj = { target_username: file.select.name, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendSingleFile(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 3, name: file.select.name, type: 3 } }); if (file.transmitMsg) { msgs.text = file.select.memo_name || file.select.nickName || file.select.name; } this.errorFn(msgs); } else { msgs.unread_count = 1; msgs.msg_type = 3; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 2, msgs, name: file.select.name, type: 3 } }); } return { type: '[chat] transmit single file useless' }; }); // 发送群组文件消息 @Effect() private sendGroupFile$: Observable<Action> = this.actions$ .ofType(chatAction.sendGroupFile) .map(toPayload) .switchMap(async (file) => { const msgs: any = await this.apiService.sendGroupFile(file.groupFile); if (msgs.code) { this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 3, type: 4 } }); this.errorFn(msgs); } else { msgs.msg_type = 4; this.store$.dispatch({ type: chatAction.sendMsgComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 2, msgs, type: 4 } }); } return { type: '[chat] send group file useless' }; }); // 转发群组文件消息 @Effect() private transmitGroupFile$: Observable<Action> = this.actions$ .ofType(chatAction.transmitGroupFile) .map(toPayload) .switchMap(async (file) => { const body = file.msgs.content.msg_body; const msgBody = { media_id: body.media_id, media_crc32: body.media_crc32, hash: body.hash, fname: body.fname, fsize: body.fsize, extras: body.extras }; const msgObj = { target_gid: file.select.key, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendGroupFile(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 3, type: 4 } }); if (file.transmitMsg) { msgs.text = file.select.name; } this.errorFn(msgs); } else { msgs.msg_type = 4; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: file.msgs.msgKey, key: file.key, success: 2, msgs, type: 4 } }); } return { type: '[chat] transmit group file useless' }; }); // 转发单聊位置消息 @Effect() private transmitSingleLocation$: Observable<Action> = this.actions$ .ofType(chatAction.transmitSingleLocation) .map(toPayload) .switchMap(async (location) => { const body = location.msgs.content.msg_body; const msgBody = { latitude: body.latitude, longitude: body.longitude, scale: body.scale, label: body.label, fsize: body.fsize, extras: body.extras }; const msgObj = { target_username: location.select.name, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendSingleLocation(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: location.msgs.msgKey, key: location.key, success: 3, name: location.select.name, type: 3 } }); if (location.transmitMsg) { msgs.text = location.select.memo_name || location.select.nickName || location.select.name; } this.errorFn(msgs); } else { msgs.unread_count = 1; msgs.msg_type = 3; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: location.msgs.msgKey, key: location.key, success: 2, msgs, name: location.select.name, type: 3 } }); } return { type: '[chat] transmit single location useless' }; }); // 转发群组位置消息 @Effect() private transmitGroupLocation$: Observable<Action> = this.actions$ .ofType(chatAction.transmitGroupLocation) .map(toPayload) .switchMap(async (location) => { const body = location.msgs.content.msg_body; const msgBody = { latitude: body.latitude, longitude: body.longitude, scale: body.scale, label: body.label, fsize: body.fsize, extras: body.extras }; const msgObj = { target_gid: location.select.key, msg_body: msgBody, need_receipt: true }; const msgs: any = await this.apiService.sendGroupLocation(msgObj); if (msgs.code) { this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: location.msgs.msgKey, key: location.key, success: 3, type: 4 } }); if (location.transmitMsg) { msgs.text = location.select.name; } this.errorFn(msgs); } else { msgs.msg_type = 4; this.store$.dispatch({ type: chatAction.transmitMessageComplete, payload: { msgKey: location.msgs.msgKey, key: location.key, success: 2, msgs, type: 4 } }); } return { type: '[chat] transmit group location useless' }; }); // 查看别人的资料 @Effect() private watchOtherInfo$: Observable<Action> = this.actions$ .ofType(chatAction.watchOtherInfo) .map(toPayload) .switchMap(async (other) => { const userObj = { username: other.username }; const data: any = await this.apiService.getUserInfo(userObj); if (data.code) { this.errorFn(data); } else { data.user_info.name = data.user_info.username; data.user_info.nickName = data.user_info.nickname; data.user_info.infoType = 'watchOtherInfo'; if (other.hasOwnProperty('avatarUrl') || data.user_info.avatar === '') { data.user_info.avatarUrl = other.avatarUrl ? other.avatarUrl : ''; } else { const urlObj = { media_id: data.user_info.avatar }; const urlInfo: any = await this.apiService.getResource(urlObj); if (!urlInfo.code) { data.user_info.avatarUrl = urlInfo.url; } } this.store$.dispatch({ type: chatAction.watchOtherInfoSuccess, payload: { info: data.user_info, show: true } }); } return { type: '[chat] watch other info useless' }; }); // 获取群组信息 @Effect() private groupInfo$: Observable<Action> = this.actions$ .ofType(chatAction.groupSetting) .map(toPayload) .filter((data) => { if (data.show === false || data.active.type === 3 || data.isCache) { return false; } return data; }).switchMap(async (info) => { const activeObj = { gid: info.active.key }; const data: any = await this.apiService.getGroupInfo(activeObj); if (data.code) { this.store$.dispatch({ type: chatAction.groupInfo, payload: { groupInfo: {} } }); this.errorFn(data); } else { if (data.group_info.avatar && data.group_info.avatar !== '') { const urlObj = { media_id: data.group_info.avatar }; const urlInfo: any = await this.apiService.getResource(urlObj); if (!urlInfo.code) { data.group_info.avatarUrl = urlInfo.url; } } this.store$.dispatch({ type: chatAction.groupInfo, payload: { groupInfo: data.group_info } }); } return { type: '[chat] group setting useless' }; }); // 获取群成员信息 @Effect() private getGroupMembers$: Observable<Action> = this.actions$ .ofType(chatAction.getGroupMembers) .map(toPayload) .switchMap(async (info) => { const infoObj = { gid: info.key }; const data: any = await this.apiService.getGroupMembers(infoObj); if (data.code) { this.errorFn(data); } else { Util.getMembersFirstLetter(data.member_list); this.store$.dispatch({ type: chatAction.groupInfo, payload: { memberList: data.member_list, key: info.key } }); for (let member of data.member_list) { if (member.avatar !== '') { const urlObj = { media_id: member.avatar }; this.apiService.getResource(urlObj).then((result: any) => { if (!result.code) { member.avatarUrl = result.url; this.store$.dispatch({ type: chatAction.groupInfo, payload: { memberList: data.member_list, key: info.key } }); } }); } } } return { type: '[chat] get group memebers useless' }; }); // 更新群组资料 @Effect() private updateGroupInfo$: Observable<Action> = this.actions$ .ofType(chatAction.updateGroupInfo) .map(toPayload) .switchMap(async (info) => { let requestObj: any = { gid: info.gid }; if (info.actionType) { if (info.actionType === 'modifyName') { requestObj.group_name = info.name; } else if (info.actionType === 'modifyDescription') { requestObj.group_description = info.desc; } else if (info.actionType === 'modifyGroupAvatar') { requestObj.avatar = info.avatar; } } const data: any = this.apiService.updateGroupInfo(requestObj); if (data.code) { this.errorFn(data); } else { if (info.actionType && info.actionType === 'modifyDescription') { this.store$.dispatch({ type: chatAction.groupDescription, payload: { data, show: false } }); } else if (info.actionType && info.actionType === 'modifyGroupAvatar') { this.store$.dispatch({ type: mainAction.showModalTip, payload: { show: true, info: { title: '修改群头像', tip: '修改群头像成功', actionType: '[chat] modify group avatar success useless', success: 1 } } }); } } return { type: '[chat] update group info useless' }; }); // 切换群屏蔽 @Effect() private changeGroupShield$: Observable<Action> = this.actions$ .ofType(chatAction.changeGroupShield) .map(toPayload) .switchMap(async (active) => { const activeObj = { gid: active.key }; let data: any; if (active.shield) { data = await this.apiService.delGroupShield(activeObj); } else { data = await this.apiService.addGroupShield(activeObj); } if (data.code) { this.errorFn(data); } else { active.shield = !active.shield; this.store$.dispatch({ type: chatAction.changeGroupShieldSuccess, payload: active }); } return { type: '[chat] change group shield useless' }; }); // 切换群免打扰 @Effect() private changeGroupNoDisturb$: Observable<Action> = this.actions$ .ofType(chatAction.changeGroupNoDisturb) .map(toPayload) .switchMap(async (active) => { const activeObj = { gid: active.key }; let data: any; if (active.noDisturb) { data = await this.apiService.delGroupNoDisturb(activeObj); } else { data = await this.apiService.addGroupNoDisturb(activeObj); } if (data.code) { this.errorFn(data); } else { active.noDisturb = !active.noDisturb; this.store$.dispatch({ type: chatAction.changeGroupNoDisturbSuccess, payload: active }); } return { type: '[chat] change group no disturb useless' }; }); // 被添加进群时获取群信息 @Effect() private addGroupMembersEvent$: Observable<Action> = this.actions$ .ofType(chatAction.addGroupMembersEvent) .map(toPayload) .switchMap(async (eventData) => { if (eventData.group_name && eventData.group_name !== '') { eventData.name = eventData.group_name; let promises = []; for (let userList of eventData.to_usernames) { if (userList.avatar && userList.avatar !== '') { const avatarObj = { media_id: userList.avatar }; const pro = this.apiService.getResource(avatarObj).then((urlInfo: any) => { if (!urlInfo.code) { userList.avatarUrl = urlInfo.url; } }); promises.push(pro); } } Promise.all(promises).then(() => { this.store$.dispatch({ type: chatAction.updateGroupMembersEvent, payload: { eventData } }); }); } else { const groupObj = { gid: eventData.gid }; const data: any = await this.apiService.getGroupMembers(groupObj); if (data.code) { this.errorFn(data); eventData.name = '#群名获取失败??'; } else { let name = ''; let promises = []; for (let member of data.member_list) { name += (member.nickName || member.nickname || member.username || member.name) + '、'; for (let userList of eventData.to_usernames) { if (userList.username === member.username) { const urlObj = { media_id: member.avatar }; const pro = this.apiService.getResource(urlObj) .then((urlInfo: any) => { if (!urlInfo.code) { userList.avatarUrl = urlInfo.url; } }); promises.push(pro); break; } } } Promise.all(promises).then(() => { this.store$.dispatch({ type: chatAction.updateGroupMembersEvent, payload: { eventData } }); }); if (name.length > 20) { eventData.name = name.substr(0, 20); } else { eventData.name = name.substr(0, name.length - 1); } eventData.target_name = eventData.name; eventData.group_name = eventData.name; } } const urlObj = { media_id: eventData.media_id }; this.apiService.getResource(urlObj).then((result: any) => { if (result.code) { eventData.avatarUrl = ''; } else { eventData.avatarUrl = result.url; } this.store$.dispatch({ type: chatAction.addGroupMembersEventSuccess, payload: eventData }); }); return { type: '[chat] add group members event useless' }; }); // 创建群组事件 @Effect() private createGroupEvent$: Observable<Action> = this.actions$ .ofType(chatAction.createGroupEvent) .map(toPayload) .switchMap(async (eventData) => { const groupObj = { gid: eventData.gid }; const data: any = await this.apiService.getGroupInfo(groupObj); if (data.code) { eventData.name = '#群名获取失败??'; } else { eventData.name = data.group_info.name; } this.store$.dispatch({ type: chatAction.createGroupSuccessEvent, payload: eventData }); return { type: '[chat] create group event useless' }; }); // 消息撤回 @Effect() private msgRetract$: Observable<Action> = this.actions$ .ofType(chatAction.msgRetract) .map(toPayload) .switchMap(async (item) => { const msgObj = { msg_id: item.msg_id, }; const data: any = await this.apiService.msgRetract(msgObj); if (data.code) { this.errorFn(data); } else { this.store$.dispatch({ type: chatAction.msgRetractSuccess, payload: item }); } return { type: '[chat] msg eetract useless' }; }); // 添加好友 @Effect() private addFriendConfirm$: Observable<Action> = this.actions$ .ofType(chatAction.addFriendConfirm) .map(toPayload) .switchMap(async (user) => { const friendObj = { target_name: user.name, from_type: 1, why: user.verifyModalText }; const data: any = await this.apiService.addFriend(friendObj); if (data.code) { this.errorFn(data); } else { this.store$.dispatch({ type: mainAction.showModalTip, payload: { show: true, info: { title: '好友申请', tip: '好友申请发送成功', actionType: '[chat] add friend success', success: 1 } } }); } return { type: '[chat] add friend confirm useless' }; }); // 个人资料中取消黑名单 @Effect() private deleteSingleBlack$: Observable<Action> = this.actions$ .ofType(chatAction.deleteSingleBlack) .map(toPayload) .switchMap(async (user) => { const userObj = { member_usernames: [{ username: user.name }] }; const data: any = await this.apiService.delSingleBlacks(userObj); if (data.code) { this.errorFn(data); } else { this.store$.dispatch({ type: mainAction.showModalTip, payload: { show: true, info: { title: '取消黑名单', tip: '取消黑名单成功', actionType: '[chat] delete single black success useless', success: 1 } } }); this.store$.dispatch({ type: chatAction.deleteSingleBlackSuccess, payload: user }); } return { type: '[chat] delete single black useless' }; }); // 个人资料中取消免打扰 @Effect() private deleteSingleNoDisturb$: Observable<Action> = this.actions$ .ofType(chatAction.deleteSingleNoDisturb) .map(toPayload) .switchMap(async (user) => { const userObj = { target_name: user.name }; const data: any = await this.apiService.delSingleNoDisturb(userObj); if (data.code) { this.errorFn(data); } else { this.store$.dispatch({ type: mainAction.showModalTip, payload: { show: true, info: { title: '取消免打扰', tip: '取消免打扰成功', actionType: '[chat] delete single no disturb success useless', success: 1 } } }); this.store$.dispatch({ type: chatAction.deleteSingleNoDisturbSuccess, payload: user }); } return { type: '[chat] delete single no disturb useless' }; }); // 修改备注名 @Effect() private saveMemoName$: Observable<Action> = this.actions$ .ofType(chatAction.saveMemoName) .map(toPayload) .switchMap(async (user) => { const friendObj = { target_name: user.name, memo_name: user.memo_name, memo_others: 'a' }; const data: any = await this.apiService.updateFriendMemo(friendObj); if (data.code) { this.errorFn(data); } else { this.store$.dispatch({ type: chatAction.saveMemoNameSuccess, payload: { to_usernames: [user] } }); } return { type: '[chat] save memo name useless' }; }); // 加载预览图片的图片url @Effect() private loadViewerImage$: Observable<Action> = this.actions$ .ofType(chatAction.loadViewerImage) .map(toPayload) .switchMap(async (info) => { const urlObj = { media_id: info.mediaId }; const data: any = await this.apiService.getResource(urlObj); if (data.code) { this.errorFn(data); } else { info.src = data.url; this.store$.dispatch({ type: chatAction.loadViewerImageSuccess, payload: info }); } return { type: '[chat] load viewer image useless' }; }); // 加载聊天文件的url @Effect() private msgFile$: Observable<Action> = this.actions$ .ofType(chatAction.msgFile) .map(toPayload) .switchMap(async (info) => { if (info.show) { const msgs = info.messageList[info.active.activeIndex].msgs; let promises = []; for (let i = msgs.length - 1; i >= 0; i--) { let type = ''; if (msgs[i].content.msg_type === 'file') { if (msgs[i].content.msg_body.extras) { if (msgs[i].content.msg_body.extras.video) { type = 'video'; } else if (msgs[i].content.msg_body.extras.fileType) { type = Util.sortByExt(msgs[i].content.msg_body.extras.fileType); } else { type = 'other'; } } } if ((type === info.type || (msgs[i].content.msg_type === info.type && info.type === 'image')) && !msgs[i].content.msg_body.media_url) { const urlObj = { media_id: msgs[i].content.msg_body.media_id }; const pro = this.apiService.getResource(urlObj).then((result: any) => { if (!result.code) { msgs[i].content.msg_body.media_url = result.url; } }); promises.push(pro); } if (promises.length > 0 && info.type === 'image') { Promise.all(promises).then(() => { this.store$.dispatch({ type: chatAction.msgFileSuccess, payload: { messageList: info.messageList, type: info.type, isFirst: false } }); }); } } this.store$.dispatch({ type: chatAction.msgFileSuccess, payload: { messageList: info.messageList, type: info.type, isFirst: true } }); } return { type: '[chat] msg file useless' }; }); // 会话置顶和取消会话置顶 @Effect() private conversationToTop$: Observable<Action> = this.actions$ .ofType(chatAction.conversationToTop) .map(toPayload) .switchMap(async (info) => { let extras; let conversation; if (info.extras.top_time_ms) { extras = {}; } else { extras = { top_time_ms: new Date().getTime() }; } if (info.type === 3) { conversation = { appkey: info.appkey, username: info.name, extras }; } else if (info.type === 4) { conversation = { gid: info.key, extras }; } if (conversation) { this.apiService.updateConversation(conversation); this.store$.dispatch({ type: chatAction.conversationToTopSuccess, payload: info }); } return { type: '[chat] conversation to top useless' }; }); // 已读未读列表 @Effect() private watchUnreadList$: Observable<Action> = this.actions$ .ofType(chatAction.watchUnreadList) .map(toPayload) .switchMap(async (info) => { if (info.message) { const msgObj = { msg_id: info.message.msg_id }; const data: any = await this.apiService.msgUnreadList(msgObj); if (data.code) { this.store$.dispatch({ type: chatAction.watchUnreadList, payload: { show: false } }); this.errorFn(data); } else { if (info.message.unread_count !== data.msg_unread_list.unread_list.length) { info.message.unread_count = data.msg_unread_list.unread_list.length; } this.store$.dispatch({ type: chatAction.watchUnreadListSuccess, payload: { info: data.msg_unread_list, loading: false } }); for (let unread of data.msg_unread_list.unread_list) { this.getUnreadListInfo(data, unread); } for (let unread of data.msg_unread_list.read_list) { this.getUnreadListInfo(data, unread); } } } return { type: '[chat] watch unread list useless' }; }); // 已读回执 @Effect() private addReceiptReport$: Observable<Action> = this.actions$ .ofType(chatAction.addReceiptReport) .map(toPayload) .switchMap(async (readObj) => { if (readObj && readObj.msg_id.length > 0) { if (readObj.type === 3) { const singleObj = { username: readObj.username, msg_ids: readObj.msg_id }; this.apiService.addSingleReceiptReport(singleObj); } else { const groupObj = { gid: readObj.gid, msg_ids: readObj.msg_id }; this.apiService.addGroupReceiptReport(groupObj); } } return { type: '[chat] add receipt report useless' }; }); // 验证消息请求头像 @Effect() private friendEvent$: Observable<Action> = this.actions$ .ofType(chatAction.friendEvent) .map(toPayload) .switchMap(async (info) => { info.type = 3; let type; if (info.extra === 1) { type = chatAction.friendInvitationEventSuccess; } else if (info.extra === 2) { type = chatAction.friendReplyEventSuccess; } info.avatarUrl = ''; if (info.media_id || info.media_id !== '') { const urlObj = { media_id: info.media_id }; const data: any = await this.apiService.getResource(urlObj); if (!data.code) { info.avatarUrl = data.url; } } this.store$.dispatch({ type, payload: info }); return { type: '[chat] friend event useless' }; }); // 更新群信息事件 @Effect() private updateGroupInfoEvent$: Observable<Action> = this.actions$ .ofType(chatAction.updateGroupInfoEvent) .map(toPayload) .switchMap(async (info) => { const groupObj = { gid: info.gid }; const data: any = await this.apiService.getGroupInfo(groupObj); if (data.code) { this.errorFn(data); } else { data.group_info.avatarUrl = ''; if (data.group_info.avatar && data.group_info.avatar !== '') { const urlObj = { media_id: data.group_info.avatar }; const result: any = await this.apiService.getResource(urlObj); if (!result.code) { data.group_info.avatarUrl = result.url; } } this.store$.dispatch({ type: chatAction.updateGroupInfoEventSuccess, payload: { groupInfo: data.group_info, eventData: info } }); } return { type: '[chat] update group info event useless' }; }); // 更新用户的信息事件 @Effect() private userInfUpdateEvent$: Observable<Action> = this.actions$ .ofType(chatAction.userInfUpdateEvent) .map(toPayload) .switchMap(async (info) => { info.name = info.from_username; info.type = 3; const userObj = { username: info.from_username }; const data: any = await this.apiService.getUserInfo(userObj); info.avatarUrl = ''; if (!data.code) { info.nickName = data.user_info.nickname; info = Object.assign({}, info, data.user_info); if (data.user_info.avatar && data.user_info.avatar !== '') { const urlObj = { media_id: data.user_info.avatar }; const result: any = await this.apiService.getResource(urlObj); if (!result.code) { info.avatarUrl = result.url; } } } this.store$.dispatch({ type: chatAction.userInfUpdateEventSuccess, payload: info }); return { type: '[chat] user inf update event useless' }; }); // 清空会话未读数 @Effect() private emptyUnreadNum$: Observable<Action> = this.actions$ .ofType(chatAction.emptyUnreadNum) .map(toPayload) .switchMap(async (unread) => { let unreadObj; if (unread.type === 3 && unread.name) { unreadObj = { username: unread.name }; } else if (unread.type === 4 && unread.key) { unreadObj = { gid: unread.key }; } if (unreadObj) { this.apiService.resetUnreadCount(unreadObj); } return { type: '[chat] empty unread count useless' }; }); // 发送透传消息正在输入 @Effect() private inputMessage$: Observable<Action> = this.actions$ .ofType(chatAction.inputMessage) .map(toPayload) .switchMap(async (message) => { const msgObj = { target_username: message.active.name, cmd: JSON.stringify(message.input) }; this.apiService.transSingleMsg(msgObj); return { type: '[chat] input message useless' }; }); // 添加群组成员禁言 @Effect() private addGroupMemberSilence$: Observable<Action> = this.actions$ .ofType(chatAction.addGroupMemberSilence) .map(toPayload) .switchMap(async (info) => { const memberObj = { gid: info.active.key, target_username: info.item.username }; const data: any = await this.apiService.addGroupMemSilence(memberObj); if (data.code) { const error = { code: -1, myText: '禁言失败' }; this.errorFn(error); } return { type: '[chat] add group member silence useless' }; }); // 删除群组成员禁言 @Effect() private deleteGroupMemberSilence$: Observable<Action> = this.actions$ .ofType(chatAction.deleteGroupMemberSilence) .map(toPayload) .switchMap(async (info) => { const memberObj = { gid: info.active.key, target_username: info.item.username }; const data: any = await this.apiService.delGroupMemSilence(memberObj); if (data.code) { const error = { code: -1, myText: '取消禁言失败' }; this.errorFn(error); } return { type: '[chat] delete group member silence useless' }; }); // 群主或者管理员,收到用户申请入群事件请求头像 @Effect() private receiveGroupInvitationEvent$: Observable<Action> = this.actions$ .ofType(chatAction.receiveGroupInvitationEvent) .map(toPayload) .switchMap(async (info) => { let promises = []; for (let user of info.to_usernames) { const urlObj = { media_id: user.avatar }; const pro = this.apiService.getResource(urlObj).then((urlInfo: any) => { if (urlInfo.code) { user.avatarUrl = ''; } else { user.avatarUrl = urlInfo.url; } }); promises.push(pro); } await Promise.all(promises); this.store$.dispatch({ type: chatAction.receiveGroupInvitationEventSuccess, payload: info }); return { type: '[chat] receive group invitation event useless' }; }); // 被拒绝入群事件 @Effect() private receiveGroupRefuseEvent$: Observable<Action> = this.actions$ .ofType(chatAction.receiveGroupRefuseEvent) .map(toPayload) .switchMap(async (info) => { const urlObj = { media_id: info.media_id }; const urlInfo: any = await this.apiService.getResource(urlObj); if (urlInfo.code) { info.avatarUrl = ''; } else { info.avatarUrl = urlInfo.url; } this.store$.dispatch({ type: chatAction.receiveGroupRefuseEventSuccess, payload: info }); return { type: '[chat] receive group refuse event useless' }; }); constructor( private actions$: Actions, private store$: Store<AppStore>, private router: Router, private storageService: StorageService, private apiService: ApiService ) { } private errorFn(error) { this.store$.dispatch({ type: appAction.errorApiTip, payload: error }); } // 获取未读和已读列表 private getUnreadListInfo(list, unread) { if (unread.avatar && unread.avatar !== '') { const urlObj = { media_id: unread.avatar }; this.apiService.getResource(urlObj).then((result: any) => { if (result.code) { unread.avatarUrl = ''; } else { unread.avatarUrl = result.url; } this.store$.dispatch({ type: chatAction.watchUnreadListSuccess, payload: { info: list.msg_unread_list, loading: false } }); }); } } // 接收消息获取media url private getMediaUrl(obj, promises?: any[]) { if (obj.data.messages[0].content.msg_body.media_id) { const urlObj = { media_id: obj.data.messages[0].content.msg_body.media_id }; const pro1 = this.apiService.getResource(urlObj).then((result: any) => { if (result.code) { obj.data.messages[0].content.msg_body.media_url = ''; } else { obj.data.messages[0].content.msg_body.media_url = result.url; } }); if (promises && promises instanceof Array) { promises.push(pro1); } } } // 名片消息获取资源 private async getCardResource(content, info, promises?: any[]) { if (content.msg_type === 'text' && content.msg_body.extras && content.msg_body.extras.businessCard) { const userObj = { username: info.data.messages[0].content.msg_body.extras.userName, appkey: authPayload.appkey }; const data: any = await this.apiService.getUserInfo(userObj); info.data.messages[0].content.msg_body.extras.nickName = data.user_info.nickname; if (promises && promises instanceof Array) { promises.push(data); } if (!data.code) { const urlObj = { media_id: data.user_info.avatar }; const urlInfo: any = await this.apiService.getResource(urlObj); if (promises && promises instanceof Array) { promises.push(urlInfo); } if (urlInfo.code) { info.data.messages[0].content.msg_body.extras.media_url = ''; } else { info.data.messages[0].content.msg_body.extras.media_url = urlInfo.url; } } } } // 获取新消息的用户头像url private async getMsgAvatarUrl(messages, promises) { const username = messages.content.from_id !== global.user ? messages.content.from_id : messages.content.target_id; const userObj = { username }; const pro2: any = await this.apiService.getUserInfo(userObj); promises.push(pro2); if (!pro2.user_info.avatar || pro2.user_info.avatar === '') { messages.content.avatarUrl = ''; } else { const urlObj = { media_id: pro2.user_info.avatar }; const pro3: any = await this.apiService.getResource(urlObj); promises.push(pro3); if (pro3.code) { messages.content.avatarUrl = ''; } else { messages.content.avatarUrl = pro3.url; } } } }
the_stack
import {ComponentRef, Injectable} from '@angular/core'; import {BehaviorSubject, Observable, Subscription} from 'rxjs'; import {filter, map, shareReplay} from 'rxjs/operators'; import {PickOutService} from '../../../modules/pick-out/pick-out.service'; import {IBrickDefinition} from '../../model/interfaces/brick-definition.interface'; import {IWallModel} from '../../model/interfaces/wall-model.interface'; import {DEFAULT_BRICK, ITransactionMetadataItem} from '../../plugins/core2/wall-core.plugin2'; import {BrickRegistry} from '../../registry/brick-registry.service'; import {IWallUiApi} from './interfaces/ui-api.interface'; import {IFocusContext} from './interfaces/wall-component/wall-component-focus-context.interface'; /* * Related to mode stale data. * I could not remove mode (edit/navigation) completely when they are inactive. * It would be hard to manage wall-canvas subscription in that case. * One way to leave the public api but it the state should be fulfilled somewhere deeper as I * implemented in cinatabase. */ export const WALL_VIEW_API = 'ui'; export type IWallViewPlan = IViewBrickDefinition[]; export interface IViewBrickDefinition { brick: IBrickDefinition; component: any; // UI component } export enum VIEW_MODE { EDIT = 'EDIT', NAVIGATION = 'NAVIGATION', } /** May contains stale data pointing to the bricks which are not exists anymore in the plan! * Ideally that class should be deleted after mode switches to EDIT. That would automatically * erase any stale data. * todo: need to refactoring mode so they would always contains appropriate data! */ export class NavigationMode { // todo: why do we need it name = VIEW_MODE.NAVIGATION; private cursorPositionInternal$: BehaviorSubject<string> = new BehaviorSubject(null); get cursorPosition() { return this.cursorPositionInternal$.getValue(); } cursorPosition$ = this.cursorPositionInternal$.asObservable(); private selectedBricksInternal$: BehaviorSubject<string[]> = new BehaviorSubject([]); selectedBricks$ = this.selectedBricksInternal$.asObservable().pipe( shareReplay(1) ); get selectedBricks() { return this.selectedBricksInternal$.getValue(); } constructor(private wallViewModel: WallViewModel) { } // called when mode is activated onActivated(brickIdToFocus?: string) { this.unSelectAllBricks(); if (brickIdToFocus) { this.setCursorTo(brickIdToFocus); } } // called when mode is de-activated onDeActivated() { this.unSelectAllBricks(); } /** Switch brick selection for cursor. */ switchBrickSelection() { if (this.selectedBricks.includes(this.cursorPosition)) { this.removeBrickFromSelection(this.cursorPosition); } else { this.addBrickToSelection(this.cursorPosition); } } setCursorTo(brickId: string) { this.cursorPositionInternal$.next(brickId); } moveCursorToPreviousBrick() { const currentCursor = this.cursorPositionInternal$.getValue(); const previousBrickId = this.wallViewModel.wallModel.api.core2.getPreviousBrickId(currentCursor); if (previousBrickId) { this.cursorPositionInternal$.next(previousBrickId); } } moveCursorToNextBrick() { const currentCursor = this.cursorPositionInternal$.getValue(); const nextBrickId = this.wallViewModel.wallModel.api.core2.getNextBrickId(currentCursor); if (nextBrickId) { this.cursorPositionInternal$.next(nextBrickId); } } /** Performs primary action for the brick which cursor is pointed. */ callBrickPrimaryAction() { this.wallViewModel.callBrickPrimaryAction(this.cursorPositionInternal$.getValue(), { selectedBrickIds: this.selectedBricks }); } // SELECTION selectBrick(brickId: string): void { this.selectedBricksInternal$.next([brickId]); } selectBricks(brickIds: string[]) { if (JSON.stringify(brickIds) !== JSON.stringify(this.selectedBricks)) { const sortedBrickIds = this.wallViewModel.wallModel.api.core2.sortBrickIdsByLayoutOrder(brickIds); this.selectedBricksInternal$.next(sortedBrickIds); this.cursorPositionInternal$.next(sortedBrickIds[0]); } } addBrickToSelection(brickId: string): void { const selectedBrickIds = this.selectedBricks.slice(0); selectedBrickIds.push(brickId); this.selectedBricksInternal$.next( this.wallViewModel.wallModel.api.core2.sortBrickIdsByLayoutOrder(selectedBrickIds) ); } removeBrickFromSelection(brickId: string): void { const brickIdIndex = this.selectedBricks.indexOf(brickId); this.selectedBricksInternal$.next( [ ...this.selectedBricks.slice(0, brickIdIndex), ...this.selectedBricks.slice(brickIdIndex + 1) ] ); } unSelectAllBricks(): void { this.selectedBricksInternal$.next([]); } getSelectedBrickIds(): string[] { return this.selectedBricks; } moveBricksBelow() { if (this.wallViewModel.mode.currentMode !== VIEW_MODE.NAVIGATION) { console.warn(`Can move brick below only in ${VIEW_MODE.NAVIGATION} mode.`); return; } const movedBricks = this.selectedBricks.length ? this.selectedBricks : [this.cursorPosition]; this.wallViewModel.wallModel.api.core2.moveBricksBelow(movedBricks, disableViewTransactionProcessing); } moveBricksAbove() { if (this.wallViewModel.mode.currentMode !== VIEW_MODE.NAVIGATION) { console.warn(`Can move brick above only in ${VIEW_MODE.NAVIGATION} mode.`); return; } const movedBricks = this.selectedBricks.length ? this.selectedBricks : [this.cursorPosition]; this.wallViewModel.wallModel.api.core2.moveBricksAbove(movedBricks, disableViewTransactionProcessing); } } export interface IFocusedBrick { // todo: rename to brickId id: string; context?: IFocusContext; } /** May contains stale data pointing to the bricks which are not exists anymore in the plan! * Ideally that class should be deleted after mode switches to NAVIGATION. That would automatically * erase any stale data. * todo: need to refactoring mode so they would always contains appropriate data! */ export class EditMode { name = VIEW_MODE.EDIT; private focusedBrickInternal$: BehaviorSubject<IFocusedBrick | null> = new BehaviorSubject(null); get focusedBrick() { return this.focusedBrickInternal$.getValue(); } constructor(private wallViewModel: WallViewModel) { } // called when mode is activated onActivate(brickId?: string) { if (brickId) { this.focusOnBrickId(brickId); } } // called when mode is de-activated (switched to navigation mode) onDeActivate() { // do nothing for now } focusOnBrickId(brickId: string, focusContext?: IFocusContext) { this.focusedBrickInternal$.next({ id: brickId, context: focusContext, }); this.wallViewModel.callBrickFocusOnAction(brickId, focusContext); } focusOnNextTextBrick(brickId: string, focusContext?: IFocusContext) { const nextTextBrickId = this.wallViewModel.wallModel.api.core2.getNextTextBrickId(brickId); if (nextTextBrickId) { this.focusOnBrickId(nextTextBrickId, focusContext); } } focusOnPreviousTextBrick(brickId: string, focusContext?: IFocusContext) { const previousTextBrickId = this.wallViewModel.wallModel.api.core2.getPreviousTextBrickId(brickId); if (previousTextBrickId) { this.focusOnBrickId(previousTextBrickId, focusContext); } } setFocusedBrickId(brickId: string) { this.focusedBrickInternal$.next({ id: brickId, context: null }); } } export class Mode { private currentModeInternal$: BehaviorSubject<VIEW_MODE> = new BehaviorSubject(VIEW_MODE.EDIT); currentMode$: Observable<VIEW_MODE> = this.currentModeInternal$.asObservable(); get currentMode() { return this.currentModeInternal$.getValue(); } edit: EditMode = new EditMode(this.wallViewModel); navigation: NavigationMode = new NavigationMode(this.wallViewModel); constructor(private wallViewModel: WallViewModel) { } switchMode() { if (this.currentMode === VIEW_MODE.EDIT) { this.switchToNavigationMode(); } else { this.switchToEditMode(); } } switchToEditMode(focusToBrick: boolean = true) { if (this.currentMode === VIEW_MODE.EDIT) { // todo: replace it and other warn in form of assert? console.warn(`${VIEW_MODE.EDIT} mode is already active.`); return; } this.currentModeInternal$.next(VIEW_MODE.EDIT); let focusToBrickId; if (focusToBrick) { if (this.wallViewModel.wallModel.api.core2.query().hasBrick(this.navigation.cursorPosition)) { focusToBrickId = this.navigation.cursorPosition; } else { focusToBrickId = this.wallViewModel.wallModel.api.core2.query().brickIdBasedOnPosition(0); } } // De-activate navigation mode this.navigation.onDeActivated(); // De-activate edit mode this.edit.onActivate(focusToBrickId); } switchToNavigationMode() { (document.activeElement as HTMLElement).blur(); this.currentModeInternal$.next(VIEW_MODE.NAVIGATION); // try to set cursor position let brickIdToFocus: string; const focusedBrick = this.edit.focusedBrick; if (focusedBrick && focusedBrick.id && this.wallViewModel.wallModel.api.core2.query().hasBrick(focusedBrick.id)) { brickIdToFocus = focusedBrick.id; } else { brickIdToFocus = this.wallViewModel.wallModel.api.core2.query().brickIdBasedOnPosition(0); } // De-activate edit mode this.edit.onDeActivate(); // Activate navigation mode this.navigation.onActivated(brickIdToFocus); } } export class MediaInteraction { private isMediaInteractionEnabledInternal$ = new BehaviorSubject<boolean>(true); isMediaInteractionEnabled$ = this.isMediaInteractionEnabledInternal$.asObservable(); enable() { this.isMediaInteractionEnabledInternal$.next(true); } disable() { this.isMediaInteractionEnabledInternal$.next(false); } } // Defines what would be exposed as an public API class WallViewApi implements IWallUiApi { mediaInteraction = this.wallViewModel.mediaInteraction; mode = this.wallViewModel.mode; constructor(private wallViewModel: WallViewModel) { } } class BrickComponent { constructor(readonly brickId: string, private brickComponentRef: ComponentRef<any>) { } isSupportApi(apiName: string) { return Boolean(this.brickComponentRef.instance[apiName]); } onWallFocus(context: IFocusContext) { this.call('onWallFocus', context); } onPrimaryAction(options: IPrimaryActionOption) { this.call('onPrimaryAction', options); } private call(apiName: string, data: any) { if (!this.isSupportApi(apiName)) { console.warn(`Brick "${this.brickId}" does not support "${apiName}" api.`); return; } this.brickComponentRef.instance[apiName](data); } } class BrickComponentsStorage { private componentRefs: Map<string, BrickComponent> = new Map(); get(brickId: string) { return this.componentRefs.get(brickId); } register(brickId: string, brickComponentRef: ComponentRef<any>) { if (this.componentRefs.has(brickId)) { console.warn(`Register duplicate`); } this.componentRefs.set(brickId, new BrickComponent(brickId, brickComponentRef)); } unRegister(brickId: string) { this.componentRefs.delete(brickId); } } export interface IPrimaryActionOption { selectedBrickIds: string[]; } export const disableViewTransactionProcessing: ITransactionMetadataItem = { key: 'disableTransactionProcessing', value: true }; @Injectable() export class WallViewModel { wallModel: IWallModel = null; mediaInteraction = new MediaInteraction(); viewPlan$: Observable<IWallViewPlan>; mode: Mode; brickComponentsStorage = new BrickComponentsStorage(); private wallModelSubscription: Subscription; constructor(private brickRegistry: BrickRegistry, private pickOutService: PickOutService) { } // called by Wall component initialize(wallModel: IWallModel) { this.wallModel = wallModel; this.mode = new Mode(this); // register methods on model itself this.wallModel.registerApi(WALL_VIEW_API, new WallViewApi(this)); // todo-refactoring: fix subscription this.wallModelSubscription = this.wallModel.api.core2.events$.subscribe((event) => { // todo: event changes should have more friendly API, // replace from array to some custom class if (event.transaction.change.turned && event.transaction.change.turned.length) { // wait till component will be rendered // todo: ideally we have to wait (using observable) rendering process // and focus on brick setTimeout(() => { this.mode.edit.focusOnBrickId(event.transaction.change.turned[0].brickId); }); } }); // default behaviour after brick were REMOVED from the model // client could disable it adding appropriate metadata to the transaction this.wallModel.api.core2.events$.pipe( filter((event) => { return !event.transaction.metadata.has(disableViewTransactionProcessing.key); }), filter((event) => { return Boolean(event.transaction.change.removed.length); }), ).subscribe((event) => { this.mode.switchToEditMode(false); let brickIdToFocus; if (!this.wallModel.api.core2.query().length()) { const {id} = this.wallModel.api.core2.addDefaultBrick(); brickIdToFocus = id; } else { const removedChangeWithNearestBrickId = event.transaction.change.removed.reverse() .find((removedChange) => { return Boolean(removedChange.nearestBrickId); }); brickIdToFocus = removedChangeWithNearestBrickId.nearestBrickId; } // wait until view re-rendered setTimeout(() => { this.mode.edit.focusOnBrickId(brickIdToFocus); }); }); // default behaviour after brick were MOVED from the model // client could disable it adding appropriate metadata to the transaction this.wallModel.api.core2.events$.pipe( filter((event) => { return !event.transaction.metadata.has(disableViewTransactionProcessing.key); }), filter((event) => { return Boolean(event.transaction.change.moved.length); }), ).subscribe((event) => { this.mode.switchToEditMode(false); const movedTextBrick = event.transaction.change.moved.filter((movedBrickId) => { return this.wallModel.api.core2.query().tagByBrickId(movedBrickId) === DEFAULT_BRICK; }); if (movedTextBrick.length) { const sortedMovedTextBrick = this.wallModel.api.core2.query().sortBrickIdsByLayoutOrder(movedTextBrick); // wait until view re-rendered setTimeout(() => { this.mode.edit.focusOnBrickId(sortedMovedTextBrick[0]); }); } }); this.viewPlan$ = this.wallModel.api.core2.plan$.pipe( map((plan) => { const viewPlan = plan.map((brick) => { return { brick, component: this.brickRegistry.get(brick.tag).component }; }); return viewPlan; }) ); // disable pick out functionality in read-only mode this.wallModel.api.core2.isReadOnly$.subscribe((isReadOnly) => { if (isReadOnly) { this.pickOutService.disablePickOut(); } else { this.pickOutService.enablePickOut(); } }); } callBrickFocusOnAction(brickId: string, focusContext?: IFocusContext) { if (this.mode.currentMode !== VIEW_MODE.EDIT) { console.warn(`Can focus to "${brickId}" only on ${VIEW_MODE.EDIT} mode.`); return; } this.brickComponentsStorage.get(brickId).onWallFocus(focusContext); } callBrickPrimaryAction(brickId: string, options: IPrimaryActionOption) { if (this.mode.currentMode !== VIEW_MODE.NAVIGATION) { console.warn(`Can execute primary action for "${brickId}" only in ${VIEW_MODE.NAVIGATION} mode.`); return; } if (!this.wallModel.api.core2.query().hasBrick(brickId)) { console.warn(`Cannot execute primary action for "${brickId}" brick. It does not exists on wall.`); return; } const brickComponent = this.brickComponentsStorage.get(brickId); brickComponent.onPrimaryAction(options); const isSetFocusSwitchingToEditMode = !brickComponent.isSupportApi('onPrimaryAction'); this.mode.switchToEditMode(isSetFocusSwitchingToEditMode); // set focus silently (do not call brick component onWallFocus callback) if (!isSetFocusSwitchingToEditMode) { this.mode.edit.setFocusedBrickId(brickId); } } onCanvasClick() { const lastBrick = this.wallModel.api.core2.query().lastBrick(); if (lastBrick && lastBrick.tag === 'text' && !lastBrick.data.text) { this.mode.edit.focusOnBrickId(lastBrick.id); return; } const {id} = this.wallModel.api.core2.addDefaultBrick(); setTimeout(() => { this.mode.edit.focusOnBrickId(id); }); } // canvas interaction onBrickStateChanged(brickId: string, brickState: any): void { this.wallModel.api.core2.updateBrickState(brickId, brickState); } reset() { this.wallModelSubscription.unsubscribe(); this.wallModelSubscription = null; this.mode.navigation.unSelectAllBricks(); } }
the_stack
import { NULL_ADDRESS } from '@celo/base/lib/address' import { assertRevert, assertSameAddress } from '@celo/protocol/lib/test-utils' import BigNumber from 'bignumber.js' import { AddressSortedLinkedListWithMedianTestContract, AddressSortedLinkedListWithMedianTestInstance, } from 'types' const AddressSortedLinkedListWithMedianTest: AddressSortedLinkedListWithMedianTestContract = artifacts.require( 'AddressSortedLinkedListWithMedianTest' ) // @ts-ignore // TODO(mcortesi): Use BN AddressSortedLinkedListWithMedianTest.numberFormat = 'BigNumber' // TODO(asa): Test tail stuff contract('AddressSortedLinkedListWithMedianTest', (accounts: string[]) => { let addressSortedLinkedListWithMedianTest: AddressSortedLinkedListWithMedianTestInstance beforeEach(async () => { addressSortedLinkedListWithMedianTest = await AddressSortedLinkedListWithMedianTest.new() }) describe('#insert()', () => { const key = accounts[9] const numerator = 2 it('should add a single element to the list', async () => { await addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) assert.isTrue(await addressSortedLinkedListWithMedianTest.contains(key)) const [keys, numerators] = await addressSortedLinkedListWithMedianTest.getElements() assert.equal(keys.length, 1) assert.equal(numerators.length, 1) assert.equal(keys[0], key) assert.equal(numerators[0].toNumber(), numerator) }) it('should increment numElements', async () => { await addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) assert.equal((await addressSortedLinkedListWithMedianTest.getNumElements()).toNumber(), 1) }) it('should update the head', async () => { await addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) assert.equal(await addressSortedLinkedListWithMedianTest.head(), key) }) it('should update the tail', async () => { await addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) assert.equal(await addressSortedLinkedListWithMedianTest.tail(), key) }) it('should update the median', async () => { await addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) assert.equal(await addressSortedLinkedListWithMedianTest.medianKey(), key) }) it('should revert if key is 0', async () => { await assertRevert( addressSortedLinkedListWithMedianTest.insert( NULL_ADDRESS, numerator, NULL_ADDRESS, NULL_ADDRESS ) ) }) it('should revert if lesser is equal to key', async () => { await assertRevert( addressSortedLinkedListWithMedianTest.insert(key, numerator, key, NULL_ADDRESS) ) }) it('should revert if greater is equal to key', async () => { await assertRevert( addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, key) ) }) describe('when an element is already in the list', () => { beforeEach(async () => { await addressSortedLinkedListWithMedianTest.insert( key, numerator, NULL_ADDRESS, NULL_ADDRESS ) }) it('should revert when inserting an element already in the list', async () => { await assertRevert( addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) ) }) }) }) describe('#update()', () => { const key = accounts[9] const numerator = 2 const newNumerator = 3 beforeEach(async () => { await addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) }) it('should update the value for an existing element', async () => { await addressSortedLinkedListWithMedianTest.update( key, newNumerator, NULL_ADDRESS, NULL_ADDRESS ) assert.isTrue(await addressSortedLinkedListWithMedianTest.contains(key)) const [keys, numerators] = await addressSortedLinkedListWithMedianTest.getElements() assert.equal(keys.length, 1) assert.equal(numerators.length, 1) assert.equal(keys[0], key) assert.equal(numerators[0].toNumber(), newNumerator) }) it('should revert if the key is not in the list', async () => { await assertRevert( addressSortedLinkedListWithMedianTest.update( accounts[8], newNumerator, NULL_ADDRESS, NULL_ADDRESS ) ) }) it('should revert if lesser is equal to key', async () => { await assertRevert( addressSortedLinkedListWithMedianTest.update(key, newNumerator, key, NULL_ADDRESS) ) }) it('should revert if greater is equal to key', async () => { await assertRevert( addressSortedLinkedListWithMedianTest.update(key, newNumerator, NULL_ADDRESS, key) ) }) }) describe('#remove()', () => { const key = accounts[9] const numerator = 2 beforeEach(async () => { await addressSortedLinkedListWithMedianTest.insert(key, numerator, NULL_ADDRESS, NULL_ADDRESS) }) it('should remove the element from the list', async () => { await addressSortedLinkedListWithMedianTest.remove(key) assert.isFalse(await addressSortedLinkedListWithMedianTest.contains(key)) }) it('should decrement numElements', async () => { await addressSortedLinkedListWithMedianTest.remove(key) assert.equal((await addressSortedLinkedListWithMedianTest.getNumElements()).toNumber(), 0) }) it('should update the head', async () => { await addressSortedLinkedListWithMedianTest.remove(key) assert.equal(await addressSortedLinkedListWithMedianTest.head(), NULL_ADDRESS) }) it('should update the tail', async () => { await addressSortedLinkedListWithMedianTest.remove(key) assert.equal(await addressSortedLinkedListWithMedianTest.tail(), NULL_ADDRESS) }) it('should update the median', async () => { await addressSortedLinkedListWithMedianTest.remove(key) assert.equal(await addressSortedLinkedListWithMedianTest.medianKey(), NULL_ADDRESS) }) it('should revert if the key is not in the list', async () => { await assertRevert(addressSortedLinkedListWithMedianTest.remove(accounts[8])) }) }) describe('when there are multiple inserts, updates, and removals', () => { interface SortedElement { key: string numerator: BigNumber } enum SortedListActionType { Update = 1, Remove, Insert, } interface SortedListAction { actionType: SortedListActionType element: SortedElement } const randomElement = <A>(list: A[]): A => { return list[Math.floor(BigNumber.random().times(list.length).toNumber())] } const randomElementOrNullAddress = (list: string[]): string => { if (BigNumber.random().isLessThan(0.5)) { return NULL_ADDRESS } else { return randomElement(list) } } const makeActionSequence = (length: number, numKeys: number): SortedListAction[] => { const sequence: SortedListAction[] = [] const listKeys: Set<string> = new Set([]) // @ts-ignore const keyOptions = Array.from({ length: numKeys }, () => web3.utils.randomHex(20).toLowerCase() ) for (let i = 0; i < length; i++) { const key = randomElement(keyOptions) let action: SortedListActionType if (listKeys.has(key)) { action = randomElement([SortedListActionType.Update, SortedListActionType.Remove]) if (action === SortedListActionType.Remove) { listKeys.delete(key) } } else { action = SortedListActionType.Insert listKeys.add(key) } sequence.push({ actionType: action, element: { key, numerator: BigNumber.random(20).shiftedBy(20), }, }) } return sequence } const parseElements = (keys: string[], numerators: BigNumber[]): SortedElement[] => keys.map((key, i) => ({ key: key.toLowerCase(), numerator: numerators[i], })) const assertSorted = (elements: SortedElement[]) => { for (let i = 0; i < elements.length; i++) { if (i > 0) { assert.isTrue(elements[i].numerator.lte(elements[i - 1].numerator), 'Elements not sorted') } } } const assertRelations = ( elements: SortedElement[], relations: BigNumber[], medianIndex: number ) => { const MedianRelationEnum = { Undefined: 0, Lesser: 1, Greater: 2, Equal: 3, } for (let i = 0; i < elements.length; i++) { if (i < medianIndex) { assert.equal(relations[i].toNumber(), MedianRelationEnum.Greater) } else if (i === medianIndex) { assert.equal(relations[i].toNumber(), MedianRelationEnum.Equal) } else { assert.equal(relations[i].toNumber(), MedianRelationEnum.Lesser) } } } const assertSortedFractionListInvariants = async ( elementsPromise: Promise<[string[], BigNumber[], BigNumber[]]>, numElementsPromise: Promise<BigNumber>, medianPromise: Promise<string>, expectedKeys: Set<string> ) => { const [keys, numerators, relations] = await elementsPromise const elements = parseElements(keys, numerators) assert.equal( (await numElementsPromise).toNumber(), expectedKeys.size, 'Incorrect number of elements' ) assert.deepEqual( elements.map((x) => x.key).sort(), Array.from(expectedKeys.values()).sort(), 'keys do not match' ) assertSorted(elements) let expectedMedianKey = NULL_ADDRESS let medianIndex = 0 if (elements.length > 0) { medianIndex = Math.floor((elements.length - 1) / 2) expectedMedianKey = elements[medianIndex].key } assertSameAddress(await medianPromise, expectedMedianKey, 'Incorrect median element') assertRelations(elements, relations, medianIndex) } const doActionsAndAssertInvariants = async ( numActions: number, numKeys: number, getLesserAndGreater: (element: SortedElement) => Promise<{ lesser: string; greater: string }>, allowFailingTx: boolean = false ) => { const sequence = makeActionSequence(numActions, numKeys) const listKeys: Set<string> = new Set([]) let successes = 0 for (let i = 0; i < numActions; i++) { const action = sequence[i] try { if (action.actionType === SortedListActionType.Remove) { await addressSortedLinkedListWithMedianTest.remove(action.element.key) listKeys.delete(action.element.key) } else { const { lesser, greater } = await getLesserAndGreater(action.element) if (action.actionType === SortedListActionType.Insert) { await addressSortedLinkedListWithMedianTest.insert( action.element.key, action.element.numerator, lesser, greater ) listKeys.add(action.element.key) } else if (action.actionType === SortedListActionType.Update) { await addressSortedLinkedListWithMedianTest.update( action.element.key, action.element.numerator, lesser, greater ) } } successes += 1 } catch (e) { if (!allowFailingTx) { throw new Error(e) } } await assertSortedFractionListInvariants( addressSortedLinkedListWithMedianTest.getElements(), addressSortedLinkedListWithMedianTest.getNumElements(), addressSortedLinkedListWithMedianTest.medianKey(), listKeys ) } if (allowFailingTx) { const expectedSuccessRate = 2.0 / numKeys assert.isAtLeast(successes / numActions, expectedSuccessRate * 0.75) } } it('should maintain invariants when lesser, greater are correct', async () => { const numActions = 100 const numKeys = 20 const getLesserAndGreater = async (element: SortedElement) => { const [keys, numerators] = await addressSortedLinkedListWithMedianTest.getElements() const elements = parseElements(keys, numerators) let lesser = NULL_ADDRESS let greater = NULL_ADDRESS const value = element.numerator // Iterate from each end of the list towards the other end, saving the key with the // smallest value >= `value` and the key with the largest value <= `value`. for (let i = 0; i < elements.length; i++) { if (elements[i].key !== element.key.toLowerCase()) { if (elements[i].numerator.gte(value)) { greater = elements[i].key } } const j = elements.length - i - 1 if (elements[j].key !== element.key.toLowerCase()) { if (elements[j].numerator.lte(value)) { lesser = elements[j].key } } } return { lesser, greater } } await doActionsAndAssertInvariants(numActions, numKeys, getLesserAndGreater) }) it('should maintain invariants when lesser, greater are incorrect', async () => { const numReports = 200 const numKeys = 20 const getRandomKeys = async () => { let lesser = NULL_ADDRESS let greater = NULL_ADDRESS const [keys, , ,] = await addressSortedLinkedListWithMedianTest.getElements() if (keys.length > 0) { lesser = randomElementOrNullAddress(keys) greater = randomElementOrNullAddress(keys) } return { lesser, greater } } await doActionsAndAssertInvariants(numReports, numKeys, getRandomKeys, true) }) }) })
the_stack
import * as d3 from "d3"; import * as Animators from "../animators"; import { IAnimator } from "../animators/animator"; import { Dataset } from "../core/dataset"; import { AttributeToProjector, IAccessor, Point, Projector, SimpleSelection } from "../core/interfaces"; import { memThunk, Thunk } from "../memoize/index"; import { QuantitativeScale } from "../scales/quantitativeScale"; import { Scale } from "../scales/scale"; import * as Utils from "../utils"; import * as Plots from "./"; import { Area } from "./areaPlot"; import { Plot } from "./plot"; export class StackedArea<X> extends Area<X> { private _stackingOrder: Utils.Stacking.IStackingOrder; private _stackingResult: Thunk<Utils.Stacking.StackingResult> = memThunk( () => this.datasets(), () => this.x().accessor, () => this.y().accessor, () => this._stackingOrder, (datasets, keyAccessor, valueAccessor, stackingOrder) => { return Utils.Stacking.stack(datasets, keyAccessor, valueAccessor, stackingOrder); }, ); private _stackedExtent: Thunk<number[]> = memThunk( this._stackingResult, () => this.x().accessor, () => this._filterForProperty("y"), (stackingResult, keyAccessor, filter) => { return Utils.Stacking.stackedExtent(stackingResult, keyAccessor, filter); }, ); private _baseline: SimpleSelection<void>; private _baselineValue = 0; private _baselineValueProvider: () => number[]; /** * @constructor */ constructor() { super(); this._stackingOrder = "bottomup"; this.addClass("stacked-area-plot"); this._baselineValueProvider = () => [this._baselineValue]; this.croppedRenderingEnabled(false); } public croppedRenderingEnabled(): boolean; public croppedRenderingEnabled(croppedRendering: boolean): this; public croppedRenderingEnabled(croppedRendering?: boolean): any { if (croppedRendering == null) { return super.croppedRenderingEnabled(); } if (croppedRendering) { // HACKHACK #3032: cropped rendering doesn't currently work correctly on StackedArea Utils.Window.warn("Warning: Stacked Area Plot does not support cropped rendering."); return this; } return super.croppedRenderingEnabled(croppedRendering); } protected _getAnimator(key: string): IAnimator { return new Animators.Null(); } protected _setup() { super._setup(); this._baseline = this._renderArea.append("line").classed("baseline", true); } public x(): Plots.ITransformableAccessorScaleBinding<X, number>; public x(x: number | IAccessor<number>): this; public x(x: X | IAccessor<X>, xScale: Scale<X, number>): this; public x(x?: number | IAccessor<number> | X | IAccessor<X>, xScale?: Scale<X, number>): any { if (x == null) { return super.x(); } if (xScale == null) { super.x(<number | IAccessor<number>> x); } else { super.x(<X | IAccessor<X>> x, xScale); } this._checkSameDomain(); return this; } public y(): Plots.ITransformableAccessorScaleBinding<number, number>; public y(y: number | IAccessor<number>): this; public y(y: number | IAccessor<number>, yScale: QuantitativeScale<number>): this; public y(y?: number | IAccessor<number>, yScale?: QuantitativeScale<number>): any { if (y == null) { return super.y(); } if (yScale == null) { super.y(<number | IAccessor<number>> y); } else { super.y(<number | IAccessor<number>> y, yScale); } this._checkSameDomain(); return this; } /** * Gets the offset of the y value corresponding to an x value of a given dataset. This allows other plots to plot * points corresponding to their stacked value in the graph. * @param dataset The dataset from which to retrieve the y value offset * @param x The x value corresponding to the y-value of interest. */ public yOffset(dataset: Dataset, x: any): number { const stackingResult = this._stackingResult(); if (stackingResult == null) { return undefined; } const datasetStackingResult = stackingResult.get(dataset); if (datasetStackingResult == null) { return undefined; } const result = datasetStackingResult.get(String(x)); if (result == null) { return undefined; } return result.offset; } /** * Gets the stacking order of the plot. */ public stackingOrder(): Utils.Stacking.IStackingOrder; /** * Sets the stacking order of the plot. * * By default, stacked plots are "bottomup", meaning for positive data, the * first series will be placed at the bottom of the scale and subsequent * data series will by stacked on top. This can be reveresed by setting * stacking order to "topdown". * * @returns {Plots.StackedArea} This plot */ public stackingOrder(stackingOrder: Utils.Stacking.IStackingOrder): this; public stackingOrder(stackingOrder?: Utils.Stacking.IStackingOrder): any { if (stackingOrder == null) { return this._stackingOrder; } this._stackingOrder = stackingOrder; this._onDatasetUpdate(); return this; } /** * Gets if downsampling is enabled * * When downsampling is enabled, two consecutive lines with the same slope will be merged to one line. */ public downsamplingEnabled(): boolean; /** * Sets if downsampling is enabled * * For now, downsampling is always disabled in stacked area plot * @returns {Plots.StackedArea} The calling Plots.StackedArea */ public downsamplingEnabled(downsampling: boolean): this; public downsamplingEnabled(downsampling?: boolean): any { if (downsampling == null) { return super.downsamplingEnabled(); } Utils.Window.warn("Warning: Stacked Area Plot does not support downsampling"); return this; } protected _additionalPaint() { const scaledBaseline = this.y().scale.scale(this._baselineValue); const baselineAttr: any = { x1: 0, y1: scaledBaseline, x2: this.width(), y2: scaledBaseline, }; this._getAnimator("baseline").animate(this._baseline, baselineAttr); } protected _updateYScale() { const yBinding = this.y(); const scale = <QuantitativeScale<any>> (yBinding && yBinding.scale); if (scale == null) { return; } scale.addPaddingExceptionsProvider(this._baselineValueProvider); scale.addIncludedValuesProvider(this._baselineValueProvider); } protected _onDatasetUpdate() { this._checkSameDomain(); super._onDatasetUpdate(); return this; } protected getExtentsForProperty(attr: string) { const primaryAttr = "y"; if (attr === primaryAttr) { return [this._stackedExtent()]; } else { return super.getExtentsForProperty(attr); } } private _checkSameDomain() { if (!this._projectorsReady()) { return; } const datasets = this.datasets(); const keyAccessor = this.x().accessor; const keySets = datasets.map((dataset) => { return d3.set(dataset.data().map((datum, i) => Utils.Stacking.normalizeKey(keyAccessor(datum, i, dataset)))).values(); }); const domainKeys = StackedArea._domainKeys(datasets, keyAccessor); if (keySets.some((keySet) => keySet.length !== domainKeys.length)) { Utils.Window.warn("the domains across the datasets are not the same. Plot may produce unintended behavior."); } } /** * Given an array of Datasets and the accessor function for the key, computes the * set reunion (no duplicates) of the domain of each Dataset. The keys are stringified * before being returned. * * @param {Dataset[]} datasets The Datasets for which we extract the domain keys * @param {Accessor<any>} keyAccessor The accessor for the key of the data * @return {string[]} An array of stringified keys */ private static _domainKeys(datasets: Dataset[], keyAccessor: IAccessor<any>) { const domainKeys = d3.set(); datasets.forEach((dataset) => { const data = dataset.data(); const dataLen = data.length; for (let index = 0; index < dataLen; index++) { const datum = data[index]; domainKeys.add(keyAccessor(datum, index, dataset)); } }); return domainKeys.values(); } protected _coordinateProjectors(): [Projector, Projector, Projector] { const xProjector = Plot._scaledAccessor(this.x()); const yAccessor = this.y().accessor; const xAccessor = this.x().accessor; const normalizedXAccessor = (datum: any, index: number, dataset: Dataset) => { return Utils.Stacking.normalizeKey(xAccessor(datum, index, dataset)); }; const stackingResult = this._stackingResult(); const stackYProjector = (d: any, i: number, dataset: Dataset) => { const y = +yAccessor(d, i, dataset); const { offset } = stackingResult.get(dataset).get(normalizedXAccessor(d, i, dataset)); return this.y().scale.scale(y + offset); }; const stackY0Projector = (d: any, i: number, dataset: Dataset) => { const { offset } = stackingResult.get(dataset).get(normalizedXAccessor(d, i, dataset)); return this.y().scale.scale(offset); }; return [ xProjector, stackYProjector, stackY0Projector, ]; } protected _propertyProjectors(): AttributeToProjector { const propertyToProjectors = super._propertyProjectors(); const [ xProjector, stackYProjector, stackY0Projector ] = this._coordinateProjectors(); propertyToProjectors["d"] = this._constructAreaProjector(xProjector, stackYProjector, stackY0Projector); return propertyToProjectors; } protected _pixelPoint(datum: any, index: number, dataset: Dataset): Point { const pixelPoint = super._pixelPoint(datum, index, dataset); const xValue = this.x().accessor(datum, index, dataset); const yValue = this.y().accessor(datum, index, dataset); const scaledYValue = this.y().scale.scale(+yValue + this._stackingResult().get(dataset).get(Utils.Stacking.normalizeKey(xValue)).offset); return { x: pixelPoint.x, y: scaledYValue }; } }
the_stack
import React, { useState, useRef, useEffect } from 'react'; import { TextInput, Surface, Divider, HelperText, Searchbar, Caption, Chip, Text, Avatar, Provider as PaperProvider, useTheme, } from 'react-native-paper'; import { View, Dimensions, Platform, FlatList, ActivityIndicator, // ScrollView, } from 'react-native'; import Modal from 'react-native-modal'; import Lo from 'lodash'; import MultiselectItem from '../Components/MultiselectItem'; import { colors as ConsColors, defaultDropdownProps, ITEMLAYOUT, } from '../constants'; import type { IDropdownData, IMultiselectDropdownProps } from '../types'; import styles from '../styles'; import { deviceWidth, deviceHeight } from '../util'; import EmptyList from '../Components/EmptyList'; import PressableTouch from '../Components/PressableTouch'; // const theme = { // ...DefaultTheme, // roundness: 2, // colors: { // ...DefaultTheme.colors, // colors: { // primary: '#6200ee', // accent: '#03dac4', // background: '#f6f6f6', // surface: '#FFFFFF', // error: '#B00020', // text: '#000000', // onBackground: '#000000', // onSurface: '#000000', // placeholder: 'rgba(0,0,0,0.54)', // disabled: 'rgba(0,0,0,0.26)', // }, // }, // dark: true, // }; const defaultAvatar = require('../assets/ddicon.png'); const MultiselectDropdown: React.FC<IMultiselectDropdownProps> = props => { const { error, value, label, required, disabled, data, onChange, floating, enableSearch, primaryColor = ConsColors.primary, elevation, borderRadius, activityIndicatorColor, searchPlaceholder, rippleColor, helperText, errorColor, itemTextStyle, itemContainerStyle, showLoader, animationIn = 'fadeIn', animationOut = 'fadeOut', supportedOrientations = ['portrait', 'landscape'], animationInTiming, animationOutTiming, parentDDContainerStyle, emptyListText, disableSort, enableAvatar, avatarSize, defaultSortOrder = 'asc', chipType = 'flat', chipTextStyle = {}, onBlur, emptySelectionText, paperTheme, textInputStyle, chipStyle = {}, mainContainerStyle, underlineColor, disableSelectionTick, selectedItemTextStyle, selectedItemViewStyle, removeLabel, mode = 'flat', selectedItemsText, disabledItemTextStyle, disabledItemViewStyle, hideChip = false, dropdownIcon = 'menu-down', dropdownIconSize = 30, itemSelectIcon, itemSelectIconSize, multiline = false, searchInputTheme, } = props; const { colors } = useTheme(); const [selectedItems, setSelectedItems] = useState<IDropdownData[]>([]); const [labelv, setLabelV] = useState<string>(''); const [isVisible, setIsVisible] = useState<boolean>(false); const [iconColor, setIconColor] = useState<string | undefined>('grey'); const [options, setOptions] = useState<IDropdownData[]>([]); const [hasError, setError] = useState<boolean>(false); const [contMeasure, setConMeasure] = useState({ vx: 0, vy: 0, vWidth: 0, vHeight: 0, }); const [dimension, setDimension] = useState({ dw: deviceWidth, dh: deviceHeight, }); const [searchQuery, setSearchQuery] = useState<string>(''); const pViewRef = useRef<View | any>(); const listRef = useRef<FlatList | any>(); useEffect(() => { Dimensions.addEventListener('change', () => { setIsVisible(false); const { width, height } = Dimensions.get('window'); setDimension({ dw: width, dh: height }); setIconColor('grey'); }); return () => { Dimensions.removeEventListener('change', () => {}); }; }, []); useEffect(() => { if (!Lo.isEmpty(data) && value) { setLabelV(`${value.length} ${selectedItemsText || 'selected'}`); setSelectedItems(Lo.filter(data, d => value.includes(d.value))); } }, [value, data, selectedItemsText]); useEffect(() => { if (value) { setLabelV(`${value.length} ${selectedItemsText || 'selected'}`); setSelectedItems(Lo.filter(data, d => value.includes(d.value))); } }, [value, data, selectedItemsText]); useEffect(() => { if (disabled) { setIconColor('lightgrey'); } }, [disabled]); useEffect(() => { if (isVisible && listRef) { listRef.current.flashScrollIndicators(); } }, [isVisible]); useEffect(() => { if (!disableSort) setOptions(Lo.orderBy(data, ['label'], [defaultSortOrder])); else setOptions(data); }, [data, disableSort, defaultSortOrder]); useEffect(() => { if (required && error) { setError(true); setIconColor(errorColor); } else { setError(false); setIconColor('grey'); } }, [required, error, errorColor]); const onTextInputFocus = () => { if (hasError) { setIconColor('red'); } else { setIconColor(primaryColor); } pViewRef.current.measureInWindow( (vx: number, vy: number, vWidth: number, vHeight: number) => { const ddTop = vy + vHeight; const bottomMetric = dimension.dh - vy; if (bottomMetric < 300) { setConMeasure({ vx, vy: ddTop - 217, vWidth, vHeight }); } else { setConMeasure({ vx, vy: ddTop, vWidth, vHeight, }); } } ); setIsVisible(true); }; const androidOnLayout = () => { if (Platform.OS === 'android') { pViewRef.current.measureInWindow( (vx: number, vy: number, vWidth: number, vHeight: number) => { const ddTop = vy + vHeight; const bottomMetric = dimension.dh - vy; if (bottomMetric < 300) { setConMeasure({ vx, vy: ddTop - 217, vWidth, vHeight }); } else { setConMeasure({ vx, vy: ddTop, vWidth, vHeight }); } } ); } }; const onModalBlur = () => { setIsVisible(false); if (hasError) { setIconColor('red'); } else { setIconColor('grey'); } if (onBlur && typeof onBlur === 'function') onBlur(); }; const handleOptionSelect = (v: string | number) => { if (onChange && typeof onChange === 'function') { if (value.includes(v)) { onChange(Lo.remove(value, s => s !== v)); } else { onChange([...value, v]); } if (hasError) { setIconColor('red'); } else { setIconColor('grey'); } } setSearchQuery(''); if (!disableSort) setOptions(Lo.orderBy(data, ['label'], [defaultSortOrder])); else setOptions(data); }; const onChangeSearch = (query: string) => { setSearchQuery(query); if (!Lo.isEmpty(data) && query) { const lFilter = data.filter(opt => opt.label .toString() .toLowerCase() .trim() .includes(query.toString().toLowerCase()) ); if (lFilter.length === 0) { setOptions([]); } else { setOptions(lFilter); } } else if (!Lo.isEmpty(data) && !query && !disableSort) { setOptions(Lo.sortBy(data, 'label')); } else setOptions(data); }; const removeChip = (rmV: string | number) => { if (!showLoader) { if (onChange && typeof onChange === 'function') { onChange(Lo.remove(value, s => s !== rmV)); } } }; const getEmptyComponent = () => { if (typeof emptyListText === 'string') return <EmptyList emptyItemMessage={emptyListText} />; else return <>{emptyListText}</>; }; const labelAction = () => { if (removeLabel) { return ''; } else { return required ? `${label}*` : label; } }; return ( <PaperProvider theme={paperTheme}> <View> <PressableTouch onPress={onTextInputFocus} disabled={disabled} rippleColor={rippleColor} > <View style={[styles.fullWidth, mainContainerStyle]} ref={pViewRef} onLayout={androidOnLayout} pointerEvents="none" > <TextInput label={labelAction()} value={labelv} style={[styles.textInput, textInputStyle]} underlineColor={underlineColor} underlineColorAndroid={underlineColor} editable={false} error={hasError} disabled={disabled} multiline={multiline} theme={{ ...searchInputTheme, colors: { primary: primaryColor, error: errorColor, }, }} right={ <TextInput.Icon name={dropdownIcon} size={dropdownIconSize} color={iconColor} /> } mode={mode} /> </View> {required && hasError ? ( <HelperText type="error" theme={{ colors: { error: errorColor } }} visible={hasError} > {helperText ? helperText : `${label} is required`} </HelperText> ) : null} </PressableTouch> {!hideChip && ( <FlatList data={selectedItems} style={styles.chipScrollView} horizontal keyExtractor={() => Math.random().toString()} renderItem={({ item }) => ( <View style={styles.chipWrapper}> <Chip mode={chipType} style={[ styles.chip, { borderColor: primaryColor, backgroundColor: chipType === 'flat' ? primaryColor : 'transparent', }, chipStyle, ]} ellipsizeMode="tail" onClose={() => removeChip(item.value)} avatar={ enableAvatar && ( <View style={styles.textView}> {item.avatarComponent ? ( item.avatarComponent ) : ( <Avatar.Image size={avatarSize} style={styles.avatarView} source={item.avatarSource || defaultAvatar} /> )} </View> ) } > <Text style={chipTextStyle}>{item.label}</Text> </Chip> </View> )} /> )} <Modal isVisible={isVisible} onBackdropPress={onModalBlur} backdropColor={floating ? 'rgba(0,0,0,0.1)' : 'transparent'} style={styles.modalStyle} animationIn={animationIn} animationOut={animationOut} animationInTiming={animationInTiming} animationOutTiming={animationOutTiming} supportedOrientations={supportedOrientations} > <View style={{ backgroundColor: colors.background, width: !floating ? contMeasure.vWidth : 'auto', left: !floating ? contMeasure.vx : 0, top: !floating ? contMeasure.vy : 100, right: 0, position: 'absolute', padding: floating ? 20 : 0, }} > <Surface style={[ styles.multiSelectSurface, parentDDContainerStyle, { elevation, borderRadius }, floating ? { maxHeight: dimension.dh / 2 } : null, ]} > {showLoader ? ( <View style={[styles.loader, { borderRadius }]}> <ActivityIndicator size="small" color={activityIndicatorColor} /> </View> ) : null} <View> {!hideChip && ( <FlatList data={selectedItems} style={styles.chipScrollView} horizontal keyExtractor={() => Math.random().toString()} renderItem={({ item }) => ( <View style={styles.chipWrapper}> <Chip mode={chipType} style={[ styles.chip, { borderColor: primaryColor, backgroundColor: chipType === 'flat' ? primaryColor : 'transparent', }, chipStyle, ]} ellipsizeMode="tail" avatar={ enableAvatar && ( <View style={styles.textView}> {item.avatarComponent ? ( item.avatarComponent ) : ( <Avatar.Image size={avatarSize} style={styles.avatarView} source={item.avatarSource || defaultAvatar} /> )} </View> ) } onClose={() => removeChip(item.value)} > <Text style={chipTextStyle}>{item.label}</Text> </Chip> </View> )} ListEmptyComponent={<Caption>{emptySelectionText}</Caption>} /> )} </View> <Divider style={styles.divider} /> <FlatList ref={listRef} data={options} initialNumToRender={25} maxToRenderPerBatch={25} persistentScrollbar scrollEnabled={!showLoader} ListHeaderComponent={ enableSearch ? ( <View> <Searchbar placeholder={searchPlaceholder} onChangeText={onChangeSearch} value={searchQuery} theme={{ colors: { primary: primaryColor } }} style={{ elevation: 0, backgroundColor: showLoader ? 'transparent' : colors.background, height: ITEMLAYOUT, }} /> <Divider style={styles.divider} /> </View> ) : null } stickyHeaderIndices={enableSearch ? [0] : undefined} renderItem={({ item }) => ( <MultiselectItem item={item} onSelect={handleOptionSelect} selected={value} selectedColor={primaryColor} itemTextStyle={itemTextStyle} itemContainerStyle={itemContainerStyle} rippleColor={rippleColor} disabled={showLoader || item?.disabled} enableAvatar={enableAvatar} avatarSize={avatarSize} disableSelectionTick={disableSelectionTick} selectedItemTextStyle={selectedItemTextStyle} selectedItemViewStyle={selectedItemViewStyle} disabledItemTextStyle={disabledItemTextStyle} disabledItemViewStyle={disabledItemViewStyle} itemSelectIcon={itemSelectIcon} itemSelectIconSize={itemSelectIconSize} /> )} keyExtractor={() => Math.random().toString()} ItemSeparatorComponent={() => ( <Divider style={styles.divider} /> )} getItemLayout={(_d, index) => ({ length: ITEMLAYOUT, offset: ITEMLAYOUT * index, index, })} ListEmptyComponent={getEmptyComponent()} /> </Surface> </View> </Modal> </View> </PaperProvider> ); }; MultiselectDropdown.defaultProps = defaultDropdownProps; export default MultiselectDropdown;
the_stack
import { renderHook } from '@testing-library/react-hooks'; import { act } from 'react-dom/test-utils'; import { mockMouseEvent, mockTouchEvent } from './utils'; import { LongPressCallback, LongPressDetectEvents, useLongPress } from '../src'; import { createMountedTestComponent, createShallowTestComponent } from './TestComponent'; describe('Check isolated hook calls', () => { test('Return empty object when callback is null', () => { const { result } = renderHook(() => useLongPress(null)); expect(result.current).toEqual({}); }); test('Return object with all handlers when callback is not null', () => { const { result } = renderHook(() => useLongPress(() => {})); expect(result.current).toMatchObject({ onMouseDown: expect.any(Function), onMouseUp: expect.any(Function), onMouseLeave: expect.any(Function), onTouchStart: expect.any(Function), onTouchEnd: expect.any(Function), }); }); test('Return appropriate handlers when called with detect param', () => { const { result: resultBoth } = renderHook(() => useLongPress(() => {}, { detect: LongPressDetectEvents.BOTH, }) ); expect(resultBoth.current).toMatchObject({ onMouseDown: expect.any(Function), onMouseUp: expect.any(Function), onMouseLeave: expect.any(Function), onTouchStart: expect.any(Function), onTouchEnd: expect.any(Function), }); const { result: resultMouse } = renderHook(() => useLongPress(() => {}, { detect: LongPressDetectEvents.MOUSE, }) ); expect(resultMouse.current).toMatchObject({ onMouseDown: expect.any(Function), onMouseUp: expect.any(Function), onMouseLeave: expect.any(Function), }); const { result: resultTouch } = renderHook(() => useLongPress(() => {}, { detect: LongPressDetectEvents.TOUCH, }) ); expect(resultTouch.current).toMatchObject({ onTouchStart: expect.any(Function), onTouchEnd: expect.any(Function), }); }); }); describe('Browser compatibility', () => { const originalWindow = { ...window.window }; // let mouseEvent: React.MouseEvent; let touchEvent: React.TouchEvent; let windowSpy: jest.MockInstance<typeof window, []>; let callback: LongPressCallback; let onStart: LongPressCallback; let onFinish: LongPressCallback; let onCancel: LongPressCallback; beforeEach(() => { // Use fake timers for detecting long press jest.useFakeTimers(); // mouseEvent = mockMouseEvent({ persist: jest.fn() }); touchEvent = mockTouchEvent({ persist: jest.fn() }); windowSpy = jest.spyOn(window, 'window', 'get'); callback = jest.fn(); onStart = jest.fn(); onFinish = jest.fn(); onCancel = jest.fn(); }); afterEach(() => { windowSpy.mockRestore(); jest.clearAllMocks(); jest.clearAllTimers(); }); test('Properly detect TouchEvent event if browser doesnt provide it', () => { windowSpy.mockImplementation( () => ({ ...originalWindow, TouchEvent: undefined, } as unknown as typeof window) ); const component = createShallowTestComponent({ callback, onStart, onFinish, onCancel, captureEvent: true, detect: LongPressDetectEvents.TOUCH, }); component.props().onTouchStart(touchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toHaveBeenCalledTimes(1); expect(callback).toHaveBeenCalledWith(touchEvent); expect(onStart).toHaveBeenCalledTimes(1); expect(onStart).toHaveBeenCalledWith(touchEvent); expect(onFinish).toHaveBeenCalledTimes(1); expect(onFinish).toHaveBeenCalledWith(touchEvent); expect(onCancel).toHaveBeenCalledTimes(0); }); }); describe('Detect long press and trigger appropriate handlers', () => { let mouseEvent: React.MouseEvent; let touchEvent: React.TouchEvent; let threshold: number; let callback: LongPressCallback; let onStart: LongPressCallback; let onFinish: LongPressCallback; let onCancel: LongPressCallback; beforeEach(() => { // Use fake timers for detecting long press jest.useFakeTimers(); // Setup common variables mouseEvent = mockMouseEvent({ persist: jest.fn() }); touchEvent = mockTouchEvent({ persist: jest.fn() }); threshold = Math.round(Math.random() * 1000); callback = jest.fn(); onStart = jest.fn(); onFinish = jest.fn(); onCancel = jest.fn(); }); afterEach(() => { jest.clearAllMocks(); jest.clearAllTimers(); }); test('Detect long press using mouse events', () => { const component = createShallowTestComponent({ callback, onStart, onFinish, onCancel, threshold, captureEvent: true, detect: LongPressDetectEvents.MOUSE, }); // -------------------------------------------------------------------------------------------------------- // Mouse down + mouse up (trigger long press) // -------------------------------------------------------------------------------------------------------- component.props().onMouseDown(mouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(mouseEvent); expect(callback).toHaveBeenCalledTimes(1); expect(callback).toHaveBeenCalledWith(mouseEvent); expect(onStart).toHaveBeenCalledTimes(1); expect(onStart).toHaveBeenCalledWith(mouseEvent); expect(onFinish).toHaveBeenCalledTimes(1); expect(onFinish).toHaveBeenCalledWith(mouseEvent); expect(onCancel).toHaveBeenCalledTimes(0); // -------------------------------------------------------------------------------------------------------- // Mouse down + mouse leave (trigger long press) // -------------------------------------------------------------------------------------------------------- jest.clearAllMocks(); component.props().onMouseDown(mouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseLeave(mouseEvent); expect(callback).toHaveBeenCalledTimes(1); expect(callback).toHaveBeenCalledWith(mouseEvent); expect(onStart).toHaveBeenCalledTimes(1); expect(onStart).toHaveBeenCalledWith(mouseEvent); expect(onFinish).toHaveBeenCalledTimes(1); expect(onFinish).toHaveBeenCalledWith(mouseEvent); expect(onCancel).toHaveBeenCalledTimes(0); // -------------------------------------------------------------------------------------------------------- // Mouse down + mouse up (cancelled long press) // -------------------------------------------------------------------------------------------------------- jest.clearAllMocks(); component.props().onMouseDown(mouseEvent); jest.advanceTimersByTime(Math.round(threshold / 2)); component.props().onMouseUp(mouseEvent); expect(callback).toHaveBeenCalledTimes(0); expect(onStart).toHaveBeenCalledTimes(1); expect(onStart).toHaveBeenCalledWith(mouseEvent); expect(onCancel).toHaveBeenCalledTimes(1); expect(onCancel).toHaveBeenCalledWith(mouseEvent); expect(onFinish).toHaveBeenCalledTimes(0); // -------------------------------------------------------------------------------------------------------- // Mouse down + mouse leave (cancelled long press) // -------------------------------------------------------------------------------------------------------- jest.clearAllMocks(); component.props().onMouseDown(mouseEvent); jest.advanceTimersByTime(Math.round(threshold / 2)); component.props().onMouseLeave(mouseEvent); expect(callback).toHaveBeenCalledTimes(0); expect(onStart).toHaveBeenCalledTimes(1); expect(onStart).toHaveBeenCalledWith(mouseEvent); expect(onCancel).toHaveBeenCalledTimes(1); expect(onCancel).toHaveBeenCalledWith(mouseEvent); expect(onFinish).toHaveBeenCalledTimes(0); }); test('Detect long press using touch events', () => { const component = createShallowTestComponent({ callback, onStart, onFinish, onCancel, threshold, captureEvent: true, detect: LongPressDetectEvents.TOUCH, }); // -------------------------------------------------------------------------------------------------------- // Touch start + touch end (trigger long press) // -------------------------------------------------------------------------------------------------------- component.props().onTouchStart(touchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toHaveBeenCalledTimes(1); expect(callback).toHaveBeenCalledWith(touchEvent); expect(onStart).toHaveBeenCalledTimes(1); expect(onStart).toHaveBeenCalledWith(touchEvent); expect(onFinish).toHaveBeenCalledTimes(1); expect(onFinish).toHaveBeenCalledWith(touchEvent); expect(onCancel).toHaveBeenCalledTimes(0); // -------------------------------------------------------------------------------------------------------- // Touch start + touch end (cancelled long press) // -------------------------------------------------------------------------------------------------------- jest.clearAllMocks(); component.props().onTouchStart(touchEvent); jest.advanceTimersByTime(Math.round(threshold / 2)); component.props().onTouchEnd(touchEvent); expect(callback).toHaveBeenCalledTimes(0); expect(onStart).toHaveBeenCalledTimes(1); expect(onStart).toHaveBeenCalledWith(touchEvent); expect(onCancel).toHaveBeenCalledTimes(1); expect(onCancel).toHaveBeenCalledWith(touchEvent); expect(onFinish).toHaveBeenCalledTimes(0); }); test('Detect and capture move event', () => { const onMove = jest.fn(); let touchComponent = createShallowTestComponent({ callback: jest.fn(), onMove, captureEvent: true, detect: LongPressDetectEvents.TOUCH, }); touchComponent.props().onTouchMove(touchEvent); expect(onMove).toHaveBeenCalledWith(touchEvent); touchComponent = createShallowTestComponent({ callback: jest.fn(), onMove, captureEvent: false, detect: LongPressDetectEvents.TOUCH, }); touchComponent.props().onTouchMove(touchEvent); expect(onMove).toHaveBeenCalledWith(); let mouseComponent = createShallowTestComponent({ callback: jest.fn(), onMove, captureEvent: true, detect: LongPressDetectEvents.MOUSE, }); mouseComponent.props().onMouseMove(mouseEvent); expect(onMove).toHaveBeenCalledWith(mouseEvent); mouseComponent = createShallowTestComponent({ callback: jest.fn(), onMove, captureEvent: false, detect: LongPressDetectEvents.MOUSE, }); mouseComponent.props().onMouseMove(mouseEvent); expect(onMove).toHaveBeenCalledWith(); }); }); describe('Check appropriate behaviour considering supplied hook options', () => { beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.clearAllTimers(); jest.clearAllMocks(); }); test('No events are passed to callbacks when captureEvent flag is false', () => { const threshold = 400; const callback = jest.fn(); const onStart = jest.fn(); const onFinish = jest.fn(); const onCancel = jest.fn(); const mouseEvent = mockMouseEvent(); const component = createShallowTestComponent({ callback, onStart, onFinish, onCancel, threshold, captureEvent: false, }); component.props().onMouseDown(mouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(mouseEvent); expect(callback).toHaveBeenCalledWith(); expect(onStart).toHaveBeenCalledWith(); expect(onFinish).toHaveBeenCalledWith(); component.props().onMouseDown(mouseEvent); jest.advanceTimersByTime(Math.round(threshold / 2)); component.props().onMouseUp(mouseEvent); expect(onCancel).toHaveBeenCalledWith(); }); test('Long press is properly detected when end event is long after threshold value', () => { const mouseEvent = mockMouseEvent(); const callback = jest.fn(); const threshold = 1000; const component = createShallowTestComponent({ callback, threshold }); component.props().onMouseDown(mouseEvent); jest.advanceTimersByTime(threshold * 5); component.props().onMouseUp(mouseEvent); expect(callback).toBeCalledTimes(1); }); test('Detect both mouse and touch events interchangeably, when using detect both option', () => { const touchEvent = mockTouchEvent(); const mouseEvent = mockMouseEvent(); const callback = jest.fn(); const component = createShallowTestComponent({ callback, detect: LongPressDetectEvents.BOTH }); component.props().onTouchStart(touchEvent); jest.runOnlyPendingTimers(); component.props().onMouseLeave(mouseEvent); expect(callback).toBeCalledTimes(1); }); test('Triggering multiple events simultaneously does not trigger onStart and callback twice when using detect both option', () => { const touchEvent = mockTouchEvent(); const mouseEvent = mockMouseEvent(); const callback = jest.fn(); const onStart = jest.fn(); const onFinish = jest.fn(); const component = createShallowTestComponent({ callback, detect: LongPressDetectEvents.BOTH, onStart, onFinish, }); component.props().onMouseDown(mouseEvent); component.props().onTouchStart(touchEvent); expect(onStart).toBeCalledTimes(1); jest.runOnlyPendingTimers(); component.props().onMouseLeave(mouseEvent); component.props().onMouseUp(mouseEvent); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(1); expect(onFinish).toBeCalledTimes(1); }); describe('Cancel on movement', () => { test('Should not cancel on movement when appropriate option is set to false', () => { const touchEvent = mockTouchEvent({ touches: [{ pageX: 0, pageY: 0 }] as unknown as React.TouchList, }); const moveTouchEvent = mockTouchEvent({ touches: [{ pageX: Number.MAX_SAFE_INTEGER, pageY: Number.MAX_SAFE_INTEGER }] as unknown as React.TouchList, }); const mouseEvent = mockMouseEvent({ pageX: 0, pageY: 0 }); const moveMouseEvent = mockMouseEvent({ pageX: Number.MAX_SAFE_INTEGER, pageY: Number.MAX_SAFE_INTEGER, }); const callback = jest.fn(); const component = createShallowTestComponent({ callback, cancelOnMovement: false, }); component.props().onTouchStart(touchEvent); component.props().onTouchMove(moveTouchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(1); component.props().onMouseDown(mouseEvent); component.props().onMouseMove(moveMouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(mouseEvent); expect(callback).toBeCalledTimes(2); }); test('Should cancel on movement when appropriate option is set to true', () => { const touchEvent = mockTouchEvent({ touches: [{ pageX: 0, pageY: 0 }] as unknown as React.TouchList, }); const moveTouchEvent = mockTouchEvent({ touches: [{ pageX: Number.MAX_SAFE_INTEGER, pageY: Number.MAX_SAFE_INTEGER }] as unknown as React.TouchList, }); const mouseEvent = mockMouseEvent({ pageX: 0, pageY: 0 }); const moveMouseEvent = mockMouseEvent({ pageX: Number.MAX_SAFE_INTEGER, pageY: Number.MAX_SAFE_INTEGER, }); const callback = jest.fn(); const component = createShallowTestComponent({ callback, cancelOnMovement: true, }); component.props().onTouchStart(touchEvent); component.props().onTouchMove(moveTouchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(0); component.props().onMouseDown(mouseEvent); component.props().onMouseMove(moveMouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(mouseEvent); expect(callback).toBeCalledTimes(0); }); test('Should not cancel when within explicitly set movement tolerance', () => { const tolerance = 10; const touchEvent = mockTouchEvent({ touches: [{ pageX: 0, pageY: 0 }] as unknown as React.TouchList, }); const moveTouchEvent = mockTouchEvent({ touches: [{ pageX: tolerance, pageY: tolerance }] as unknown as React.TouchList, }); const mouseEvent = mockMouseEvent({ pageX: 0, pageY: 0 }); const moveMouseEvent = mockMouseEvent({ pageX: tolerance, pageY: tolerance, }); const callback = jest.fn(); const component = createShallowTestComponent({ callback, cancelOnMovement: tolerance, }); component.props().onTouchStart(touchEvent); component.props().onTouchMove(moveTouchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(1); component.props().onMouseDown(mouseEvent); component.props().onMouseMove(moveMouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(mouseEvent); expect(callback).toBeCalledTimes(2); }); test('Should cancel when moved outside explicitly set movement tolerance', () => { const tolerance = 10; const touchEvent = mockTouchEvent({ touches: [{ pageX: 0, pageY: 0 }] as unknown as React.TouchList, }); const moveTouchEvent = mockTouchEvent({ touches: [{ pageX: 2 * tolerance, pageY: 2 * tolerance }] as unknown as React.TouchList, }); const mouseEvent = mockMouseEvent({ pageX: 0, pageY: 0 }); const moveMouseEvent = mockMouseEvent({ pageX: 2 * tolerance, pageY: 2 * tolerance, }); const callback = jest.fn(); const component = createShallowTestComponent({ callback, cancelOnMovement: tolerance, }); component.props().onTouchStart(touchEvent); component.props().onTouchMove(moveTouchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(0); component.props().onMouseDown(mouseEvent); component.props().onMouseMove(moveMouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(mouseEvent); expect(callback).toBeCalledTimes(0); }); }); }); describe('Test general hook behaviour inside a component', () => { beforeEach(() => { jest.useFakeTimers('legacy'); }); afterEach(() => { jest.clearAllTimers(); jest.clearAllMocks(); }); test('Callback is called repetitively on multiple long presses', () => { const touchEvent = mockTouchEvent(); const callback = jest.fn(); const component = createShallowTestComponent({ callback }); component.props().onTouchStart(touchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(1); component.props().onTouchStart(touchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(2); component.props().onTouchStart(touchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(touchEvent); expect(callback).toBeCalledTimes(3); }); test('Timer is destroyed when component unmount', () => { const mouseEvent = mockMouseEvent(); const callback = jest.fn(); const onStart = jest.fn(); const threshold = 1000; const thresholdHalf = Math.round(threshold / 2); const component = createMountedTestComponent({ callback, threshold, onStart }); // Trigger press start component.find('TestComponent').children().props().onMouseDown(mouseEvent); expect(onStart).toHaveBeenCalledTimes(1); jest.advanceTimersByTime(thresholdHalf); component.unmount(); // Trigger useEffect unmount handler act(() => { jest.runAllImmediates(); }); expect(callback).toHaveBeenCalledTimes(0); jest.advanceTimersByTime(thresholdHalf + 1); expect(callback).toHaveBeenCalledTimes(0); }); test('Callbacks are not triggered when callback change to null after click / tap', () => { const mouseEvent = mockMouseEvent(); const callback = jest.fn(); const onStart = jest.fn(); const onFinish = jest.fn(); const onCancel = jest.fn(); const component = createMountedTestComponent({ callback, onStart, onFinish, onCancel }); let props = component.find('TestComponent').children().props(); expect(props).toHaveProperty('onMouseDown'); expect(props).toHaveProperty('onMouseUp'); expect(props).toHaveProperty('onMouseLeave'); expect(props).toHaveProperty('onTouchStart'); expect(props).toHaveProperty('onTouchEnd'); props.onMouseDown(mouseEvent); component.setProps({ callback: null }).update(); act(() => { jest.runAllImmediates(); }); jest.runOnlyPendingTimers(); props = component.find('TestComponent').children().props(); expect(props).not.toHaveProperty('onMouseDown'); expect(props).not.toHaveProperty('onMouseUp'); expect(props).not.toHaveProperty('onMouseLeave'); expect(props).not.toHaveProperty('onTouchStart'); expect(props).not.toHaveProperty('onTouchEnd'); expect(onStart).toBeCalledTimes(1); expect(callback).toBeCalledTimes(0); expect(onFinish).toBeCalledTimes(0); expect(onCancel).toBeCalledTimes(0); }); test('Cancel event is not called simply on mouse leave', () => { const mouseEvent = mockMouseEvent(); const callback = jest.fn(); const onCancel = jest.fn(); const component = createShallowTestComponent({ callback, onCancel }); component.props().onMouseLeave(mouseEvent); component.props().onMouseDown(mouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(mouseEvent); component.props().onMouseLeave(mouseEvent); expect(onCancel).toBeCalledTimes(0); }); test('Hook is not failing when invalid event was sent to the handler', () => { const fakeEvent = new ErrorEvent('invalid'); const callback = jest.fn(); const component = createShallowTestComponent({ callback, cancelOnMovement: true }); component.props().onMouseDown(fakeEvent as unknown as React.MouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(fakeEvent as unknown as React.MouseEvent); expect(callback).toBeCalledTimes(0); component.props().onMouseDown(fakeEvent as unknown as React.MouseEvent); component.props().onMouseMove(fakeEvent as unknown as React.MouseEvent); jest.runOnlyPendingTimers(); component.props().onMouseUp(fakeEvent as unknown as React.MouseEvent); component.props().onMouseLeave(fakeEvent as unknown as React.MouseEvent); expect(callback).toBeCalledTimes(0); component.props().onTouchStart(fakeEvent as unknown as React.TouchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(fakeEvent as unknown as React.TouchEvent); expect(callback).toBeCalledTimes(0); component.props().onTouchStart(fakeEvent as unknown as React.TouchEvent); component.props().onTouchMove(fakeEvent as unknown as React.TouchEvent); jest.runOnlyPendingTimers(); component.props().onTouchEnd(fakeEvent as unknown as React.TouchEvent); expect(callback).toBeCalledTimes(0); }); });
the_stack
import { Headers } from 'node-fetch'; import { account, async, auth, check, common, contacts, file_properties, file_requests, files, paper, secondary_emails, seen_state, sharing, team, team_common, team_log, team_policies, users, users_common } from './dropbox_types'; export * from './dropbox_types'; export interface DropboxAuthOptions { // An access token for making authenticated requests. accessToken?: string; // The time at which the access token expires. accessTokenExpiresAt?: Date; // A refresh token for retrieving access tokens refreshToken?: string; // The client id for your app. Used to create authentication URL. clientId?: string; // The client secret for your app. Used for refresh and token exchange. clientSecret?: string; // The fetch library for making requests. fetch?: Function; // A custom domain to use when making api requests. This should only be used for testing as scaffolding to avoid making network requests. domain?: string; // A custom delimiter to use when separating domain from subdomain. This should only be used for testing as scaffolding. domainDelimiter?: string; } export class DropboxAuth { /** * The DropboxAuth class that provides methods to manage, acquire, and refresh tokens. */ constructor(); /** * The DropboxAuth class that provides methods to manage, acquire, and refresh tokens. */ constructor(options: DropboxAuthOptions); /** * Get the access token * @returns {String} Access token */ getAccessToken(): string; /** * Get an OAuth2 access token from an OAuth2 Code. * @param redirectUri A URL to redirect the user to after authenticating. * This must be added to your app through the admin interface. * @param code An OAuth2 code. * @returns {Object} An object containing the token and related info (if applicable) */ getAccessTokenFromCode(redirectUri: string, code: string): Promise<DropboxResponse<object>>; /** * Get a URL that can be used to authenticate users for the Dropbox API. * @arg {String} redirectUri - A URL to redirect the user to after * authenticating. This must be added to your app through the admin interface. * @arg {String} [state] - State that will be returned in the redirect URL to help * prevent cross site scripting attacks. * @arg {String} [authType] - auth type, defaults to 'token', other option is 'code' * @arg {String} [tokenAccessType] - type of token to request. From the following: * null - creates a token with the app default (either legacy or online) * legacy - creates one long-lived token with no expiration * online - create one short-lived token with an expiration * offline - create one short-lived token with an expiration with a refresh token * @arg {Array<String>} [scope] - scopes to request for the grant * @arg {String} [includeGrantedScopes] - whether or not to include previously granted scopes. * From the following: * user - include user scopes in the grant * team - include team scopes in the grant * Note: if this user has never linked the app, include_granted_scopes must be None * @arg {boolean} [usePKCE] - Whether or not to use Sha256 based PKCE. PKCE should be only use on * client apps which doesn't call your server. It is less secure than non-PKCE flow but * can be used if you are unable to safely retrieve your app secret * @returns {Promise<String>} - Url to send user to for Dropbox API authentication * returned in a promise */ getAuthenticationUrl(redirectUri: string, state?: string, authType?: 'token' | 'code', tokenAccessType?: null | 'legacy' | 'offline' | 'online', scope?: Array<String>, includeGrantedScopes?: 'none' | 'user' | 'team', usePKCE?: boolean): Promise<String>; /** * Get the client id * @returns {String} Client id */ getClientId(): string; /** * Set the access token used to authenticate requests to the API. * @param accessToken An access token. */ setAccessToken(accessToken: string): void; /** * Set the client id, which is used to help gain an access token. * @param clientId Your app's client ID. */ setClientId(clientId: string): void; /** * Set the client secret * @param clientSecret Your app's client secret. */ setClientSecret(clientSecret: string): void; /** * Sets the refresh token * @param refreshToken - A refresh token */ setRefreshToken(refreshToken: string): void; /** * Gets the refresh token * @returns {String} Refresh token */ getRefreshToken(): string; /** * Sets the access token's expiration date * @param accessTokenExpiresAt - new expiration date */ setAccessTokenExpiresAt(accessTokenExpiresAt: Date): void; /** * Gets the access token's expiration date * @returns {Date} date of token expiration */ getAccessTokenExpiresAt(): Date; /** * Sets the code verifier for PKCE flow * @param {String} codeVerifier - new code verifier */ setCodeVerifier(codeVerifier: string): void; /** * Gets the code verifier for PKCE flow * @returns {String} - code verifier for PKCE */ getCodeVerifier(): string; /** * Checks if a token is needed, can be refreshed and if the token is expired. * If so, attempts to refresh access token * @returns {Promise<*>} */ checkAndRefreshAccessToken(): void; /** * Refreshes the access token using the refresh token, if available * @arg {List} scope - a subset of scopes from the original * refresh to acquire with an access token * @returns {Promise<*>} */ refreshAccessToken(scope?: Array<String>): void; } export interface DropboxOptions { // Select user is only used for team functionality. It specifies which user the team access token should be acting as. selectUser?: string; // Select admin is only used by team functionality. It specifies which team admin the team access token should be acting as. selectAdmin?: string; // Root path to access other namespaces. Use to access team folders for example pathRoot?: string; // The DropboxAuth object used to authenticate requests. If this is set, the remaining parameters will be ignored. auth?: DropboxAuth | null; // An access token for making authenticated requests. accessToken?: string; // The time at which the access token expires. accessTokenExpiresAt?: Date; // A refresh token for retrieving access tokens refreshToken?: string; // The client id for your app. Used to create authentication URL. clientId?: string; // The client secret for your app. Used for refresh and token exchange. clientSecret?: string; // The fetch library for making requests. fetch?: Function; // A custom domain to use when making api requests. This should only be used for testing as scaffolding to avoid making network requests. domain?: string; // A custom delimiter to use when separating domain subdomain. This should only be used for testing as scaffolding. domainDelimiter?: string; // An object (in the form of header: value) designed to set custom headers to use during a request. customHeaders?: object; } export class DropboxResponseError<T> { /** * The response class of HTTP errors from API calls using the Dropbox SDK. */ constructor(status: number, headers: Headers, error: T); /** * HTTP Status code of the call */ status: number; /** * Headers returned from the call */ headers: Headers; /** * Serialized Error of the call */ error: T; } export class DropboxResponse<T> { /** * The response class of all successful API calls using the Dropbox SDK. */ constructor(status: number, headers: Headers, result: T); /** * HTTP Status code of the call */ status: number; /** * Headers returned from the call */ headers: Headers; /** * Serialized Result of the call */ result: T; } export class Dropbox { /** * The Dropbox SDK class that provides methods to read, write and * create files or folders in a user or team's Dropbox. */ constructor(); /** * The Dropbox SDK class that provides methods to read, write and * create files or folders in a user or team's Dropbox. */ constructor(options: DropboxOptions); /*ROUTES*/ /** * Sets a user's profile photo. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<account.SetProfilePhotoError>. * @param arg The request parameters. */ public accountSetProfilePhoto(arg: account.SetProfilePhotoArg): Promise<DropboxResponse<account.SetProfilePhotoResult>>; /** * Creates an OAuth 2.0 access token from the supplied OAuth 1.0 access * token. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<auth.TokenFromOAuth1Error>. * @param arg The request parameters. */ public authTokenFromOauth1(arg: auth.TokenFromOAuth1Arg): Promise<DropboxResponse<auth.TokenFromOAuth1Result>>; /** * Disables the access token used to authenticate the call. If there is a * corresponding refresh token for the access token, this disables that * refresh token, as well as any other access tokens for that refresh token. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. */ public authTokenRevoke(): Promise<DropboxResponse<void>>; /** * This endpoint performs App Authentication, validating the supplied app * key and secret, and returns the supplied string, to allow you to test * your code and connection to the Dropbox API. It has no other effect. If * you receive an HTTP 200 response with the supplied query, it indicates at * least part of the Dropbox API infrastructure is working and that the app * key and secret valid. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public checkApp(arg: check.EchoArg): Promise<DropboxResponse<check.EchoResult>>; /** * This endpoint performs User Authentication, validating the supplied * access token, and returns the supplied string, to allow you to test your * code and connection to the Dropbox API. It has no other effect. If you * receive an HTTP 200 response with the supplied query, it indicates at * least part of the Dropbox API infrastructure is working and that the * access token is valid. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public checkUser(arg: check.EchoArg): Promise<DropboxResponse<check.EchoResult>>; /** * Removes all manually added contacts. You'll still keep contacts who are * on your team or who you imported. New contacts will be added when you * share. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. */ public contactsDeleteManualContacts(): Promise<DropboxResponse<void>>; /** * Removes manually added contacts from the given list. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<contacts.DeleteManualContactsError>. * @param arg The request parameters. */ public contactsDeleteManualContactsBatch(arg: contacts.DeleteManualContactsArg): Promise<DropboxResponse<void>>; /** * Add property groups to a Dropbox file. See templatesAddForUser() or * templatesAddForTeam() to create new templates. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.AddPropertiesError>. * @param arg The request parameters. */ public filePropertiesPropertiesAdd(arg: file_properties.AddPropertiesArg): Promise<DropboxResponse<void>>; /** * Overwrite property groups associated with a file. This endpoint should be * used instead of propertiesUpdate() when property groups are being updated * via a "snapshot" instead of via a "delta". In other words, this endpoint * will delete all omitted fields from a property group, whereas * propertiesUpdate() will only delete fields that are explicitly marked for * deletion. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.InvalidPropertyGroupError>. * @param arg The request parameters. */ public filePropertiesPropertiesOverwrite(arg: file_properties.OverwritePropertyGroupArg): Promise<DropboxResponse<void>>; /** * Permanently removes the specified property group from the file. To remove * specific property field key value pairs, see propertiesUpdate(). To * update a template, see templatesUpdateForUser() or * templatesUpdateForTeam(). To remove a template, see * templatesRemoveForUser() or templatesRemoveForTeam(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.RemovePropertiesError>. * @param arg The request parameters. */ public filePropertiesPropertiesRemove(arg: file_properties.RemovePropertiesArg): Promise<DropboxResponse<void>>; /** * Search across property templates for particular property field values. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.PropertiesSearchError>. * @param arg The request parameters. */ public filePropertiesPropertiesSearch(arg: file_properties.PropertiesSearchArg): Promise<DropboxResponse<file_properties.PropertiesSearchResult>>; /** * Once a cursor has been retrieved from propertiesSearch(), use this to * paginate through all search results. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.PropertiesSearchContinueError>. * @param arg The request parameters. */ public filePropertiesPropertiesSearchContinue(arg: file_properties.PropertiesSearchContinueArg): Promise<DropboxResponse<file_properties.PropertiesSearchResult>>; /** * Add, update or remove properties associated with the supplied file and * templates. This endpoint should be used instead of propertiesOverwrite() * when property groups are being updated via a "delta" instead of via a * "snapshot" . In other words, this endpoint will not delete any omitted * fields from a property group, whereas propertiesOverwrite() will delete * any fields that are omitted from a property group. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.UpdatePropertiesError>. * @param arg The request parameters. */ public filePropertiesPropertiesUpdate(arg: file_properties.UpdatePropertiesArg): Promise<DropboxResponse<void>>; /** * Add a template associated with a team. See propertiesAdd() to add * properties to a file or folder. Note: this endpoint will create * team-owned templates. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.ModifyTemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesAddForTeam(arg: file_properties.AddTemplateArg): Promise<DropboxResponse<file_properties.AddTemplateResult>>; /** * Add a template associated with a user. See propertiesAdd() to add * properties to a file. This endpoint can't be called on a team member or * admin's behalf. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.ModifyTemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesAddForUser(arg: file_properties.AddTemplateArg): Promise<DropboxResponse<file_properties.AddTemplateResult>>; /** * Get the schema for a specified template. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesGetForTeam(arg: file_properties.GetTemplateArg): Promise<DropboxResponse<file_properties.GetTemplateResult>>; /** * Get the schema for a specified template. This endpoint can't be called on * a team member or admin's behalf. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesGetForUser(arg: file_properties.GetTemplateArg): Promise<DropboxResponse<file_properties.GetTemplateResult>>; /** * Get the template identifiers for a team. To get the schema of each * template use templatesGetForTeam(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. */ public filePropertiesTemplatesListForTeam(): Promise<DropboxResponse<file_properties.ListTemplateResult>>; /** * Get the template identifiers for a team. To get the schema of each * template use templatesGetForUser(). This endpoint can't be called on a * team member or admin's behalf. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. */ public filePropertiesTemplatesListForUser(): Promise<DropboxResponse<file_properties.ListTemplateResult>>; /** * Permanently removes the specified template created from * templatesAddForUser(). All properties associated with the template will * also be removed. This action cannot be undone. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesRemoveForTeam(arg: file_properties.RemoveTemplateArg): Promise<DropboxResponse<void>>; /** * Permanently removes the specified template created from * templatesAddForUser(). All properties associated with the template will * also be removed. This action cannot be undone. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesRemoveForUser(arg: file_properties.RemoveTemplateArg): Promise<DropboxResponse<void>>; /** * Update a template associated with a team. This route can update the * template name, the template description and add optional properties to * templates. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.ModifyTemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesUpdateForTeam(arg: file_properties.UpdateTemplateArg): Promise<DropboxResponse<file_properties.UpdateTemplateResult>>; /** * Update a template associated with a user. This route can update the * template name, the template description and add optional properties to * templates. This endpoint can't be called on a team member or admin's * behalf. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.ModifyTemplateError>. * @param arg The request parameters. */ public filePropertiesTemplatesUpdateForUser(arg: file_properties.UpdateTemplateArg): Promise<DropboxResponse<file_properties.UpdateTemplateResult>>; /** * Returns the total number of file requests owned by this user. Includes * both open and closed file requests. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.CountFileRequestsError>. */ public fileRequestsCount(): Promise<DropboxResponse<file_requests.CountFileRequestsResult>>; /** * Creates a file request for this user. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.CreateFileRequestError>. * @param arg The request parameters. */ public fileRequestsCreate(arg: file_requests.CreateFileRequestArgs): Promise<DropboxResponse<file_requests.FileRequest>>; /** * Delete a batch of closed file requests. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.DeleteFileRequestError>. * @param arg The request parameters. */ public fileRequestsDelete(arg: file_requests.DeleteFileRequestArgs): Promise<DropboxResponse<file_requests.DeleteFileRequestsResult>>; /** * Delete all closed file requests owned by this user. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.DeleteAllClosedFileRequestsError>. */ public fileRequestsDeleteAllClosed(): Promise<DropboxResponse<file_requests.DeleteAllClosedFileRequestsResult>>; /** * Returns the specified file request. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.GetFileRequestError>. * @param arg The request parameters. */ public fileRequestsGet(arg: file_requests.GetFileRequestArgs): Promise<DropboxResponse<file_requests.FileRequest>>; /** * Returns a list of file requests owned by this user. For apps with the app * folder permission, this will only return file requests with destinations * in the app folder. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.ListFileRequestsError>. * @param arg The request parameters. */ public fileRequestsListV2(arg: file_requests.ListFileRequestsArg): Promise<DropboxResponse<file_requests.ListFileRequestsV2Result>>; /** * Returns a list of file requests owned by this user. For apps with the app * folder permission, this will only return file requests with destinations * in the app folder. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.ListFileRequestsError>. */ public fileRequestsList(): Promise<DropboxResponse<file_requests.ListFileRequestsResult>>; /** * Once a cursor has been retrieved from listV2(), use this to paginate * through all file requests. The cursor must come from a previous call to * listV2() or listContinue(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.ListFileRequestsContinueError>. * @param arg The request parameters. */ public fileRequestsListContinue(arg: file_requests.ListFileRequestsContinueArg): Promise<DropboxResponse<file_requests.ListFileRequestsV2Result>>; /** * Update a file request. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_requests.UpdateFileRequestError>. * @param arg The request parameters. */ public fileRequestsUpdate(arg: file_requests.UpdateFileRequestArgs): Promise<DropboxResponse<file_requests.FileRequest>>; /** * Returns the metadata for a file or folder. This is an alpha endpoint * compatible with the properties API. Note: Metadata for the root folder is * unsupported. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.AlphaGetMetadataError>. * @deprecated * @param arg The request parameters. */ public filesAlphaGetMetadata(arg: files.AlphaGetMetadataArg): Promise<DropboxResponse<files.FileMetadataReference|files.FolderMetadataReference|files.DeletedMetadataReference>>; /** * Create a new file with the contents provided in the request. Note that * this endpoint is part of the properties API alpha and is slightly * different from upload(). Do not use this to upload a file larger than 150 * MB. Instead, create an upload session with uploadSessionStart(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.UploadErrorWithProperties>. * @deprecated * @param arg The request parameters. */ public filesAlphaUpload(arg: files.CommitInfoWithProperties): Promise<DropboxResponse<files.FileMetadata>>; /** * Copy a file or folder to a different location in the user's Dropbox. If * the source path is a folder all its contents will be copied. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.RelocationError>. * @param arg The request parameters. */ public filesCopyV2(arg: files.RelocationArg): Promise<DropboxResponse<files.RelocationResult>>; /** * Copy a file or folder to a different location in the user's Dropbox. If * the source path is a folder all its contents will be copied. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.RelocationError>. * @deprecated * @param arg The request parameters. */ public filesCopy(arg: files.RelocationArg): Promise<DropboxResponse<files.FileMetadataReference|files.FolderMetadataReference|files.DeletedMetadataReference>>; /** * Copy multiple files or folders to different locations at once in the * user's Dropbox. This route will replace copyBatch(). The main difference * is this route will return status for each entry, while copyBatch() raises * failure if any entry fails. This route will either finish synchronously, * or return a job ID and do the async copy job in background. Please use * copyBatchCheckV2() to check the job status. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public filesCopyBatchV2(arg: files.CopyBatchArg): Promise<DropboxResponse<files.RelocationBatchV2Launch>>; /** * Copy multiple files or folders to different locations at once in the * user's Dropbox. This route will return job ID immediately and do the * async copy job in background. Please use copyBatchCheck() to check the * job status. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @deprecated * @param arg The request parameters. */ public filesCopyBatch(arg: files.RelocationBatchArg): Promise<DropboxResponse<files.RelocationBatchLaunch>>; /** * Returns the status of an asynchronous job for copyBatchV2(). It returns * list of results for each entry. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public filesCopyBatchCheckV2(arg: async.PollArg): Promise<DropboxResponse<files.RelocationBatchV2JobStatus>>; /** * Returns the status of an asynchronous job for copyBatch(). If success, it * returns list of results for each entry. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @deprecated * @param arg The request parameters. */ public filesCopyBatchCheck(arg: async.PollArg): Promise<DropboxResponse<files.RelocationBatchJobStatus>>; /** * Get a copy reference to a file or folder. This reference string can be * used to save that file or folder to another user's Dropbox by passing it * to copyReferenceSave(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.GetCopyReferenceError>. * @param arg The request parameters. */ public filesCopyReferenceGet(arg: files.GetCopyReferenceArg): Promise<DropboxResponse<files.GetCopyReferenceResult>>; /** * Save a copy reference returned by copyReferenceGet() to the user's * Dropbox. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.SaveCopyReferenceError>. * @param arg The request parameters. */ public filesCopyReferenceSave(arg: files.SaveCopyReferenceArg): Promise<DropboxResponse<files.SaveCopyReferenceResult>>; /** * Create a folder at a given path. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.CreateFolderError>. * @param arg The request parameters. */ public filesCreateFolderV2(arg: files.CreateFolderArg): Promise<DropboxResponse<files.CreateFolderResult>>; /** * Create a folder at a given path. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.CreateFolderError>. * @deprecated * @param arg The request parameters. */ public filesCreateFolder(arg: files.CreateFolderArg): Promise<DropboxResponse<files.FolderMetadata>>; /** * Create multiple folders at once. This route is asynchronous for large * batches, which returns a job ID immediately and runs the create folder * batch asynchronously. Otherwise, creates the folders and returns the * result synchronously for smaller inputs. You can force asynchronous * behaviour by using the CreateFolderBatchArg.force_async flag. Use * createFolderBatchCheck() to check the job status. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public filesCreateFolderBatch(arg: files.CreateFolderBatchArg): Promise<DropboxResponse<files.CreateFolderBatchLaunch>>; /** * Returns the status of an asynchronous job for createFolderBatch(). If * success, it returns list of result for each entry. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public filesCreateFolderBatchCheck(arg: async.PollArg): Promise<DropboxResponse<files.CreateFolderBatchJobStatus>>; /** * Delete the file or folder at a given path. If the path is a folder, all * its contents will be deleted too. A successful response indicates that * the file or folder was deleted. The returned metadata will be the * corresponding FileMetadata or FolderMetadata for the item at time of * deletion, and not a DeletedMetadata object. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.DeleteError>. * @param arg The request parameters. */ public filesDeleteV2(arg: files.DeleteArg): Promise<DropboxResponse<files.DeleteResult>>; /** * Delete the file or folder at a given path. If the path is a folder, all * its contents will be deleted too. A successful response indicates that * the file or folder was deleted. The returned metadata will be the * corresponding FileMetadata or FolderMetadata for the item at time of * deletion, and not a DeletedMetadata object. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.DeleteError>. * @deprecated * @param arg The request parameters. */ public filesDelete(arg: files.DeleteArg): Promise<DropboxResponse<files.FileMetadataReference|files.FolderMetadataReference|files.DeletedMetadataReference>>; /** * Delete multiple files/folders at once. This route is asynchronous, which * returns a job ID immediately and runs the delete batch asynchronously. * Use deleteBatchCheck() to check the job status. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public filesDeleteBatch(arg: files.DeleteBatchArg): Promise<DropboxResponse<files.DeleteBatchLaunch>>; /** * Returns the status of an asynchronous job for deleteBatch(). If success, * it returns list of result for each entry. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public filesDeleteBatchCheck(arg: async.PollArg): Promise<DropboxResponse<files.DeleteBatchJobStatus>>; /** * Download a file from a user's Dropbox. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.DownloadError>. * @param arg The request parameters. */ public filesDownload(arg: files.DownloadArg): Promise<DropboxResponse<files.FileMetadata>>; /** * Download a folder from the user's Dropbox, as a zip file. The folder must * be less than 20 GB in size and any single file within must be less than 4 * GB in size. The resulting zip must have fewer than 10,000 total file and * folder entries, including the top level folder. The input cannot be a * single file. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.DownloadZipError>. * @param arg The request parameters. */ public filesDownloadZip(arg: files.DownloadZipArg): Promise<DropboxResponse<files.DownloadZipResult>>; /** * Export a file from a user's Dropbox. This route only supports exporting * files that cannot be downloaded directly and whose * ExportResult.file_metadata has ExportInfo.export_as populated. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ExportError>. * @param arg The request parameters. */ public filesExport(arg: files.ExportArg): Promise<DropboxResponse<files.ExportResult>>; /** * Return the lock metadata for the given list of paths. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.LockFileError>. * @param arg The request parameters. */ public filesGetFileLockBatch(arg: files.LockFileBatchArg): Promise<DropboxResponse<files.LockFileBatchResult>>; /** * Returns the metadata for a file or folder. Note: Metadata for the root * folder is unsupported. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.GetMetadataError>. * @param arg The request parameters. */ public filesGetMetadata(arg: files.GetMetadataArg): Promise<DropboxResponse<files.FileMetadataReference|files.FolderMetadataReference|files.DeletedMetadataReference>>; /** * Get a preview for a file. Currently, PDF previews are generated for files * with the following extensions: .ai, .doc, .docm, .docx, .eps, .gdoc, * .gslides, .odp, .odt, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .rtf. HTML * previews are generated for files with the following extensions: .csv, * .ods, .xls, .xlsm, .gsheet, .xlsx. Other formats will return an * unsupported extension error. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.PreviewError>. * @param arg The request parameters. */ public filesGetPreview(arg: files.PreviewArg): Promise<DropboxResponse<files.FileMetadata>>; /** * Get a temporary link to stream content of a file. This link will expire * in four hours and afterwards you will get 410 Gone. This URL should not * be used to display content directly in the browser. The Content-Type of * the link is determined automatically by the file's mime type. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.GetTemporaryLinkError>. * @param arg The request parameters. */ public filesGetTemporaryLink(arg: files.GetTemporaryLinkArg): Promise<DropboxResponse<files.GetTemporaryLinkResult>>; /** * Get a one-time use temporary upload link to upload a file to a Dropbox * location. This endpoint acts as a delayed upload(). The returned * temporary upload link may be used to make a POST request with the data to * be uploaded. The upload will then be perfomed with the CommitInfo * previously provided to getTemporaryUploadLink() but evaluated only upon * consumption. Hence, errors stemming from invalid CommitInfo with respect * to the state of the user's Dropbox will only be communicated at * consumption time. Additionally, these errors are surfaced as generic HTTP * 409 Conflict responses, potentially hiding issue details. The maximum * temporary upload link duration is 4 hours. Upon consumption or * expiration, a new link will have to be generated. Multiple links may * exist for a specific upload path at any given time. The POST request on * the temporary upload link must have its Content-Type set to * "application/octet-stream". Example temporary upload link consumption * request: curl -X POST * https://content.dropboxapi.com/apitul/1/bNi2uIYF51cVBND --header * "Content-Type: application/octet-stream" --data-binary @local_file.txt A * successful temporary upload link consumption request returns the content * hash of the uploaded data in JSON format. Example successful temporary * upload link consumption response: {"content-hash": * "599d71033d700ac892a0e48fa61b125d2f5994"} An unsuccessful temporary * upload link consumption request returns any of the following status * codes: HTTP 400 Bad Request: Content-Type is not one of * application/octet-stream and text/plain or request is invalid. HTTP 409 * Conflict: The temporary upload link does not exist or is currently * unavailable, the upload failed, or another error happened. HTTP 410 Gone: * The temporary upload link is expired or consumed. Example unsuccessful * temporary upload link consumption response: Temporary upload link has * been recently consumed. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public filesGetTemporaryUploadLink(arg: files.GetTemporaryUploadLinkArg): Promise<DropboxResponse<files.GetTemporaryUploadLinkResult>>; /** * Get a thumbnail for an image. This method currently supports files with * the following file extensions: jpg, jpeg, png, tiff, tif, gif, webp, ppm * and bmp. Photos that are larger than 20MB in size won't be converted to a * thumbnail. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ThumbnailError>. * @param arg The request parameters. */ public filesGetThumbnail(arg: files.ThumbnailArg): Promise<DropboxResponse<files.FileMetadata>>; /** * Get a thumbnail for an image. This method currently supports files with * the following file extensions: jpg, jpeg, png, tiff, tif, gif, webp, ppm * and bmp. Photos that are larger than 20MB in size won't be converted to a * thumbnail. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ThumbnailV2Error>. * @param arg The request parameters. */ public filesGetThumbnailV2(arg: files.ThumbnailV2Arg): Promise<DropboxResponse<files.PreviewResult>>; /** * Get thumbnails for a list of images. We allow up to 25 thumbnails in a * single batch. This method currently supports files with the following * file extensions: jpg, jpeg, png, tiff, tif, gif, webp, ppm and bmp. * Photos that are larger than 20MB in size won't be converted to a * thumbnail. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.GetThumbnailBatchError>. * @param arg The request parameters. */ public filesGetThumbnailBatch(arg: files.GetThumbnailBatchArg): Promise<DropboxResponse<files.GetThumbnailBatchResult>>; /** * Starts returning the contents of a folder. If the result's * ListFolderResult.has_more field is true, call listFolderContinue() with * the returned ListFolderResult.cursor to retrieve more entries. If you're * using ListFolderArg.recursive set to true to keep a local cache of the * contents of a Dropbox account, iterate through each entry in order and * process them as follows to keep your local state in sync: For each * FileMetadata, store the new entry at the given path in your local state. * If the required parent folders don't exist yet, create them. If there's * already something else at the given path, replace it and remove all its * children. For each FolderMetadata, store the new entry at the given path * in your local state. If the required parent folders don't exist yet, * create them. If there's already something else at the given path, replace * it but leave the children as they are. Check the new entry's * FolderSharingInfo.read_only and set all its children's read-only statuses * to match. For each DeletedMetadata, if your local state has something at * the given path, remove it and all its children. If there's nothing at the * given path, ignore this entry. Note: auth.RateLimitError may be returned * if multiple listFolder() or listFolderContinue() calls with same * parameters are made simultaneously by same API app for same user. If your * app implements retry logic, please hold off the retry until the previous * request finishes. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ListFolderError>. * @param arg The request parameters. */ public filesListFolder(arg: files.ListFolderArg): Promise<DropboxResponse<files.ListFolderResult>>; /** * Once a cursor has been retrieved from listFolder(), use this to paginate * through all files and retrieve updates to the folder, following the same * rules as documented for listFolder(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ListFolderContinueError>. * @param arg The request parameters. */ public filesListFolderContinue(arg: files.ListFolderContinueArg): Promise<DropboxResponse<files.ListFolderResult>>; /** * A way to quickly get a cursor for the folder's state. Unlike * listFolder(), listFolderGetLatestCursor() doesn't return any entries. * This endpoint is for app which only needs to know about new files and * modifications and doesn't need to know about files that already exist in * Dropbox. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ListFolderError>. * @param arg The request parameters. */ public filesListFolderGetLatestCursor(arg: files.ListFolderArg): Promise<DropboxResponse<files.ListFolderGetLatestCursorResult>>; /** * A longpoll endpoint to wait for changes on an account. In conjunction * with listFolderContinue(), this call gives you a low-latency way to * monitor an account for file changes. The connection will block until * there are changes available or a timeout occurs. This endpoint is useful * mostly for client-side apps. If you're looking for server-side * notifications, check out our [webhooks documentation]{@link * https://www.dropbox.com/developers/reference/webhooks}. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ListFolderLongpollError>. * @param arg The request parameters. */ public filesListFolderLongpoll(arg: files.ListFolderLongpollArg): Promise<DropboxResponse<files.ListFolderLongpollResult>>; /** * Returns revisions for files based on a file path or a file id. The file * path or file id is identified from the latest file entry at the given * file path or id. This end point allows your app to query either by file * path or file id by setting the mode parameter appropriately. In the * ListRevisionsMode.path (default) mode, all revisions at the same file * path as the latest file entry are returned. If revisions with the same * file id are desired, then mode must be set to ListRevisionsMode.id. The * ListRevisionsMode.id mode is useful to retrieve revisions for a given * file across moves or renames. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.ListRevisionsError>. * @param arg The request parameters. */ public filesListRevisions(arg: files.ListRevisionsArg): Promise<DropboxResponse<files.ListRevisionsResult>>; /** * Lock the files at the given paths. A locked file will be writable only by * the lock holder. A successful response indicates that the file has been * locked. Returns a list of the locked file paths and their metadata after * this operation. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.LockFileError>. * @param arg The request parameters. */ public filesLockFileBatch(arg: files.LockFileBatchArg): Promise<DropboxResponse<files.LockFileBatchResult>>; /** * Move a file or folder to a different location in the user's Dropbox. If * the source path is a folder all its contents will be moved. Note that we * do not currently support case-only renaming. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.RelocationError>. * @param arg The request parameters. */ public filesMoveV2(arg: files.RelocationArg): Promise<DropboxResponse<files.RelocationResult>>; /** * Move a file or folder to a different location in the user's Dropbox. If * the source path is a folder all its contents will be moved. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.RelocationError>. * @deprecated * @param arg The request parameters. */ public filesMove(arg: files.RelocationArg): Promise<DropboxResponse<files.FileMetadataReference|files.FolderMetadataReference|files.DeletedMetadataReference>>; /** * Move multiple files or folders to different locations at once in the * user's Dropbox. Note that we do not currently support case-only renaming. * This route will replace moveBatch(). The main difference is this route * will return status for each entry, while moveBatch() raises failure if * any entry fails. This route will either finish synchronously, or return a * job ID and do the async move job in background. Please use * moveBatchCheckV2() to check the job status. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public filesMoveBatchV2(arg: files.MoveBatchArg): Promise<DropboxResponse<files.RelocationBatchV2Launch>>; /** * Move multiple files or folders to different locations at once in the * user's Dropbox. This route will return job ID immediately and do the * async moving job in background. Please use moveBatchCheck() to check the * job status. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @deprecated * @param arg The request parameters. */ public filesMoveBatch(arg: files.RelocationBatchArg): Promise<DropboxResponse<files.RelocationBatchLaunch>>; /** * Returns the status of an asynchronous job for moveBatchV2(). It returns * list of results for each entry. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public filesMoveBatchCheckV2(arg: async.PollArg): Promise<DropboxResponse<files.RelocationBatchV2JobStatus>>; /** * Returns the status of an asynchronous job for moveBatch(). If success, it * returns list of results for each entry. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @deprecated * @param arg The request parameters. */ public filesMoveBatchCheck(arg: async.PollArg): Promise<DropboxResponse<files.RelocationBatchJobStatus>>; /** * Creates a new Paper doc with the provided content. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.PaperCreateError>. * @param arg The request parameters. */ public filesPaperCreate(arg: files.PaperCreateArg): Promise<DropboxResponse<files.PaperCreateResult>>; /** * Updates an existing Paper doc with the provided content. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.PaperUpdateError>. * @param arg The request parameters. */ public filesPaperUpdate(arg: files.PaperUpdateArg): Promise<DropboxResponse<files.PaperUpdateResult>>; /** * Permanently delete the file or folder at a given path (see * https://www.dropbox.com/en/help/40). If the given file or folder is not * yet deleted, this route will first delete it. It is possible for this * route to successfully delete, then fail to permanently delete. Note: This * endpoint is only available for Dropbox Business apps. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.DeleteError>. * @param arg The request parameters. */ public filesPermanentlyDelete(arg: files.DeleteArg): Promise<DropboxResponse<void>>; /** * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.AddPropertiesError>. * @deprecated * @param arg The request parameters. */ public filesPropertiesAdd(arg: file_properties.AddPropertiesArg): Promise<DropboxResponse<void>>; /** * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.InvalidPropertyGroupError>. * @deprecated * @param arg The request parameters. */ public filesPropertiesOverwrite(arg: file_properties.OverwritePropertyGroupArg): Promise<DropboxResponse<void>>; /** * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.RemovePropertiesError>. * @deprecated * @param arg The request parameters. */ public filesPropertiesRemove(arg: file_properties.RemovePropertiesArg): Promise<DropboxResponse<void>>; /** * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @deprecated * @param arg The request parameters. */ public filesPropertiesTemplateGet(arg: file_properties.GetTemplateArg): Promise<DropboxResponse<file_properties.GetTemplateResult>>; /** * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @deprecated */ public filesPropertiesTemplateList(): Promise<DropboxResponse<file_properties.ListTemplateResult>>; /** * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.UpdatePropertiesError>. * @deprecated * @param arg The request parameters. */ public filesPropertiesUpdate(arg: file_properties.UpdatePropertiesArg): Promise<DropboxResponse<void>>; /** * Restore a specific revision of a file to the given path. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.RestoreError>. * @param arg The request parameters. */ public filesRestore(arg: files.RestoreArg): Promise<DropboxResponse<files.FileMetadata>>; /** * Save the data from a specified URL into a file in user's Dropbox. Note * that the transfer from the URL must complete within 5 minutes, or the * operation will time out and the job will fail. If the given path already * exists, the file will be renamed to avoid the conflict (e.g. myfile * (1).txt). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.SaveUrlError>. * @param arg The request parameters. */ public filesSaveUrl(arg: files.SaveUrlArg): Promise<DropboxResponse<files.SaveUrlResult>>; /** * Check the status of a saveUrl() job. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public filesSaveUrlCheckJobStatus(arg: async.PollArg): Promise<DropboxResponse<files.SaveUrlJobStatus>>; /** * Searches for files and folders. Note: Recent changes will be reflected in * search results within a few seconds and older revisions of existing files * may still match your query for up to a few days. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.SearchError>. * @deprecated * @param arg The request parameters. */ public filesSearch(arg: files.SearchArg): Promise<DropboxResponse<files.SearchResult>>; /** * Searches for files and folders. Note: searchV2() along with * searchContinueV2() can only be used to retrieve a maximum of 10,000 * matches. Recent changes may not immediately be reflected in search * results due to a short delay in indexing. Duplicate results may be * returned across pages. Some results may not be returned. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.SearchError>. * @param arg The request parameters. */ public filesSearchV2(arg: files.SearchV2Arg): Promise<DropboxResponse<files.SearchV2Result>>; /** * Fetches the next page of search results returned from searchV2(). Note: * searchV2() along with searchContinueV2() can only be used to retrieve a * maximum of 10,000 matches. Recent changes may not immediately be * reflected in search results due to a short delay in indexing. Duplicate * results may be returned across pages. Some results may not be returned. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.SearchError>. * @param arg The request parameters. */ public filesSearchContinueV2(arg: files.SearchV2ContinueArg): Promise<DropboxResponse<files.SearchV2Result>>; /** * Unlock the files at the given paths. A locked file can only be unlocked * by the lock holder or, if a business account, a team admin. A successful * response indicates that the file has been unlocked. Returns a list of the * unlocked file paths and their metadata after this operation. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.LockFileError>. * @param arg The request parameters. */ public filesUnlockFileBatch(arg: files.UnlockFileBatchArg): Promise<DropboxResponse<files.LockFileBatchResult>>; /** * Create a new file with the contents provided in the request. Do not use * this to upload a file larger than 150 MB. Instead, create an upload * session with uploadSessionStart(). Calls to this endpoint will count as * data transport calls for any Dropbox Business teams with a limit on the * number of data transport calls allowed per month. For more information, * see the [Data transport limit page]{@link * https://www.dropbox.com/developers/reference/data-transport-limit}. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.UploadError>. * @param arg The request parameters. */ public filesUpload(arg: files.CommitInfo): Promise<DropboxResponse<files.FileMetadata>>; /** * Append more data to an upload session. When the parameter close is set, * this call will close the session. A single request should not upload more * than 150 MB. The maximum size of a file one can upload to an upload * session is 350 GB. Calls to this endpoint will count as data transport * calls for any Dropbox Business teams with a limit on the number of data * transport calls allowed per month. For more information, see the [Data * transport limit page]{@link * https://www.dropbox.com/developers/reference/data-transport-limit}. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.UploadSessionLookupError>. * @param arg The request parameters. */ public filesUploadSessionAppendV2(arg: files.UploadSessionAppendArg): Promise<DropboxResponse<void>>; /** * Append more data to an upload session. A single request should not upload * more than 150 MB. The maximum size of a file one can upload to an upload * session is 350 GB. Calls to this endpoint will count as data transport * calls for any Dropbox Business teams with a limit on the number of data * transport calls allowed per month. For more information, see the [Data * transport limit page]{@link * https://www.dropbox.com/developers/reference/data-transport-limit}. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.UploadSessionLookupError>. * @deprecated * @param arg The request parameters. */ public filesUploadSessionAppend(arg: files.UploadSessionCursor): Promise<DropboxResponse<void>>; /** * Finish an upload session and save the uploaded data to the given file * path. A single request should not upload more than 150 MB. The maximum * size of a file one can upload to an upload session is 350 GB. Calls to * this endpoint will count as data transport calls for any Dropbox Business * teams with a limit on the number of data transport calls allowed per * month. For more information, see the [Data transport limit page]{@link * https://www.dropbox.com/developers/reference/data-transport-limit}. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.UploadSessionFinishError>. * @param arg The request parameters. */ public filesUploadSessionFinish(arg: files.UploadSessionFinishArg): Promise<DropboxResponse<files.FileMetadata>>; /** * This route helps you commit many files at once into a user's Dropbox. Use * uploadSessionStart() and uploadSessionAppendV2() to upload file contents. * We recommend uploading many files in parallel to increase throughput. * Once the file contents have been uploaded, rather than calling * uploadSessionFinish(), use this route to finish all your upload sessions * in a single request. UploadSessionStartArg.close or * UploadSessionAppendArg.close needs to be true for the last * uploadSessionStart() or uploadSessionAppendV2() call. The maximum size of * a file one can upload to an upload session is 350 GB. This route will * return a job_id immediately and do the async commit job in background. * Use uploadSessionFinishBatchCheck() to check the job status. For the same * account, this route should be executed serially. That means you should * not start the next job before current job finishes. We allow up to 1000 * entries in a single request. Calls to this endpoint will count as data * transport calls for any Dropbox Business teams with a limit on the number * of data transport calls allowed per month. For more information, see the * [Data transport limit page]{@link * https://www.dropbox.com/developers/reference/data-transport-limit}. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @deprecated * @param arg The request parameters. */ public filesUploadSessionFinishBatch(arg: files.UploadSessionFinishBatchArg): Promise<DropboxResponse<files.UploadSessionFinishBatchLaunch>>; /** * This route helps you commit many files at once into a user's Dropbox. Use * uploadSessionStart() and uploadSessionAppendV2() to upload file contents. * We recommend uploading many files in parallel to increase throughput. * Once the file contents have been uploaded, rather than calling * uploadSessionFinish(), use this route to finish all your upload sessions * in a single request. UploadSessionStartArg.close or * UploadSessionAppendArg.close needs to be true for the last * uploadSessionStart() or uploadSessionAppendV2() call of each upload * session. The maximum size of a file one can upload to an upload session * is 350 GB. We allow up to 1000 entries in a single request. Calls to this * endpoint will count as data transport calls for any Dropbox Business * teams with a limit on the number of data transport calls allowed per * month. For more information, see the [Data transport limit page]{@link * https://www.dropbox.com/developers/reference/data-transport-limit}. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public filesUploadSessionFinishBatchV2(arg: files.UploadSessionFinishBatchArg): Promise<DropboxResponse<files.UploadSessionFinishBatchResult>>; /** * Returns the status of an asynchronous job for uploadSessionFinishBatch(). * If success, it returns list of result for each entry. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public filesUploadSessionFinishBatchCheck(arg: async.PollArg): Promise<DropboxResponse<files.UploadSessionFinishBatchJobStatus>>; /** * Upload sessions allow you to upload a single file in one or more * requests, for example where the size of the file is greater than 150 MB. * This call starts a new upload session with the given data. You can then * use uploadSessionAppendV2() to add more data and uploadSessionFinish() to * save all the data to a file in Dropbox. A single request should not * upload more than 150 MB. The maximum size of a file one can upload to an * upload session is 350 GB. An upload session can be used for a maximum of * 7 days. Attempting to use an UploadSessionStartResult.session_id with * uploadSessionAppendV2() or uploadSessionFinish() more than 7 days after * its creation will return a UploadSessionLookupError.not_found. Calls to * this endpoint will count as data transport calls for any Dropbox Business * teams with a limit on the number of data transport calls allowed per * month. For more information, see the [Data transport limit page]{@link * https://www.dropbox.com/developers/reference/data-transport-limit}. By * default, upload sessions require you to send content of the file in * sequential order via consecutive uploadSessionStart(), * uploadSessionAppendV2(), uploadSessionFinish() calls. For better * performance, you can instead optionally use a * UploadSessionType.concurrent upload session. To start a new concurrent * session, set UploadSessionStartArg.session_type to * UploadSessionType.concurrent. After that, you can send file data in * concurrent uploadSessionAppendV2() requests. Finally finish the session * with uploadSessionFinish(). There are couple of constraints with * concurrent sessions to make them work. You can not send data with * uploadSessionStart() or uploadSessionFinish() call, only with * uploadSessionAppendV2() call. Also data uploaded in * uploadSessionAppendV2() call must be multiple of 4194304 bytes (except * for last uploadSessionAppendV2() with UploadSessionStartArg.close to * true, that may contain any remaining data). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<files.UploadSessionStartError>. * @param arg The request parameters. */ public filesUploadSessionStart(arg: files.UploadSessionStartArg): Promise<DropboxResponse<files.UploadSessionStartResult>>; /** * Marks the given Paper doc as archived. This action can be performed or * undone by anyone with edit permissions to the doc. Note that this * endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. This endpoint will be * retired in September 2020. Refer to the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for more information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsArchive(arg: paper.RefPaperDoc): Promise<DropboxResponse<void>>; /** * Creates a new Paper doc with the provided content. Note that this * endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. This endpoint will be * retired in September 2020. Refer to the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for more information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.PaperDocCreateError>. * @deprecated * @param arg The request parameters. */ public paperDocsCreate(arg: paper.PaperDocCreateArgs): Promise<DropboxResponse<paper.PaperDocCreateUpdateResult>>; /** * Exports and downloads Paper doc either as HTML or markdown. Note that * this endpoint will continue to work for content created by users on the * older version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsDownload(arg: paper.PaperDocExport): Promise<DropboxResponse<paper.PaperDocExportResult>>; /** * Lists the users who are explicitly invited to the Paper folder in which * the Paper doc is contained. For private folders all users (including * owner) shared on the folder are listed and for team folders all non-team * users shared on the folder are returned. Note that this endpoint will * continue to work for content created by users on the older version of * Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsFolderUsersList(arg: paper.ListUsersOnFolderArgs): Promise<DropboxResponse<paper.ListUsersOnFolderResponse>>; /** * Once a cursor has been retrieved from docsFolderUsersList(), use this to * paginate through all users on the Paper folder. Note that this endpoint * will continue to work for content created by users on the older version * of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.ListUsersCursorError>. * @deprecated * @param arg The request parameters. */ public paperDocsFolderUsersListContinue(arg: paper.ListUsersOnFolderContinueArgs): Promise<DropboxResponse<paper.ListUsersOnFolderResponse>>; /** * Retrieves folder information for the given Paper doc. This includes: - * folder sharing policy; permissions for subfolders are set by the * top-level folder. - full 'filepath', i.e. the list of folders (both * folderId and folderName) from the root folder to the folder directly * containing the Paper doc. If the Paper doc is not in any folder (aka * unfiled) the response will be empty. Note that this endpoint will * continue to work for content created by users on the older version of * Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsGetFolderInfo(arg: paper.RefPaperDoc): Promise<DropboxResponse<paper.FoldersContainingPaperDoc>>; /** * Return the list of all Paper docs according to the argument * specifications. To iterate over through the full pagination, pass the * cursor to docsListContinue(). Note that this endpoint will continue to * work for content created by users on the older version of Paper. To check * which version of Paper a user is on, use /users/features/get_values. If * the paper_as_files feature is enabled, then the user is running the new * version of Paper. Refer to the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @deprecated * @param arg The request parameters. */ public paperDocsList(arg: paper.ListPaperDocsArgs): Promise<DropboxResponse<paper.ListPaperDocsResponse>>; /** * Once a cursor has been retrieved from docsList(), use this to paginate * through all Paper doc. Note that this endpoint will continue to work for * content created by users on the older version of Paper. To check which * version of Paper a user is on, use /users/features/get_values. If the * paper_as_files feature is enabled, then the user is running the new * version of Paper. Refer to the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.ListDocsCursorError>. * @deprecated * @param arg The request parameters. */ public paperDocsListContinue(arg: paper.ListPaperDocsContinueArgs): Promise<DropboxResponse<paper.ListPaperDocsResponse>>; /** * Permanently deletes the given Paper doc. This operation is final as the * doc cannot be recovered. This action can be performed only by the doc * owner. Note that this endpoint will continue to work for content created * by users on the older version of Paper. To check which version of Paper a * user is on, use /users/features/get_values. If the paper_as_files feature * is enabled, then the user is running the new version of Paper. Refer to * the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsPermanentlyDelete(arg: paper.RefPaperDoc): Promise<DropboxResponse<void>>; /** * Gets the default sharing policy for the given Paper doc. Note that this * endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsSharingPolicyGet(arg: paper.RefPaperDoc): Promise<DropboxResponse<paper.SharingPolicy>>; /** * Sets the default sharing policy for the given Paper doc. The default * 'team_sharing_policy' can be changed only by teams, omit this field for * personal accounts. The 'public_sharing_policy' policy can't be set to the * value 'disabled' because this setting can be changed only via the team * admin console. Note that this endpoint will continue to work for content * created by users on the older version of Paper. To check which version of * Paper a user is on, use /users/features/get_values. If the paper_as_files * feature is enabled, then the user is running the new version of Paper. * Refer to the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsSharingPolicySet(arg: paper.PaperDocSharingPolicy): Promise<DropboxResponse<void>>; /** * Updates an existing Paper doc with the provided content. Note that this * endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. This endpoint will be * retired in September 2020. Refer to the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for more information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.PaperDocUpdateError>. * @deprecated * @param arg The request parameters. */ public paperDocsUpdate(arg: paper.PaperDocUpdateArgs): Promise<DropboxResponse<paper.PaperDocCreateUpdateResult>>; /** * Allows an owner or editor to add users to a Paper doc or change their * permissions using their email address or Dropbox account ID. The doc * owner's permissions cannot be changed. Note that this endpoint will * continue to work for content created by users on the older version of * Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsUsersAdd(arg: paper.AddPaperDocUser): Promise<DropboxResponse<Array<paper.AddPaperDocUserMemberResult>>>; /** * Lists all users who visited the Paper doc or users with explicit access. * This call excludes users who have been removed. The list is sorted by the * date of the visit or the share date. The list will include both users, * the explicitly shared ones as well as those who came in using the Paper * url link. Note that this endpoint will continue to work for content * created by users on the older version of Paper. To check which version of * Paper a user is on, use /users/features/get_values. If the paper_as_files * feature is enabled, then the user is running the new version of Paper. * Refer to the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsUsersList(arg: paper.ListUsersOnPaperDocArgs): Promise<DropboxResponse<paper.ListUsersOnPaperDocResponse>>; /** * Once a cursor has been retrieved from docsUsersList(), use this to * paginate through all users on the Paper doc. Note that this endpoint will * continue to work for content created by users on the older version of * Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.ListUsersCursorError>. * @deprecated * @param arg The request parameters. */ public paperDocsUsersListContinue(arg: paper.ListUsersOnPaperDocContinueArgs): Promise<DropboxResponse<paper.ListUsersOnPaperDocResponse>>; /** * Allows an owner or editor to remove users from a Paper doc using their * email address or Dropbox account ID. The doc owner cannot be removed. * Note that this endpoint will continue to work for content created by * users on the older version of Paper. To check which version of Paper a * user is on, use /users/features/get_values. If the paper_as_files feature * is enabled, then the user is running the new version of Paper. Refer to * the [Paper Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.DocLookupError>. * @deprecated * @param arg The request parameters. */ public paperDocsUsersRemove(arg: paper.RemovePaperDocUser): Promise<DropboxResponse<void>>; /** * Create a new Paper folder with the provided info. Note that this endpoint * will continue to work for content created by users on the older version * of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, * then the user is running the new version of Paper. Refer to the [Paper * Migration Guide]{@link * https://www.dropbox.com/lp/developers/reference/paper-migration-guide} * for migration information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<paper.PaperFolderCreateError>. * @deprecated * @param arg The request parameters. */ public paperFoldersCreate(arg: paper.PaperFolderCreateArg): Promise<DropboxResponse<paper.PaperFolderCreateResult>>; /** * Adds specified members to a file. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.AddFileMemberError>. * @param arg The request parameters. */ public sharingAddFileMember(arg: sharing.AddFileMemberArgs): Promise<DropboxResponse<Array<sharing.FileMemberActionResult>>>; /** * Allows an owner or editor (if the ACL update policy allows) of a shared * folder to add another member. For the new member to get access to all the * functionality for this folder, you will need to call mountFolder() on * their behalf. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.AddFolderMemberError>. * @param arg The request parameters. */ public sharingAddFolderMember(arg: sharing.AddFolderMemberArg): Promise<DropboxResponse<void>>; /** * Returns the status of an asynchronous job. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public sharingCheckJobStatus(arg: async.PollArg): Promise<DropboxResponse<sharing.JobStatus>>; /** * Returns the status of an asynchronous job for sharing a folder. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public sharingCheckRemoveMemberJobStatus(arg: async.PollArg): Promise<DropboxResponse<sharing.RemoveMemberJobStatus>>; /** * Returns the status of an asynchronous job for sharing a folder. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public sharingCheckShareJobStatus(arg: async.PollArg): Promise<DropboxResponse<sharing.ShareFolderJobStatus>>; /** * Create a shared link. If a shared link already exists for the given path, * that link is returned. Previously, it was technically possible to break a * shared link by moving or renaming the corresponding file or folder. In * the future, this will no longer be the case, so your app shouldn't rely * on this behavior. Instead, if your app needs to revoke a shared link, use * revokeSharedLink(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.CreateSharedLinkError>. * @deprecated * @param arg The request parameters. */ public sharingCreateSharedLink(arg: sharing.CreateSharedLinkArg): Promise<DropboxResponse<sharing.PathLinkMetadata>>; /** * Create a shared link with custom settings. If no settings are given then * the default visibility is RequestedVisibility.public (The resolved * visibility, though, may depend on other aspects such as team and shared * folder settings). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.CreateSharedLinkWithSettingsError>. * @param arg The request parameters. */ public sharingCreateSharedLinkWithSettings(arg: sharing.CreateSharedLinkWithSettingsArg): Promise<DropboxResponse<sharing.FileLinkMetadataReference|sharing.FolderLinkMetadataReference|sharing.SharedLinkMetadataReference>>; /** * Returns shared file metadata. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.GetFileMetadataError>. * @param arg The request parameters. */ public sharingGetFileMetadata(arg: sharing.GetFileMetadataArg): Promise<DropboxResponse<sharing.SharedFileMetadata>>; /** * Returns shared file metadata. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.SharingUserError>. * @param arg The request parameters. */ public sharingGetFileMetadataBatch(arg: sharing.GetFileMetadataBatchArg): Promise<DropboxResponse<Array<sharing.GetFileMetadataBatchResult>>>; /** * Returns shared folder metadata by its folder ID. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.SharedFolderAccessError>. * @param arg The request parameters. */ public sharingGetFolderMetadata(arg: sharing.GetMetadataArgs): Promise<DropboxResponse<sharing.SharedFolderMetadata>>; /** * Download the shared link's file from a user's Dropbox. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.GetSharedLinkFileError>. * @param arg The request parameters. */ public sharingGetSharedLinkFile(arg: sharing.GetSharedLinkFileArg): Promise<DropboxResponse<sharing.FileLinkMetadataReference|sharing.FolderLinkMetadataReference|sharing.SharedLinkMetadataReference>>; /** * Get the shared link's metadata. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.SharedLinkError>. * @param arg The request parameters. */ public sharingGetSharedLinkMetadata(arg: sharing.GetSharedLinkMetadataArg): Promise<DropboxResponse<sharing.FileLinkMetadataReference|sharing.FolderLinkMetadataReference|sharing.SharedLinkMetadataReference>>; /** * Returns a list of LinkMetadata objects for this user, including * collection links. If no path is given, returns a list of all shared links * for the current user, including collection links, up to a maximum of 1000 * links. If a non-empty path is given, returns a list of all shared links * that allow access to the given path. Collection links are never returned * in this case. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.GetSharedLinksError>. * @deprecated * @param arg The request parameters. */ public sharingGetSharedLinks(arg: sharing.GetSharedLinksArg): Promise<DropboxResponse<sharing.GetSharedLinksResult>>; /** * Use to obtain the members who have been invited to a file, both inherited * and uninherited members. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ListFileMembersError>. * @param arg The request parameters. */ public sharingListFileMembers(arg: sharing.ListFileMembersArg): Promise<DropboxResponse<sharing.SharedFileMembers>>; /** * Get members of multiple files at once. The arguments to this route are * more limited, and the limit on query result size per file is more strict. * To customize the results more, use the individual file endpoint. * Inherited users and groups are not included in the result, and * permissions are not returned for this endpoint. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.SharingUserError>. * @param arg The request parameters. */ public sharingListFileMembersBatch(arg: sharing.ListFileMembersBatchArg): Promise<DropboxResponse<Array<sharing.ListFileMembersBatchResult>>>; /** * Once a cursor has been retrieved from listFileMembers() or * listFileMembersBatch(), use this to paginate through all shared file * members. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ListFileMembersContinueError>. * @param arg The request parameters. */ public sharingListFileMembersContinue(arg: sharing.ListFileMembersContinueArg): Promise<DropboxResponse<sharing.SharedFileMembers>>; /** * Returns shared folder membership by its folder ID. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.SharedFolderAccessError>. * @param arg The request parameters. */ public sharingListFolderMembers(arg: sharing.ListFolderMembersArgs): Promise<DropboxResponse<sharing.SharedFolderMembers>>; /** * Once a cursor has been retrieved from listFolderMembers(), use this to * paginate through all shared folder members. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ListFolderMembersContinueError>. * @param arg The request parameters. */ public sharingListFolderMembersContinue(arg: sharing.ListFolderMembersContinueArg): Promise<DropboxResponse<sharing.SharedFolderMembers>>; /** * Return the list of all shared folders the current user has access to. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public sharingListFolders(arg: sharing.ListFoldersArgs): Promise<DropboxResponse<sharing.ListFoldersResult>>; /** * Once a cursor has been retrieved from listFolders(), use this to paginate * through all shared folders. The cursor must come from a previous call to * listFolders() or listFoldersContinue(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ListFoldersContinueError>. * @param arg The request parameters. */ public sharingListFoldersContinue(arg: sharing.ListFoldersContinueArg): Promise<DropboxResponse<sharing.ListFoldersResult>>; /** * Return the list of all shared folders the current user can mount or * unmount. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public sharingListMountableFolders(arg: sharing.ListFoldersArgs): Promise<DropboxResponse<sharing.ListFoldersResult>>; /** * Once a cursor has been retrieved from listMountableFolders(), use this to * paginate through all mountable shared folders. The cursor must come from * a previous call to listMountableFolders() or * listMountableFoldersContinue(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ListFoldersContinueError>. * @param arg The request parameters. */ public sharingListMountableFoldersContinue(arg: sharing.ListFoldersContinueArg): Promise<DropboxResponse<sharing.ListFoldersResult>>; /** * Returns a list of all files shared with current user. Does not include * files the user has received via shared folders, and does not include * unclaimed invitations. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.SharingUserError>. * @param arg The request parameters. */ public sharingListReceivedFiles(arg: sharing.ListFilesArg): Promise<DropboxResponse<sharing.ListFilesResult>>; /** * Get more results with a cursor from listReceivedFiles(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ListFilesContinueError>. * @param arg The request parameters. */ public sharingListReceivedFilesContinue(arg: sharing.ListFilesContinueArg): Promise<DropboxResponse<sharing.ListFilesResult>>; /** * List shared links of this user. If no path is given, returns a list of * all shared links for the current user. For members of business teams * using team space and member folders, returns all shared links in the team * member's home folder unless the team space ID is specified in the request * header. For more information, refer to the [Namespace Guide]{@link * https://www.dropbox.com/developers/reference/namespace-guide}. If a * non-empty path is given, returns a list of all shared links that allow * access to the given path - direct links to the given path and links to * parent folders of the given path. Links to parent folders can be * suppressed by setting direct_only to true. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ListSharedLinksError>. * @param arg The request parameters. */ public sharingListSharedLinks(arg: sharing.ListSharedLinksArg): Promise<DropboxResponse<sharing.ListSharedLinksResult>>; /** * Modify the shared link's settings. If the requested visibility conflict * with the shared links policy of the team or the shared folder (in case * the linked file is part of a shared folder) then the * LinkPermissions.resolved_visibility of the returned SharedLinkMetadata * will reflect the actual visibility of the shared link and the * LinkPermissions.requested_visibility will reflect the requested * visibility. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ModifySharedLinkSettingsError>. * @param arg The request parameters. */ public sharingModifySharedLinkSettings(arg: sharing.ModifySharedLinkSettingsArgs): Promise<DropboxResponse<sharing.FileLinkMetadataReference|sharing.FolderLinkMetadataReference|sharing.SharedLinkMetadataReference>>; /** * The current user mounts the designated folder. Mount a shared folder for * a user after they have been added as a member. Once mounted, the shared * folder will appear in their Dropbox. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.MountFolderError>. * @param arg The request parameters. */ public sharingMountFolder(arg: sharing.MountFolderArg): Promise<DropboxResponse<sharing.SharedFolderMetadata>>; /** * The current user relinquishes their membership in the designated file. * Note that the current user may still have inherited access to this file * through the parent folder. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.RelinquishFileMembershipError>. * @param arg The request parameters. */ public sharingRelinquishFileMembership(arg: sharing.RelinquishFileMembershipArg): Promise<DropboxResponse<void>>; /** * The current user relinquishes their membership in the designated shared * folder and will no longer have access to the folder. A folder owner * cannot relinquish membership in their own folder. This will run * synchronously if leave_a_copy is false, and asynchronously if * leave_a_copy is true. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.RelinquishFolderMembershipError>. * @param arg The request parameters. */ public sharingRelinquishFolderMembership(arg: sharing.RelinquishFolderMembershipArg): Promise<DropboxResponse<async.LaunchEmptyResult>>; /** * Identical to remove_file_member_2 but with less information returned. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.RemoveFileMemberError>. * @deprecated * @param arg The request parameters. */ public sharingRemoveFileMember(arg: sharing.RemoveFileMemberArg): Promise<DropboxResponse<sharing.FileMemberActionIndividualResult>>; /** * Removes a specified member from the file. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.RemoveFileMemberError>. * @param arg The request parameters. */ public sharingRemoveFileMember2(arg: sharing.RemoveFileMemberArg): Promise<DropboxResponse<sharing.FileMemberRemoveActionResult>>; /** * Allows an owner or editor (if the ACL update policy allows) of a shared * folder to remove another member. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.RemoveFolderMemberError>. * @param arg The request parameters. */ public sharingRemoveFolderMember(arg: sharing.RemoveFolderMemberArg): Promise<DropboxResponse<async.LaunchResultBase>>; /** * Revoke a shared link. Note that even after revoking a shared link to a * file, the file may be accessible if there are shared links leading to any * of the file parent folders. To list all shared links that enable access * to a specific file, you can use the listSharedLinks() with the file as * the ListSharedLinksArg.path argument. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.RevokeSharedLinkError>. * @param arg The request parameters. */ public sharingRevokeSharedLink(arg: sharing.RevokeSharedLinkArg): Promise<DropboxResponse<void>>; /** * Change the inheritance policy of an existing Shared Folder. Only * permitted for shared folders in a shared team root. If a * ShareFolderLaunch.async_job_id is returned, you'll need to call * checkShareJobStatus() until the action completes to get the metadata for * the folder. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.SetAccessInheritanceError>. * @param arg The request parameters. */ public sharingSetAccessInheritance(arg: sharing.SetAccessInheritanceArg): Promise<DropboxResponse<sharing.ShareFolderLaunch>>; /** * Share a folder with collaborators. Most sharing will be completed * synchronously. Large folders will be completed asynchronously. To make * testing the async case repeatable, set `ShareFolderArg.force_async`. If a * ShareFolderLaunch.async_job_id is returned, you'll need to call * checkShareJobStatus() until the action completes to get the metadata for * the folder. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.ShareFolderError>. * @param arg The request parameters. */ public sharingShareFolder(arg: sharing.ShareFolderArg): Promise<DropboxResponse<sharing.ShareFolderLaunch>>; /** * Transfer ownership of a shared folder to a member of the shared folder. * User must have AccessLevel.owner access to the shared folder to perform a * transfer. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.TransferFolderError>. * @param arg The request parameters. */ public sharingTransferFolder(arg: sharing.TransferFolderArg): Promise<DropboxResponse<void>>; /** * The current user unmounts the designated folder. They can re-mount the * folder at a later time using mountFolder(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.UnmountFolderError>. * @param arg The request parameters. */ public sharingUnmountFolder(arg: sharing.UnmountFolderArg): Promise<DropboxResponse<void>>; /** * Remove all members from this file. Does not remove inherited members. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.UnshareFileError>. * @param arg The request parameters. */ public sharingUnshareFile(arg: sharing.UnshareFileArg): Promise<DropboxResponse<void>>; /** * Allows a shared folder owner to unshare the folder. You'll need to call * checkJobStatus() to determine if the action has completed successfully. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.UnshareFolderError>. * @param arg The request parameters. */ public sharingUnshareFolder(arg: sharing.UnshareFolderArg): Promise<DropboxResponse<async.LaunchEmptyResult>>; /** * Changes a member's access on a shared file. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.FileMemberActionError>. * @param arg The request parameters. */ public sharingUpdateFileMember(arg: sharing.UpdateFileMemberArgs): Promise<DropboxResponse<sharing.MemberAccessLevelResult>>; /** * Allows an owner or editor of a shared folder to update another member's * permissions. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.UpdateFolderMemberError>. * @param arg The request parameters. */ public sharingUpdateFolderMember(arg: sharing.UpdateFolderMemberArg): Promise<DropboxResponse<sharing.MemberAccessLevelResult>>; /** * Update the sharing policies for a shared folder. User must have * AccessLevel.owner access to the shared folder to update its policies. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<sharing.UpdateFolderPolicyError>. * @param arg The request parameters. */ public sharingUpdateFolderPolicy(arg: sharing.UpdateFolderPolicyArg): Promise<DropboxResponse<sharing.SharedFolderMetadata>>; /** * List all device sessions of a team's member. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ListMemberDevicesError>. * @param arg The request parameters. */ public teamDevicesListMemberDevices(arg: team.ListMemberDevicesArg): Promise<DropboxResponse<team.ListMemberDevicesResult>>; /** * List all device sessions of a team. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ListMembersDevicesError>. * @param arg The request parameters. */ public teamDevicesListMembersDevices(arg: team.ListMembersDevicesArg): Promise<DropboxResponse<team.ListMembersDevicesResult>>; /** * List all device sessions of a team. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ListTeamDevicesError>. * @deprecated * @param arg The request parameters. */ public teamDevicesListTeamDevices(arg: team.ListTeamDevicesArg): Promise<DropboxResponse<team.ListTeamDevicesResult>>; /** * Revoke a device session of a team's member. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.RevokeDeviceSessionError>. * @param arg The request parameters. */ public teamDevicesRevokeDeviceSession(arg: team.RevokeDeviceSessionArg): Promise<DropboxResponse<void>>; /** * Revoke a list of device sessions of team members. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.RevokeDeviceSessionBatchError>. * @param arg The request parameters. */ public teamDevicesRevokeDeviceSessionBatch(arg: team.RevokeDeviceSessionBatchArg): Promise<DropboxResponse<team.RevokeDeviceSessionBatchResult>>; /** * Get the values for one or more featues. This route allows you to check * your account's capability for what feature you can access or what value * you have for certain features. Permission : Team information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.FeaturesGetValuesBatchError>. * @param arg The request parameters. */ public teamFeaturesGetValues(arg: team.FeaturesGetValuesBatchArg): Promise<DropboxResponse<team.FeaturesGetValuesBatchResult>>; /** * Retrieves information about a team. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. */ public teamGetInfo(): Promise<DropboxResponse<team.TeamGetInfoResult>>; /** * Creates a new, empty group, with a requested name. Permission : Team * member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupCreateError>. * @param arg The request parameters. */ public teamGroupsCreate(arg: team.GroupCreateArg): Promise<DropboxResponse<team.GroupFullInfo>>; /** * Deletes a group. The group is deleted immediately. However the revoking * of group-owned resources may take additional time. Use the * groupsJobStatusGet() to determine whether this process has completed. * Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupDeleteError>. * @param arg The request parameters. */ public teamGroupsDelete(arg: team.GroupSelector): Promise<DropboxResponse<async.LaunchEmptyResult>>; /** * Retrieves information about one or more groups. Note that the optional * field GroupFullInfo.members is not returned for system-managed groups. * Permission : Team Information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupsGetInfoError>. * @param arg The request parameters. */ public teamGroupsGetInfo(arg: team.GroupsSelector): Promise<DropboxResponse<team.GroupsGetInfoResult>>; /** * Once an async_job_id is returned from groupsDelete(), groupsMembersAdd() * , or groupsMembersRemove() use this method to poll the status of * granting/revoking group members' access to group-owned resources. * Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupsPollError>. * @param arg The request parameters. */ public teamGroupsJobStatusGet(arg: async.PollArg): Promise<DropboxResponse<async.PollEmptyResult>>; /** * Lists groups on a team. Permission : Team Information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public teamGroupsList(arg: team.GroupsListArg): Promise<DropboxResponse<team.GroupsListResult>>; /** * Once a cursor has been retrieved from groupsList(), use this to paginate * through all groups. Permission : Team Information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupsListContinueError>. * @param arg The request parameters. */ public teamGroupsListContinue(arg: team.GroupsListContinueArg): Promise<DropboxResponse<team.GroupsListResult>>; /** * Adds members to a group. The members are added immediately. However the * granting of group-owned resources may take additional time. Use the * groupsJobStatusGet() to determine whether this process has completed. * Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupMembersAddError>. * @param arg The request parameters. */ public teamGroupsMembersAdd(arg: team.GroupMembersAddArg): Promise<DropboxResponse<team.GroupMembersChangeResult>>; /** * Lists members of a group. Permission : Team Information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupSelectorError>. * @param arg The request parameters. */ public teamGroupsMembersList(arg: team.GroupsMembersListArg): Promise<DropboxResponse<team.GroupsMembersListResult>>; /** * Once a cursor has been retrieved from groupsMembersList(), use this to * paginate through all members of the group. Permission : Team information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupsMembersListContinueError>. * @param arg The request parameters. */ public teamGroupsMembersListContinue(arg: team.GroupsMembersListContinueArg): Promise<DropboxResponse<team.GroupsMembersListResult>>; /** * Removes members from a group. The members are removed immediately. * However the revoking of group-owned resources may take additional time. * Use the groupsJobStatusGet() to determine whether this process has * completed. This method permits removing the only owner of a group, even * in cases where this is not possible via the web client. Permission : Team * member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupMembersRemoveError>. * @param arg The request parameters. */ public teamGroupsMembersRemove(arg: team.GroupMembersRemoveArg): Promise<DropboxResponse<team.GroupMembersChangeResult>>; /** * Sets a member's access type in a group. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupMemberSetAccessTypeError>. * @param arg The request parameters. */ public teamGroupsMembersSetAccessType(arg: team.GroupMembersSetAccessTypeArg): Promise<DropboxResponse<team.GroupsGetInfoResult>>; /** * Updates a group's name and/or external ID. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.GroupUpdateError>. * @param arg The request parameters. */ public teamGroupsUpdate(arg: team.GroupUpdateArgs): Promise<DropboxResponse<team.GroupFullInfo>>; /** * Creates new legal hold policy. Note: Legal Holds is a paid add-on. Not * all teams have the feature. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.LegalHoldsPolicyCreateError>. * @param arg The request parameters. */ public teamLegalHoldsCreatePolicy(arg: team.LegalHoldsPolicyCreateArg): Promise<DropboxResponse<team.LegalHoldsPolicyCreateResult>>; /** * Gets a legal hold by Id. Note: Legal Holds is a paid add-on. Not all * teams have the feature. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.LegalHoldsGetPolicyError>. * @param arg The request parameters. */ public teamLegalHoldsGetPolicy(arg: team.LegalHoldsGetPolicyArg): Promise<DropboxResponse<team.LegalHoldsGetPolicyResult>>; /** * List the file metadata that's under the hold. Note: Legal Holds is a paid * add-on. Not all teams have the feature. Permission : Team member file * access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.LegalHoldsListHeldRevisionsError>. * @param arg The request parameters. */ public teamLegalHoldsListHeldRevisions(arg: team.LegalHoldsListHeldRevisionsArg): Promise<DropboxResponse<team.LegalHoldsListHeldRevisionResult>>; /** * Continue listing the file metadata that's under the hold. Note: Legal * Holds is a paid add-on. Not all teams have the feature. Permission : Team * member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.LegalHoldsListHeldRevisionsError>. * @param arg The request parameters. */ public teamLegalHoldsListHeldRevisionsContinue(arg: team.LegalHoldsListHeldRevisionsContinueArg): Promise<DropboxResponse<team.LegalHoldsListHeldRevisionResult>>; /** * Lists legal holds on a team. Note: Legal Holds is a paid add-on. Not all * teams have the feature. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.LegalHoldsListPoliciesError>. * @param arg The request parameters. */ public teamLegalHoldsListPolicies(arg: team.LegalHoldsListPoliciesArg): Promise<DropboxResponse<team.LegalHoldsListPoliciesResult>>; /** * Releases a legal hold by Id. Note: Legal Holds is a paid add-on. Not all * teams have the feature. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.LegalHoldsPolicyReleaseError>. * @param arg The request parameters. */ public teamLegalHoldsReleasePolicy(arg: team.LegalHoldsPolicyReleaseArg): Promise<DropboxResponse<void>>; /** * Updates a legal hold. Note: Legal Holds is a paid add-on. Not all teams * have the feature. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.LegalHoldsPolicyUpdateError>. * @param arg The request parameters. */ public teamLegalHoldsUpdatePolicy(arg: team.LegalHoldsPolicyUpdateArg): Promise<DropboxResponse<team.LegalHoldsPolicyUpdateResult>>; /** * List all linked applications of the team member. Note, this endpoint does * not list any team-linked applications. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ListMemberAppsError>. * @param arg The request parameters. */ public teamLinkedAppsListMemberLinkedApps(arg: team.ListMemberAppsArg): Promise<DropboxResponse<team.ListMemberAppsResult>>; /** * List all applications linked to the team members' accounts. Note, this * endpoint does not list any team-linked applications. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ListMembersAppsError>. * @param arg The request parameters. */ public teamLinkedAppsListMembersLinkedApps(arg: team.ListMembersAppsArg): Promise<DropboxResponse<team.ListMembersAppsResult>>; /** * List all applications linked to the team members' accounts. Note, this * endpoint doesn't list any team-linked applications. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ListTeamAppsError>. * @deprecated * @param arg The request parameters. */ public teamLinkedAppsListTeamLinkedApps(arg: team.ListTeamAppsArg): Promise<DropboxResponse<team.ListTeamAppsResult>>; /** * Revoke a linked application of the team member. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.RevokeLinkedAppError>. * @param arg The request parameters. */ public teamLinkedAppsRevokeLinkedApp(arg: team.RevokeLinkedApiAppArg): Promise<DropboxResponse<void>>; /** * Revoke a list of linked applications of the team members. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.RevokeLinkedAppBatchError>. * @param arg The request parameters. */ public teamLinkedAppsRevokeLinkedAppBatch(arg: team.RevokeLinkedApiAppBatchArg): Promise<DropboxResponse<team.RevokeLinkedAppBatchResult>>; /** * Add users to member space limits excluded users list. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ExcludedUsersUpdateError>. * @param arg The request parameters. */ public teamMemberSpaceLimitsExcludedUsersAdd(arg: team.ExcludedUsersUpdateArg): Promise<DropboxResponse<team.ExcludedUsersUpdateResult>>; /** * List member space limits excluded users. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ExcludedUsersListError>. * @param arg The request parameters. */ public teamMemberSpaceLimitsExcludedUsersList(arg: team.ExcludedUsersListArg): Promise<DropboxResponse<team.ExcludedUsersListResult>>; /** * Continue listing member space limits excluded users. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ExcludedUsersListContinueError>. * @param arg The request parameters. */ public teamMemberSpaceLimitsExcludedUsersListContinue(arg: team.ExcludedUsersListContinueArg): Promise<DropboxResponse<team.ExcludedUsersListResult>>; /** * Remove users from member space limits excluded users list. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.ExcludedUsersUpdateError>. * @param arg The request parameters. */ public teamMemberSpaceLimitsExcludedUsersRemove(arg: team.ExcludedUsersUpdateArg): Promise<DropboxResponse<team.ExcludedUsersUpdateResult>>; /** * Get users custom quota. Returns none as the custom quota if none was set. * A maximum of 1000 members can be specified in a single call. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.CustomQuotaError>. * @param arg The request parameters. */ public teamMemberSpaceLimitsGetCustomQuota(arg: team.CustomQuotaUsersArg): Promise<DropboxResponse<Array<team.CustomQuotaResult>>>; /** * Remove users custom quota. A maximum of 1000 members can be specified in * a single call. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.CustomQuotaError>. * @param arg The request parameters. */ public teamMemberSpaceLimitsRemoveCustomQuota(arg: team.CustomQuotaUsersArg): Promise<DropboxResponse<Array<team.RemoveCustomQuotaResult>>>; /** * Set users custom quota. Custom quota has to be at least 15GB. A maximum * of 1000 members can be specified in a single call. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.SetCustomQuotaError>. * @param arg The request parameters. */ public teamMemberSpaceLimitsSetCustomQuota(arg: team.SetCustomQuotaArg): Promise<DropboxResponse<Array<team.CustomQuotaResult>>>; /** * Adds members to a team. Permission : Team member management A maximum of * 20 members can be specified in a single call. If no Dropbox account * exists with the email address specified, a new Dropbox account will be * created with the given email address, and that account will be invited to * the team. If a personal Dropbox account exists with the email address * specified in the call, this call will create a placeholder Dropbox * account for the user on the team and send an email inviting the user to * migrate their existing personal account onto the team. Team member * management apps are required to set an initial given_name and surname for * a user to use in the team invitation and for 'Perform as team member' * actions taken on the user before they become 'active'. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public teamMembersAddV2(arg: team.MembersAddV2Arg): Promise<DropboxResponse<team.MembersAddLaunchV2Result>>; /** * Adds members to a team. Permission : Team member management A maximum of * 20 members can be specified in a single call. If no Dropbox account * exists with the email address specified, a new Dropbox account will be * created with the given email address, and that account will be invited to * the team. If a personal Dropbox account exists with the email address * specified in the call, this call will create a placeholder Dropbox * account for the user on the team and send an email inviting the user to * migrate their existing personal account onto the team. Team member * management apps are required to set an initial given_name and surname for * a user to use in the team invitation and for 'Perform as team member' * actions taken on the user before they become 'active'. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public teamMembersAdd(arg: team.MembersAddArg): Promise<DropboxResponse<team.MembersAddLaunch>>; /** * Once an async_job_id is returned from membersAddV2() , use this to poll * the status of the asynchronous request. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public teamMembersAddJobStatusGetV2(arg: async.PollArg): Promise<DropboxResponse<team.MembersAddJobStatusV2Result>>; /** * Once an async_job_id is returned from membersAdd() , use this to poll the * status of the asynchronous request. Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public teamMembersAddJobStatusGet(arg: async.PollArg): Promise<DropboxResponse<team.MembersAddJobStatus>>; /** * Deletes a team member's profile photo. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersDeleteProfilePhotoError>. * @param arg The request parameters. */ public teamMembersDeleteProfilePhotoV2(arg: team.MembersDeleteProfilePhotoArg): Promise<DropboxResponse<team.TeamMemberInfoV2Result>>; /** * Deletes a team member's profile photo. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersDeleteProfilePhotoError>. * @param arg The request parameters. */ public teamMembersDeleteProfilePhoto(arg: team.MembersDeleteProfilePhotoArg): Promise<DropboxResponse<team.TeamMemberInfo>>; /** * Get available TeamMemberRoles for the connected team. To be used with * membersSetAdminPermissionsV2(). Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. */ public teamMembersGetAvailableTeamMemberRoles(): Promise<DropboxResponse<team.MembersGetAvailableTeamMemberRolesResult>>; /** * Returns information about multiple team members. Permission : Team * information This endpoint will return MembersGetInfoItem.id_not_found, * for IDs (or emails) that cannot be matched to a valid team member. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersGetInfoError>. * @param arg The request parameters. */ public teamMembersGetInfoV2(arg: team.MembersGetInfoV2Arg): Promise<DropboxResponse<team.MembersGetInfoV2Result>>; /** * Returns information about multiple team members. Permission : Team * information This endpoint will return MembersGetInfoItem.id_not_found, * for IDs (or emails) that cannot be matched to a valid team member. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersGetInfoError>. * @param arg The request parameters. */ public teamMembersGetInfo(arg: team.MembersGetInfoArgs): Promise<DropboxResponse<team.MembersGetInfoResult>>; /** * Lists members of a team. Permission : Team information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersListError>. * @param arg The request parameters. */ public teamMembersListV2(arg: team.MembersListArg): Promise<DropboxResponse<team.MembersListV2Result>>; /** * Lists members of a team. Permission : Team information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersListError>. * @param arg The request parameters. */ public teamMembersList(arg: team.MembersListArg): Promise<DropboxResponse<team.MembersListResult>>; /** * Once a cursor has been retrieved from membersListV2(), use this to * paginate through all team members. Permission : Team information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersListContinueError>. * @param arg The request parameters. */ public teamMembersListContinueV2(arg: team.MembersListContinueArg): Promise<DropboxResponse<team.MembersListV2Result>>; /** * Once a cursor has been retrieved from membersList(), use this to paginate * through all team members. Permission : Team information. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersListContinueError>. * @param arg The request parameters. */ public teamMembersListContinue(arg: team.MembersListContinueArg): Promise<DropboxResponse<team.MembersListResult>>; /** * Moves removed member's files to a different member. This endpoint * initiates an asynchronous job. To obtain the final result of the job, the * client should periodically poll * membersMoveFormerMemberFilesJobStatusCheck(). Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersTransferFormerMembersFilesError>. * @param arg The request parameters. */ public teamMembersMoveFormerMemberFiles(arg: team.MembersDataTransferArg): Promise<DropboxResponse<async.LaunchEmptyResult>>; /** * Once an async_job_id is returned from membersMoveFormerMemberFiles() , * use this to poll the status of the asynchronous request. Permission : * Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public teamMembersMoveFormerMemberFilesJobStatusCheck(arg: async.PollArg): Promise<DropboxResponse<async.PollEmptyResult>>; /** * Recover a deleted member. Permission : Team member management Exactly one * of team_member_id, email, or external_id must be provided to identify the * user account. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersRecoverError>. * @param arg The request parameters. */ public teamMembersRecover(arg: team.MembersRecoverArg): Promise<DropboxResponse<void>>; /** * Removes a member from a team. Permission : Team member management Exactly * one of team_member_id, email, or external_id must be provided to identify * the user account. Accounts can be recovered via membersRecover() for a 7 * day period or until the account has been permanently deleted or * transferred to another account (whichever comes first). Calling * membersAdd() while a user is still recoverable on your team will return * with MemberAddResult.user_already_on_team. Accounts can have their files * transferred via the admin console for a limited time, based on the * version history length associated with the team (180 days for most * teams). This endpoint may initiate an asynchronous job. To obtain the * final result of the job, the client should periodically poll * membersRemoveJobStatusGet(). * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersRemoveError>. * @param arg The request parameters. */ public teamMembersRemove(arg: team.MembersRemoveArg): Promise<DropboxResponse<async.LaunchEmptyResult>>; /** * Once an async_job_id is returned from membersRemove() , use this to poll * the status of the asynchronous request. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public teamMembersRemoveJobStatusGet(arg: async.PollArg): Promise<DropboxResponse<async.PollEmptyResult>>; /** * Add secondary emails to users. Permission : Team member management. * Emails that are on verified domains will be verified automatically. For * each email address not on a verified domain a verification email will be * sent. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.AddSecondaryEmailsError>. * @param arg The request parameters. */ public teamMembersSecondaryEmailsAdd(arg: team.AddSecondaryEmailsArg): Promise<DropboxResponse<team.AddSecondaryEmailsResult>>; /** * Delete secondary emails from users Permission : Team member management. * Users will be notified of deletions of verified secondary emails at both * the secondary email and their primary email. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public teamMembersSecondaryEmailsDelete(arg: team.DeleteSecondaryEmailsArg): Promise<DropboxResponse<team.DeleteSecondaryEmailsResult>>; /** * Resend secondary email verification emails. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public teamMembersSecondaryEmailsResendVerificationEmails(arg: team.ResendVerificationEmailArg): Promise<DropboxResponse<team.ResendVerificationEmailResult>>; /** * Sends welcome email to pending team member. Permission : Team member * management Exactly one of team_member_id, email, or external_id must be * provided to identify the user account. No-op if team member is not * pending. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSendWelcomeError>. * @param arg The request parameters. */ public teamMembersSendWelcomeEmail(arg: team.UserSelectorArg): Promise<DropboxResponse<void>>; /** * Updates a team member's permissions. Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSetPermissions2Error>. * @param arg The request parameters. */ public teamMembersSetAdminPermissionsV2(arg: team.MembersSetPermissions2Arg): Promise<DropboxResponse<team.MembersSetPermissions2Result>>; /** * Updates a team member's permissions. Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSetPermissionsError>. * @param arg The request parameters. */ public teamMembersSetAdminPermissions(arg: team.MembersSetPermissionsArg): Promise<DropboxResponse<team.MembersSetPermissionsResult>>; /** * Updates a team member's profile. Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSetProfileError>. * @param arg The request parameters. */ public teamMembersSetProfileV2(arg: team.MembersSetProfileArg): Promise<DropboxResponse<team.TeamMemberInfoV2Result>>; /** * Updates a team member's profile. Permission : Team member management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSetProfileError>. * @param arg The request parameters. */ public teamMembersSetProfile(arg: team.MembersSetProfileArg): Promise<DropboxResponse<team.TeamMemberInfo>>; /** * Updates a team member's profile photo. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSetProfilePhotoError>. * @param arg The request parameters. */ public teamMembersSetProfilePhotoV2(arg: team.MembersSetProfilePhotoArg): Promise<DropboxResponse<team.TeamMemberInfoV2Result>>; /** * Updates a team member's profile photo. Permission : Team member * management. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSetProfilePhotoError>. * @param arg The request parameters. */ public teamMembersSetProfilePhoto(arg: team.MembersSetProfilePhotoArg): Promise<DropboxResponse<team.TeamMemberInfo>>; /** * Suspend a member from a team. Permission : Team member management Exactly * one of team_member_id, email, or external_id must be provided to identify * the user account. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersSuspendError>. * @param arg The request parameters. */ public teamMembersSuspend(arg: team.MembersDeactivateArg): Promise<DropboxResponse<void>>; /** * Unsuspend a member from a team. Permission : Team member management * Exactly one of team_member_id, email, or external_id must be provided to * identify the user account. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.MembersUnsuspendError>. * @param arg The request parameters. */ public teamMembersUnsuspend(arg: team.MembersUnsuspendArg): Promise<DropboxResponse<void>>; /** * Returns a list of all team-accessible namespaces. This list includes team * folders, shared folders containing team members, team members' home * namespaces, and team members' app folders. Home namespaces and app * folders are always owned by this team or members of the team, but shared * folders may be owned by other users or other teams. Duplicates may occur * in the list. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamNamespacesListError>. * @param arg The request parameters. */ public teamNamespacesList(arg: team.TeamNamespacesListArg): Promise<DropboxResponse<team.TeamNamespacesListResult>>; /** * Once a cursor has been retrieved from namespacesList(), use this to * paginate through all team-accessible namespaces. Duplicates may occur in * the list. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamNamespacesListContinueError>. * @param arg The request parameters. */ public teamNamespacesListContinue(arg: team.TeamNamespacesListContinueArg): Promise<DropboxResponse<team.TeamNamespacesListResult>>; /** * Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.ModifyTemplateError>. * @deprecated * @param arg The request parameters. */ public teamPropertiesTemplateAdd(arg: file_properties.AddTemplateArg): Promise<DropboxResponse<file_properties.AddTemplateResult>>; /** * Permission : Team member file access. The scope for the route is * files.team_metadata.write. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @deprecated * @param arg The request parameters. */ public teamPropertiesTemplateGet(arg: file_properties.GetTemplateArg): Promise<DropboxResponse<file_properties.GetTemplateResult>>; /** * Permission : Team member file access. The scope for the route is * files.team_metadata.write. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.TemplateError>. * @deprecated */ public teamPropertiesTemplateList(): Promise<DropboxResponse<file_properties.ListTemplateResult>>; /** * Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<file_properties.ModifyTemplateError>. * @deprecated * @param arg The request parameters. */ public teamPropertiesTemplateUpdate(arg: file_properties.UpdateTemplateArg): Promise<DropboxResponse<file_properties.UpdateTemplateResult>>; /** * Retrieves reporting data about a team's user activity. Deprecated: Will * be removed on July 1st 2021. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.DateRangeError>. * @deprecated * @param arg The request parameters. */ public teamReportsGetActivity(arg: team.DateRange): Promise<DropboxResponse<team.GetActivityReport>>; /** * Retrieves reporting data about a team's linked devices. Deprecated: Will * be removed on July 1st 2021. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.DateRangeError>. * @deprecated * @param arg The request parameters. */ public teamReportsGetDevices(arg: team.DateRange): Promise<DropboxResponse<team.GetDevicesReport>>; /** * Retrieves reporting data about a team's membership. Deprecated: Will be * removed on July 1st 2021. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.DateRangeError>. * @deprecated * @param arg The request parameters. */ public teamReportsGetMembership(arg: team.DateRange): Promise<DropboxResponse<team.GetMembershipReport>>; /** * Retrieves reporting data about a team's storage usage. Deprecated: Will * be removed on July 1st 2021. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.DateRangeError>. * @deprecated * @param arg The request parameters. */ public teamReportsGetStorage(arg: team.DateRange): Promise<DropboxResponse<team.GetStorageReport>>; /** * Sets an archived team folder's status to active. Permission : Team member * file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderActivateError>. * @param arg The request parameters. */ public teamTeamFolderActivate(arg: team.TeamFolderIdArg): Promise<DropboxResponse<team.TeamFolderMetadata>>; /** * Sets an active team folder's status to archived and removes all folder * and file members. This endpoint cannot be used for teams that have a * shared team space. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderArchiveError>. * @param arg The request parameters. */ public teamTeamFolderArchive(arg: team.TeamFolderArchiveArg): Promise<DropboxResponse<team.TeamFolderArchiveLaunch>>; /** * Returns the status of an asynchronous job for archiving a team folder. * Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<async.PollError>. * @param arg The request parameters. */ public teamTeamFolderArchiveCheck(arg: async.PollArg): Promise<DropboxResponse<team.TeamFolderArchiveJobStatus>>; /** * Creates a new, active, team folder with no members. This endpoint can * only be used for teams that do not already have a shared team space. * Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderCreateError>. * @param arg The request parameters. */ public teamTeamFolderCreate(arg: team.TeamFolderCreateArg): Promise<DropboxResponse<team.TeamFolderMetadata>>; /** * Retrieves metadata for team folders. Permission : Team member file * access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. * @param arg The request parameters. */ public teamTeamFolderGetInfo(arg: team.TeamFolderIdListArg): Promise<DropboxResponse<Array<team.TeamFolderGetInfoItem>>>; /** * Lists all team folders. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderListError>. * @param arg The request parameters. */ public teamTeamFolderList(arg: team.TeamFolderListArg): Promise<DropboxResponse<team.TeamFolderListResult>>; /** * Once a cursor has been retrieved from teamFolderList(), use this to * paginate through all team folders. Permission : Team member file access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderListContinueError>. * @param arg The request parameters. */ public teamTeamFolderListContinue(arg: team.TeamFolderListContinueArg): Promise<DropboxResponse<team.TeamFolderListResult>>; /** * Permanently deletes an archived team folder. This endpoint cannot be used * for teams that have a shared team space. Permission : Team member file * access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderPermanentlyDeleteError>. * @param arg The request parameters. */ public teamTeamFolderPermanentlyDelete(arg: team.TeamFolderIdArg): Promise<DropboxResponse<void>>; /** * Changes an active team folder's name. Permission : Team member file * access. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderRenameError>. * @param arg The request parameters. */ public teamTeamFolderRename(arg: team.TeamFolderRenameArg): Promise<DropboxResponse<team.TeamFolderMetadata>>; /** * Updates the sync settings on a team folder or its contents. Use of this * endpoint requires that the team has team selective sync enabled. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TeamFolderUpdateSyncSettingsError>. * @param arg The request parameters. */ public teamTeamFolderUpdateSyncSettings(arg: team.TeamFolderUpdateSyncSettingsArg): Promise<DropboxResponse<team.TeamFolderMetadata>>; /** * Returns the member profile of the admin who generated the team access * token used to make the call. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team.TokenGetAuthenticatedAdminError>. */ public teamTokenGetAuthenticatedAdmin(): Promise<DropboxResponse<team.TokenGetAuthenticatedAdminResult>>; /** * Retrieves team events. If the result's GetTeamEventsResult.has_more field * is true, call getEventsContinue() with the returned cursor to retrieve * more entries. If end_time is not specified in your request, you may use * the returned cursor to poll getEventsContinue() for new events. Many * attributes note 'may be missing due to historical data gap'. Note that * the file_operations category and & analogous paper events are not * available on all Dropbox Business [plans]{@link * /business/plans-comparison}. Use [features/get_values]{@link * /developers/documentation/http/teams#team-features-get_values} to check * for this feature. Permission : Team Auditing. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team_log.GetTeamEventsError>. * @param arg The request parameters. */ public teamLogGetEvents(arg: team_log.GetTeamEventsArg): Promise<DropboxResponse<team_log.GetTeamEventsResult>>; /** * Once a cursor has been retrieved from getEvents(), use this to paginate * through all events. Permission : Team Auditing. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<team_log.GetTeamEventsContinueError>. * @param arg The request parameters. */ public teamLogGetEventsContinue(arg: team_log.GetTeamEventsContinueArg): Promise<DropboxResponse<team_log.GetTeamEventsResult>>; /** * Get a list of feature values that may be configured for the current * account. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<users.UserFeaturesGetValuesBatchError>. * @param arg The request parameters. */ public usersFeaturesGetValues(arg: users.UserFeaturesGetValuesBatchArg): Promise<DropboxResponse<users.UserFeaturesGetValuesBatchResult>>; /** * Get information about a user's account. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<users.GetAccountError>. * @param arg The request parameters. */ public usersGetAccount(arg: users.GetAccountArg): Promise<DropboxResponse<users.BasicAccount>>; /** * Get information about multiple user accounts. At most 300 accounts may * be queried per request. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<users.GetAccountBatchError>. * @param arg The request parameters. */ public usersGetAccountBatch(arg: users.GetAccountBatchArg): Promise<DropboxResponse<users.GetAccountBatchResult>>; /** * Get information about the current user's account. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. */ public usersGetCurrentAccount(): Promise<DropboxResponse<users.FullAccount>>; /** * Get the space usage information for the current user's account. * * When an error occurs, the route rejects the promise with type * DropboxResponseError<void>. */ public usersGetSpaceUsage(): Promise<DropboxResponse<users.SpaceUsage>>; }
the_stack
import React, { useState, useCallback, useRef, useMemo } from 'react'; import { UUIFunctionComponent, UUIFunctionComponentProps } from '../../core'; import { createComponentPropTypes, PropTypes, ExtraPropTypes } from '../../utils/createPropTypes'; import { DateTimeShortcut as UUIDateTimeShortcut } from './DateTimeShortcut'; import { YearMonthSelect as UUIYearMonthSelect } from './YearMonthSelect'; import { DateSelect as UUIDateSelect } from './DateSelect'; import { TimeSelect as UUITimeSelect } from './TimeSelect'; import { PickerButtons as UUIPickerButtons } from './PickerButtons'; import { Popover as UUIPopover } from '../Popover/Popover'; import { TextField as UUITextField } from '../Input/TextField'; import { DateTimeShortcutOption, DateTimeShortcutOptionPropTypes } from './DateTimeShortcut'; import { usePendingValue } from '../../hooks/usePendingValue'; import { Icons } from '../../icons/Icons'; import { set, isAfter, startOfMonth, add, isSameMonth, isBefore } from 'date-fns'; import { getZeroDate, formatDateTime, tryParseDateTimeFromString } from './utils/DateTimeUtils'; import ReactHelper from '../../utils/ReactHelper'; import { compact } from 'lodash-es'; export type DateTimeRangePickerValue = [Date, Date]; export type DateTimeRangePickerShortCut = DateTimeShortcutOption<DateTimeRangePickerValue>; export interface DateTimeRangePickerFeatureProps { value: DateTimeRangePickerValue | null; onChange: (value: DateTimeRangePickerValue | null) => void; shortcuts?: DateTimeRangePickerShortCut[]; startPlaceholder?: string; endPlaceholder?: string; confirmLabel?: React.ReactNode; cancelLabel?: React.ReactNode; } export const DateTimeRangePickerPropTypes = createComponentPropTypes<DateTimeRangePickerFeatureProps>({ value: ExtraPropTypes.nullable(PropTypes.arrayOf(PropTypes.instanceOf(Date).isRequired).isRequired), onChange: PropTypes.func.isRequired, shortcuts: PropTypes.arrayOf(DateTimeShortcutOptionPropTypes), startPlaceholder: PropTypes.string, endPlaceholder: PropTypes.string, confirmLabel: PropTypes.node, cancelLabel: PropTypes.node, }) interface DateTimeRangePickerInnerValue { startYearMonth: Date; endYearMonth: Date; startDate: Date | null; endDate: Date | null; startInput: string; endInput: string; } export const DateTimeRangePicker = UUIFunctionComponent({ name: 'DateTimeRangePicker', nodes: { Root: 'div', ConnectIcon: Icons.ArrowRight, CalendarIcon: Icons.Calendar, Popover: UUIPopover, TextField: UUITextField, Activator: 'div', Container: 'div', Toolbar: 'div', Main: 'div', StartSection: 'div', EndSection: 'div', Section: 'div', PickerButtons: UUIPickerButtons, YearMonthSelect: UUIYearMonthSelect, DateSelect: UUIDateSelect, TimeSelect: UUITimeSelect, DateTimeShortcut: UUIDateTimeShortcut, }, propTypes: DateTimeRangePickerPropTypes, }, (props: DateTimeRangePickerFeatureProps, { nodes }) => { const { Root, ConnectIcon, CalendarIcon, Popover, TextField, Activator, Container, Main, StartSection, EndSection, Section, YearMonthSelect, DateSelect, TimeSelect, DateTimeShortcut, PickerButtons, } = nodes const startTimeSelectRef = useRef<any | null>(null) const endTimeSelectRef = useRef<any | null>(null) const startInputRef = useRef<HTMLInputElement | null>(null) const endInputRef = useRef<HTMLInputElement | null>(null) const [active, setActive] = useState(false) const [whichFocusing, setWhichFocusing] = useState<'start' | 'end'>() const [hoverDate, setHoverDate] = useState<Date>() const initialInnerValue = useMemo(() => { if (props.value === null) { return { startDate: null, endDate: null, startInput: '', endInput: '', startYearMonth: startOfMonth(new Date), endYearMonth: add(startOfMonth(new Date), { months: 1 }), } } return { startDate: props.value[0], endDate: props.value[1], startInput: formatDateTime(props.value[0]), endInput: formatDateTime(props.value[1]), startYearMonth: startOfMonth(props.value[0]), endYearMonth: isSameMonth(props.value[0], props.value[1]) ? add(startOfMonth(props.value[1]), { months: 1 }) : props.value[1], } }, [props.value]) const [innerValue, setInnerValue, resetInnerValue] = usePendingValue<DateTimeRangePickerInnerValue>(initialInnerValue, (value) => { if (value.startDate && value.endDate) { handleValueOnChange([value.startDate, value.endDate]) closePopover() } }, { resetWhenInitialValueChanged: true }) const selectedDates = useMemo(() => { return compact([innerValue.startDate, innerValue.endDate]) }, [innerValue.endDate, innerValue.startDate]) const timeSelectScrollToValue = useCallback((type: 'start' | 'end', value: Date, animate?: boolean) => { if (type === 'start' && startTimeSelectRef.current) { startTimeSelectRef.current.scrollToValue(value, animate) } if (type === 'end' && endTimeSelectRef.current) { endTimeSelectRef.current.scrollToValue(value, animate) } }, []) const openPopover = useCallback(() => { setActive(true) }, []) const closePopover = useCallback(() => { setActive(false) }, []) const handleValueOnChange = useCallback((value: DateTimeRangePickerValue | null) => { const sortedValue = value?.sort((i, j) => Number(i) - Number(j)) || null props.onChange(sortedValue) }, [props]) /** * */ const handleInputOnSubmit = useCallback((type: 'start' | 'end') => { if (innerValue.startDate && innerValue.endDate) { const originalInput = formatDateTime(type === 'start' ? innerValue.startDate : innerValue.endDate) const input = type === 'start' ? innerValue.startInput : innerValue.endInput if (originalInput === input) return; try { if (input === '') { handleValueOnChange(null) } else { const result = tryParseDateTimeFromString(input) handleValueOnChange(type === 'start' ? [result, innerValue.endDate] : [innerValue.startDate, result]) } } catch { resetInnerValue() } } }, [handleValueOnChange, innerValue.endInput, innerValue.endDate, innerValue.startInput, innerValue.startDate, resetInnerValue]) /** * handle user change year or month in YearMonthSelect. */ const handleStartYearMonthSelect = useCallback((value: Date) => { setInnerValue((oldValue) => { const startYearMonthDate = value let endYearMonthDate = oldValue.endYearMonth if (!isBefore(startYearMonthDate, endYearMonthDate)) { endYearMonthDate = add(startYearMonthDate, { months: 1 }) } return { ...oldValue, startYearMonth: startYearMonthDate, endYearMonth: endYearMonthDate, } }) }, [setInnerValue]) const handleEndYearMonthSelect = useCallback((value: Date) => { setInnerValue((oldValue) => { const endYearMonthDate = value let startYearMonthDate = oldValue.startYearMonth if (!isAfter(endYearMonthDate, startYearMonthDate)) { startYearMonthDate = add(endYearMonthDate, { months: -1 }) } return { ...oldValue, startYearMonth: startYearMonthDate, endYearMonth: endYearMonthDate, } }) }, [setInnerValue]) /** * handle user select date in DateSelect. */ const handleDateSelect = useCallback((value: Date) => { let newStartValue = innerValue.startDate let newEndValue = innerValue.endDate if ( (newStartValue !== null && newEndValue !== null) || (newStartValue === null && newEndValue === null) ) { if (whichFocusing === 'end') { newStartValue = null newEndValue = value } else { newStartValue = value newEndValue = null } } else { if (newStartValue === null) newStartValue = value if (newEndValue === null) newEndValue = value if (isAfter(newStartValue, newEndValue)) { const tmp = new Date(newStartValue) newStartValue = new Date(newEndValue) newEndValue = tmp } } setInnerValue((oldValue) => { return { ...oldValue, startDate: newStartValue, startInput: formatDateTime(newStartValue), endDate: newEndValue, endInput: formatDateTime(newEndValue), } }) }, [innerValue.endDate, innerValue.startDate, setInnerValue, whichFocusing]) /** * handle user select date in TimeSelect. */ const handleTimeSelect = useCallback((type: 'start' | 'end') => { return (value: Date) => { setInnerValue((oldValue) => { const oldDate = type === 'start' ? oldValue.startDate : oldValue.endDate const newDate = set(oldDate || getZeroDate(), { hours: value.getHours(), minutes: value.getMinutes(), seconds: value.getSeconds(), }) const newInput = formatDateTime(newDate) return { ...oldValue, ...(type === 'start' ? { startDate: newDate, startInput: newInput, } : {}), ...(type === 'end' ? { endDate: newDate, endInput: newInput, } : {}), } }) } }, [setInnerValue]) return ( <Root> <Popover placement={'bottom-start'} active={active} onClickAway={() => { resetInnerValue(); timeSelectScrollToValue('start', props.value ? props.value[0] : getZeroDate(), false) timeSelectScrollToValue('end', props.value ? props.value[1] : getZeroDate(), false) setTimeout(() => { closePopover() }, 10) }} activator={ <Activator onClick={() => { openPopover() setTimeout(() => { const focusedElement = ReactHelper.document?.activeElement if (startInputRef.current === focusedElement || endInputRef.current === focusedElement) return; if (startInputRef.current) { startInputRef.current.focus() } }, 0) }} > <TextField placeholder={props.startPlaceholder} value={innerValue.startInput} onChange={(value) => { setInnerValue((oldValue) => ({ ...oldValue, startInput: value })) }} customize={{ Input: { ref: startInputRef, onFocus: () => { setWhichFocusing('start') }, onBlur: () => { setWhichFocusing(undefined) handleInputOnSubmit('start') }, onKeyDown: (event) => { if (event.key === 'Enter') { handleInputOnSubmit('start') } } } }} /> <ConnectIcon /> <TextField placeholder={props.endPlaceholder} value={innerValue.endInput} onChange={(value) => { setInnerValue((oldValue) => ({ ...oldValue, endInput: value })) }} customize={{ Input: { ref: endInputRef, onFocus: () => { setWhichFocusing('end') }, onBlur: () => { setWhichFocusing(undefined) handleInputOnSubmit('end') }, onKeyDown: (event) => { if (event.key === 'Enter') { handleInputOnSubmit('end') } } } }} /> <CalendarIcon /> </Activator> } > <Container> <Main tabIndex={-1}> {props.shortcuts && ( <DateTimeShortcut options={props.shortcuts} onSelect={(value) => { handleValueOnChange(value) timeSelectScrollToValue('start', value ? value[0] : getZeroDate(), false) timeSelectScrollToValue('end', value ? value[1] : getZeroDate(), false) closePopover() }} /> )} <StartSection> <YearMonthSelect value={innerValue.startYearMonth} onChange={handleStartYearMonthSelect} /> <Section> <DateSelect yearMonth={innerValue.startYearMonth} selectedDates={selectedDates} onSelect={handleDateSelect} hoverDate={hoverDate} onHoverDateChange={(date) => { setHoverDate(date) }} /> <TimeSelect ref={startTimeSelectRef} value={innerValue.startDate || getZeroDate()} onChange={handleTimeSelect('start')} /> </Section> </StartSection> <EndSection> <YearMonthSelect value={innerValue.endYearMonth} onChange={handleEndYearMonthSelect} /> <Section> <DateSelect yearMonth={innerValue.endYearMonth} selectedDates={selectedDates} onSelect={handleDateSelect} hoverDate={hoverDate} onHoverDateChange={(date) => { setHoverDate(date) }} /> <TimeSelect ref={endTimeSelectRef} value={innerValue.endDate || getZeroDate()} onChange={handleTimeSelect('end')} /> </Section> </EndSection> </Main> <PickerButtons confirmLabel={props.confirmLabel} cancelLabel={props.cancelLabel} onCancel={() => { resetInnerValue() timeSelectScrollToValue('start', props.value ? props.value[0] : getZeroDate(), false) timeSelectScrollToValue('end', props.value ? props.value[1] : getZeroDate(), false) setTimeout(() => { closePopover() }, 10) }} onConfirm={() => { setInnerValue((value) => value, true) if (innerValue.startDate && innerValue.endDate) { let data = [innerValue.startDate, innerValue.endDate] if (isAfter(innerValue.startDate, innerValue.endDate)) { data = data.reverse() } timeSelectScrollToValue('start', data[0], false) timeSelectScrollToValue('end', data[1], false) } else { timeSelectScrollToValue('start', getZeroDate(), false) timeSelectScrollToValue('end', getZeroDate(), false) } setTimeout(() => { closePopover() }, 10) }} /> </Container> </Popover> </Root> ) }) export type DateTimeRangePickerProps = UUIFunctionComponentProps<typeof DateTimeRangePicker>
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class IoT1ClickProjects extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: IoT1ClickProjects.Types.ClientConfiguration) config: Config & IoT1ClickProjects.Types.ClientConfiguration; /** * Associates a physical device with a placement. */ associateDeviceWithPlacement(params: IoT1ClickProjects.Types.AssociateDeviceWithPlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse) => void): Request<IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse, AWSError>; /** * Associates a physical device with a placement. */ associateDeviceWithPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse) => void): Request<IoT1ClickProjects.Types.AssociateDeviceWithPlacementResponse, AWSError>; /** * Creates an empty placement. */ createPlacement(params: IoT1ClickProjects.Types.CreatePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreatePlacementResponse) => void): Request<IoT1ClickProjects.Types.CreatePlacementResponse, AWSError>; /** * Creates an empty placement. */ createPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreatePlacementResponse) => void): Request<IoT1ClickProjects.Types.CreatePlacementResponse, AWSError>; /** * Creates an empty project with a placement template. A project contains zero or more placements that adhere to the placement template defined in the project. */ createProject(params: IoT1ClickProjects.Types.CreateProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreateProjectResponse) => void): Request<IoT1ClickProjects.Types.CreateProjectResponse, AWSError>; /** * Creates an empty project with a placement template. A project contains zero or more placements that adhere to the placement template defined in the project. */ createProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.CreateProjectResponse) => void): Request<IoT1ClickProjects.Types.CreateProjectResponse, AWSError>; /** * Deletes a placement. To delete a placement, it must not have any devices associated with it. When you delete a placement, all associated data becomes irretrievable. */ deletePlacement(params: IoT1ClickProjects.Types.DeletePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeletePlacementResponse) => void): Request<IoT1ClickProjects.Types.DeletePlacementResponse, AWSError>; /** * Deletes a placement. To delete a placement, it must not have any devices associated with it. When you delete a placement, all associated data becomes irretrievable. */ deletePlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeletePlacementResponse) => void): Request<IoT1ClickProjects.Types.DeletePlacementResponse, AWSError>; /** * Deletes a project. To delete a project, it must not have any placements associated with it. When you delete a project, all associated data becomes irretrievable. */ deleteProject(params: IoT1ClickProjects.Types.DeleteProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeleteProjectResponse) => void): Request<IoT1ClickProjects.Types.DeleteProjectResponse, AWSError>; /** * Deletes a project. To delete a project, it must not have any placements associated with it. When you delete a project, all associated data becomes irretrievable. */ deleteProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DeleteProjectResponse) => void): Request<IoT1ClickProjects.Types.DeleteProjectResponse, AWSError>; /** * Describes a placement in a project. */ describePlacement(params: IoT1ClickProjects.Types.DescribePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribePlacementResponse) => void): Request<IoT1ClickProjects.Types.DescribePlacementResponse, AWSError>; /** * Describes a placement in a project. */ describePlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribePlacementResponse) => void): Request<IoT1ClickProjects.Types.DescribePlacementResponse, AWSError>; /** * Returns an object describing a project. */ describeProject(params: IoT1ClickProjects.Types.DescribeProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribeProjectResponse) => void): Request<IoT1ClickProjects.Types.DescribeProjectResponse, AWSError>; /** * Returns an object describing a project. */ describeProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DescribeProjectResponse) => void): Request<IoT1ClickProjects.Types.DescribeProjectResponse, AWSError>; /** * Removes a physical device from a placement. */ disassociateDeviceFromPlacement(params: IoT1ClickProjects.Types.DisassociateDeviceFromPlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse) => void): Request<IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse, AWSError>; /** * Removes a physical device from a placement. */ disassociateDeviceFromPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse) => void): Request<IoT1ClickProjects.Types.DisassociateDeviceFromPlacementResponse, AWSError>; /** * Returns an object enumerating the devices in a placement. */ getDevicesInPlacement(params: IoT1ClickProjects.Types.GetDevicesInPlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.GetDevicesInPlacementResponse) => void): Request<IoT1ClickProjects.Types.GetDevicesInPlacementResponse, AWSError>; /** * Returns an object enumerating the devices in a placement. */ getDevicesInPlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.GetDevicesInPlacementResponse) => void): Request<IoT1ClickProjects.Types.GetDevicesInPlacementResponse, AWSError>; /** * Lists the placement(s) of a project. */ listPlacements(params: IoT1ClickProjects.Types.ListPlacementsRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListPlacementsResponse) => void): Request<IoT1ClickProjects.Types.ListPlacementsResponse, AWSError>; /** * Lists the placement(s) of a project. */ listPlacements(callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListPlacementsResponse) => void): Request<IoT1ClickProjects.Types.ListPlacementsResponse, AWSError>; /** * Lists the AWS IoT 1-Click project(s) associated with your AWS account and region. */ listProjects(params: IoT1ClickProjects.Types.ListProjectsRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListProjectsResponse) => void): Request<IoT1ClickProjects.Types.ListProjectsResponse, AWSError>; /** * Lists the AWS IoT 1-Click project(s) associated with your AWS account and region. */ listProjects(callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListProjectsResponse) => void): Request<IoT1ClickProjects.Types.ListProjectsResponse, AWSError>; /** * Lists the tags (metadata key/value pairs) which you have assigned to the resource. */ listTagsForResource(params: IoT1ClickProjects.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListTagsForResourceResponse) => void): Request<IoT1ClickProjects.Types.ListTagsForResourceResponse, AWSError>; /** * Lists the tags (metadata key/value pairs) which you have assigned to the resource. */ listTagsForResource(callback?: (err: AWSError, data: IoT1ClickProjects.Types.ListTagsForResourceResponse) => void): Request<IoT1ClickProjects.Types.ListTagsForResourceResponse, AWSError>; /** * Creates or modifies tags for a resource. Tags are key/value pairs (metadata) that can be used to manage a resource. For more information, see AWS Tagging Strategies. */ tagResource(params: IoT1ClickProjects.Types.TagResourceRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.TagResourceResponse) => void): Request<IoT1ClickProjects.Types.TagResourceResponse, AWSError>; /** * Creates or modifies tags for a resource. Tags are key/value pairs (metadata) that can be used to manage a resource. For more information, see AWS Tagging Strategies. */ tagResource(callback?: (err: AWSError, data: IoT1ClickProjects.Types.TagResourceResponse) => void): Request<IoT1ClickProjects.Types.TagResourceResponse, AWSError>; /** * Removes one or more tags (metadata key/value pairs) from a resource. */ untagResource(params: IoT1ClickProjects.Types.UntagResourceRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.UntagResourceResponse) => void): Request<IoT1ClickProjects.Types.UntagResourceResponse, AWSError>; /** * Removes one or more tags (metadata key/value pairs) from a resource. */ untagResource(callback?: (err: AWSError, data: IoT1ClickProjects.Types.UntagResourceResponse) => void): Request<IoT1ClickProjects.Types.UntagResourceResponse, AWSError>; /** * Updates a placement with the given attributes. To clear an attribute, pass an empty value (i.e., ""). */ updatePlacement(params: IoT1ClickProjects.Types.UpdatePlacementRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdatePlacementResponse) => void): Request<IoT1ClickProjects.Types.UpdatePlacementResponse, AWSError>; /** * Updates a placement with the given attributes. To clear an attribute, pass an empty value (i.e., ""). */ updatePlacement(callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdatePlacementResponse) => void): Request<IoT1ClickProjects.Types.UpdatePlacementResponse, AWSError>; /** * Updates a project associated with your AWS account and region. With the exception of device template names, you can pass just the values that need to be updated because the update request will change only the values that are provided. To clear a value, pass the empty string (i.e., ""). */ updateProject(params: IoT1ClickProjects.Types.UpdateProjectRequest, callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdateProjectResponse) => void): Request<IoT1ClickProjects.Types.UpdateProjectResponse, AWSError>; /** * Updates a project associated with your AWS account and region. With the exception of device template names, you can pass just the values that need to be updated because the update request will change only the values that are provided. To clear a value, pass the empty string (i.e., ""). */ updateProject(callback?: (err: AWSError, data: IoT1ClickProjects.Types.UpdateProjectResponse) => void): Request<IoT1ClickProjects.Types.UpdateProjectResponse, AWSError>; } declare namespace IoT1ClickProjects { export interface AssociateDeviceWithPlacementRequest { /** * The name of the project containing the placement in which to associate the device. */ projectName: ProjectName; /** * The name of the placement in which to associate the device. */ placementName: PlacementName; /** * The ID of the physical device to be associated with the given placement in the project. Note that a mandatory 4 character prefix is required for all deviceId values. */ deviceId: DeviceId; /** * The device template name to associate with the device ID. */ deviceTemplateName: DeviceTemplateName; } export interface AssociateDeviceWithPlacementResponse { } export type AttributeDefaultValue = string; export type AttributeName = string; export type AttributeValue = string; export interface CreatePlacementRequest { /** * The name of the placement to be created. */ placementName: PlacementName; /** * The name of the project in which to create the placement. */ projectName: ProjectName; /** * Optional user-defined key/value pairs providing contextual data (such as location or function) for the placement. */ attributes?: PlacementAttributeMap; } export interface CreatePlacementResponse { } export interface CreateProjectRequest { /** * The name of the project to create. */ projectName: ProjectName; /** * An optional description for the project. */ description?: Description; /** * The schema defining the placement to be created. A placement template defines placement default attributes and device templates. You cannot add or remove device templates after the project has been created. However, you can update callbackOverrides for the device templates using the UpdateProject API. */ placementTemplate?: PlacementTemplate; /** * Optional tags (metadata key/value pairs) to be associated with the project. For example, { {"key1": "value1", "key2": "value2"} }. For more information, see AWS Tagging Strategies. */ tags?: TagMap; } export interface CreateProjectResponse { } export type DefaultPlacementAttributeMap = {[key: string]: AttributeDefaultValue}; export interface DeletePlacementRequest { /** * The name of the empty placement to delete. */ placementName: PlacementName; /** * The project containing the empty placement to delete. */ projectName: ProjectName; } export interface DeletePlacementResponse { } export interface DeleteProjectRequest { /** * The name of the empty project to delete. */ projectName: ProjectName; } export interface DeleteProjectResponse { } export interface DescribePlacementRequest { /** * The name of the placement within a project. */ placementName: PlacementName; /** * The project containing the placement to be described. */ projectName: ProjectName; } export interface DescribePlacementResponse { /** * An object describing the placement. */ placement: PlacementDescription; } export interface DescribeProjectRequest { /** * The name of the project to be described. */ projectName: ProjectName; } export interface DescribeProjectResponse { /** * An object describing the project. */ project: ProjectDescription; } export type Description = string; export type DeviceCallbackKey = string; export type DeviceCallbackOverrideMap = {[key: string]: DeviceCallbackValue}; export type DeviceCallbackValue = string; export type DeviceId = string; export type DeviceMap = {[key: string]: DeviceId}; export interface DeviceTemplate { /** * The device type, which currently must be "button". */ deviceType?: DeviceType; /** * An optional Lambda function to invoke instead of the default Lambda function provided by the placement template. */ callbackOverrides?: DeviceCallbackOverrideMap; } export type DeviceTemplateMap = {[key: string]: DeviceTemplate}; export type DeviceTemplateName = string; export type DeviceType = string; export interface DisassociateDeviceFromPlacementRequest { /** * The name of the project that contains the placement. */ projectName: ProjectName; /** * The name of the placement that the device should be removed from. */ placementName: PlacementName; /** * The device ID that should be removed from the placement. */ deviceTemplateName: DeviceTemplateName; } export interface DisassociateDeviceFromPlacementResponse { } export interface GetDevicesInPlacementRequest { /** * The name of the project containing the placement. */ projectName: ProjectName; /** * The name of the placement to get the devices from. */ placementName: PlacementName; } export interface GetDevicesInPlacementResponse { /** * An object containing the devices (zero or more) within the placement. */ devices: DeviceMap; } export interface ListPlacementsRequest { /** * The project containing the placements to be listed. */ projectName: ProjectName; /** * The token to retrieve the next set of results. */ nextToken?: NextToken; /** * The maximum number of results to return per request. If not set, a default value of 100 is used. */ maxResults?: MaxResults; } export interface ListPlacementsResponse { /** * An object listing the requested placements. */ placements: PlacementSummaryList; /** * The token used to retrieve the next set of results - will be effectively empty if there are no further results. */ nextToken?: NextToken; } export interface ListProjectsRequest { /** * The token to retrieve the next set of results. */ nextToken?: NextToken; /** * The maximum number of results to return per request. If not set, a default value of 100 is used. */ maxResults?: MaxResults; } export interface ListProjectsResponse { /** * An object containing the list of projects. */ projects: ProjectSummaryList; /** * The token used to retrieve the next set of results - will be effectively empty if there are no further results. */ nextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * The ARN of the resource whose tags you want to list. */ resourceArn: ProjectArn; } export interface ListTagsForResourceResponse { /** * The tags (metadata key/value pairs) which you have assigned to the resource. */ tags?: TagMap; } export type MaxResults = number; export type NextToken = string; export type PlacementAttributeMap = {[key: string]: AttributeValue}; export interface PlacementDescription { /** * The name of the project containing the placement. */ projectName: ProjectName; /** * The name of the placement. */ placementName: PlacementName; /** * The user-defined attributes associated with the placement. */ attributes: PlacementAttributeMap; /** * The date when the placement was initially created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the placement was last updated, in UNIX epoch time format. If the placement was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; } export type PlacementName = string; export interface PlacementSummary { /** * The name of the project containing the placement. */ projectName: ProjectName; /** * The name of the placement being summarized. */ placementName: PlacementName; /** * The date when the placement was originally created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the placement was last updated, in UNIX epoch time format. If the placement was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; } export type PlacementSummaryList = PlacementSummary[]; export interface PlacementTemplate { /** * The default attributes (key/value pairs) to be applied to all placements using this template. */ defaultAttributes?: DefaultPlacementAttributeMap; /** * An object specifying the DeviceTemplate for all placements using this (PlacementTemplate) template. */ deviceTemplates?: DeviceTemplateMap; } export type ProjectArn = string; export interface ProjectDescription { /** * The ARN of the project. */ arn?: ProjectArn; /** * The name of the project for which to obtain information from. */ projectName: ProjectName; /** * The description of the project. */ description?: Description; /** * The date when the project was originally created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the project was last updated, in UNIX epoch time format. If the project was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; /** * An object describing the project's placement specifications. */ placementTemplate?: PlacementTemplate; /** * The tags (metadata key/value pairs) associated with the project. */ tags?: TagMap; } export type ProjectName = string; export interface ProjectSummary { /** * The ARN of the project. */ arn?: ProjectArn; /** * The name of the project being summarized. */ projectName: ProjectName; /** * The date when the project was originally created, in UNIX epoch time format. */ createdDate: Time; /** * The date when the project was last updated, in UNIX epoch time format. If the project was not updated, then createdDate and updatedDate are the same. */ updatedDate: Time; /** * The tags (metadata key/value pairs) associated with the project. */ tags?: TagMap; } export type ProjectSummaryList = ProjectSummary[]; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The ARN of the resouce for which tag(s) should be added or modified. */ resourceArn: ProjectArn; /** * The new or modifying tag(s) for the resource. See AWS IoT 1-Click Service Limits for the maximum number of tags allowed per resource. */ tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export type Time = Date; export interface UntagResourceRequest { /** * The ARN of the resource whose tag you want to remove. */ resourceArn: ProjectArn; /** * The keys of those tags which you want to remove. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdatePlacementRequest { /** * The name of the placement to update. */ placementName: PlacementName; /** * The name of the project containing the placement to be updated. */ projectName: ProjectName; /** * The user-defined object of attributes used to update the placement. The maximum number of key/value pairs is 50. */ attributes?: PlacementAttributeMap; } export interface UpdatePlacementResponse { } export interface UpdateProjectRequest { /** * The name of the project to be updated. */ projectName: ProjectName; /** * An optional user-defined description for the project. */ description?: Description; /** * An object defining the project update. Once a project has been created, you cannot add device template names to the project. However, for a given placementTemplate, you can update the associated callbackOverrides for the device definition using this API. */ placementTemplate?: PlacementTemplate; } export interface UpdateProjectResponse { } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2018-05-14"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the IoT1ClickProjects client. */ export import Types = IoT1ClickProjects; } export = IoT1ClickProjects;
the_stack
import { expect } from "chai"; import { stripIndent } from "common-tags"; import { action, empty, fsa, payload, props, union } from "./action"; import { expectSnippet, timeout } from "./snippet-spec"; describe("functions/action", function (): void { /*tslint:disable-next-line:no-invalid-this*/ this.timeout(timeout); describe("creator", () => { it("should create an action", () => { const foo = action("FOO", (foo: number) => ({ foo })); const fooAction = foo(42); expect(fooAction).to.have.property("type", "FOO"); expect(fooAction).to.have.property("foo", 42); }); it("should narrow the action", () => { const foo = action("FOO", (foo: number) => ({ foo })); const bar = action("BAR", (bar: number) => ({ bar })); const both = union(foo, bar); const narrow = (action: typeof both.actions) => { if (action.type === foo.type) { expect(action.foo).to.equal(42); } else { throw new Error("Should not get here."); } }; narrow(foo(42)); }); it("should be serializable", () => { const foo = action("FOO", (foo: number) => ({ foo })); const fooAction = foo(42); const text = JSON.stringify(fooAction); expect(JSON.parse(text)).to.deep.equal({ foo: 42, type: "FOO" }); }); it("should support toString", () => { const foo = action("FOO", (foo: number) => ({ foo })); const fooAction = foo(42); expect(fooAction).to.respondTo("toString"); }); it("should enforce creator parameters", () => { expectSnippet(stripIndent` const foo = action("FOO", (foo: number) => ({ foo })); const fooAction = foo("42"); `).toFail(/not assignable to parameter of type 'number'/); }); it("should enforce action property types", () => { expectSnippet(stripIndent` const foo = action("FOO", (foo: number) => ({ foo })); const fooAction = foo(42); const value: string = fooAction.foo; `).toFail(/'number' is not assignable to type 'string'/); }); it("should enforce action property names", () => { expectSnippet(stripIndent` const foo = action("FOO", (foo: number) => ({ foo })); const fooAction = foo(42); const value = fooAction.bar; `).toFail(/'bar' does not exist on type/); }); it("should prevent type properties", () => { expectSnippet(stripIndent` action("FOO", (type: string) => ({ type })); `).toFail(/should not include a type/); }); }); describe("empty", () => { it("should default to empty", () => { const foo = action("FOO"); const fooAction = foo(); expect(fooAction).to.have.property("type", "FOO"); expect(Object.keys(fooAction)).to.deep.equal(["type"]); }); it("should create an action", () => { const foo = action("FOO", empty()); const fooAction = foo(); expect(fooAction).to.have.property("type", "FOO"); expect(fooAction).to.not.have.property("payload"); }); it("should narrow the action", () => { const foo = action("FOO", empty()); const bar = action("BAR", (bar: number) => ({ bar })); const both = union(foo, bar); const narrow = (action: typeof both.actions) => { if (action.type === foo.type) { throw new Error("Should not get here."); } else { expect(action.bar).to.equal(42); } }; narrow(bar(42)); }); it("should be serializable", () => { const foo = action("FOO", empty()); const fooAction = foo(); const text = JSON.stringify(fooAction); expect(JSON.parse(text)).to.deep.equal({ type: "FOO" }); }); it("should support toString", () => { const foo = action("FOO", empty()); const fooAction = foo(); expect(fooAction).to.respondTo("toString"); }); it("should enforce creator parameters", () => { expectSnippet(stripIndent` const foo = action("FOO", empty()); const fooAction = foo("42"); `).toFail(/Expected 0 arguments/); }); it("should enforce action property types", () => { expectSnippet(stripIndent` const foo = action("FOO", empty()); const fooAction = foo(); const value: string = fooAction.foo; `).toFail(/'foo' does not exist/); }); it("should enforce action property names", () => { expectSnippet(stripIndent` const foo = action("FOO", empty()); const fooAction = foo(); const value = fooAction.bar; `).toFail(/'bar' does not exist on type/); }); }); describe("fsa", () => { it("should create an action", () => { const foo = action("FOO", fsa<number>()); const fooAction = foo(42); expect(fooAction).to.have.property("type", "FOO"); expect(fooAction).to.have.property("error", false); expect(fooAction).to.have.property("payload", 42); }); it("should narrow the action", () => { const foo = action("FOO", fsa<{ foo: number }>()); const bar = action("BAR", fsa<{ bar: number }>()); const both = union(foo, bar); const narrow = (action: typeof both.actions) => { if (action.type === foo.type) { if (action.error) { throw new Error("Should not get here."); } else { expect(action.payload.foo).to.equal(42); } } else { throw new Error("Should not get here."); } }; narrow(foo({ foo: 42 })); }); it("should support error payloads", () => { const foo = action("FOO", fsa<number>()); const fooAction = foo(new Error("Kaboom!")); expect(fooAction).to.have.property("type", "FOO"); expect(fooAction).to.have.property("error", true); expect(fooAction).to.have.property("payload"); expect(fooAction.payload).to.be.an.instanceof(Error); }); it("should support a meta property", () => { const foo = action("FOO", fsa<number>()); const fooAction = foo(42, 54); expect(fooAction).to.have.property("type", "FOO"); expect(fooAction).to.have.property("error", false); expect(fooAction).to.have.property("payload", 42); expect(fooAction).to.have.property("meta", 54); }); it("should be serializable", () => { const foo = action("FOO", fsa<{ foo: number }>()); const fooAction = foo({ foo: 42 }); const text = JSON.stringify(fooAction); expect(JSON.parse(text)).to.deep.equal({ error: false, payload: { foo: 42 }, type: "FOO", }); }); it("should support toString", () => { const foo = action("FOO", fsa<{ foo: number }>()); const fooAction = foo({ foo: 42 }); expect(fooAction).to.respondTo("toString"); }); it("should enforce creator parameters", () => { expectSnippet(stripIndent` const foo = action("FOO", fsa<number>()); const fooAction = foo("42"); `).toFail(/not assignable to parameter of type 'number | Error'/); }); it("should enforce action property types", () => { expectSnippet(stripIndent` const foo = action("FOO", fsa<number>()); const fooAction = foo(42); const value: string = fooAction.payload; `).toFail(/'number' is not assignable to type 'string'/); }); it("should enforce action property names", () => { expectSnippet(stripIndent` const foo = action("FOO", fsa<number>()); const fooAction = foo(42); const value = fooAction.bar; `).toFail(/'bar' does not exist on type/); }); }); describe("payload", () => { it("should create an action", () => { const foo = action("FOO", payload<number>()); const fooAction = foo(42); expect(fooAction).to.have.property("type", "FOO"); expect(fooAction).to.have.property("payload", 42); }); it("should narrow the action", () => { const foo = action("FOO", payload<{ foo: number }>()); const bar = action("BAR", payload<{ bar: number }>()); const both = union(foo, bar); const narrow = (action: typeof both.actions) => { if (action.type === foo.type) { expect(action.payload.foo).to.equal(42); } else { throw new Error("Should not get here."); } }; narrow(foo({ foo: 42 })); }); it("should be serializable", () => { const foo = action("FOO", payload<{ foo: number }>()); const fooAction = foo({ foo: 42 }); const text = JSON.stringify(fooAction); expect(JSON.parse(text)).to.deep.equal({ payload: { foo: 42 }, type: "FOO", }); }); it("should support toString", () => { const foo = action("FOO", payload<{ foo: number }>()); const fooAction = foo({ foo: 42 }); expect(fooAction).to.respondTo("toString"); }); it("should enforce creator parameters", () => { expectSnippet(stripIndent` const foo = action("FOO", payload<number>()); const fooAction = foo("42"); `).toFail(/not assignable to parameter of type 'number'/); }); it("should enforce action property types", () => { expectSnippet(stripIndent` const foo = action("FOO", payload<number>()); const fooAction = foo(42); const value: string = fooAction.payload; `).toFail(/'number' is not assignable to type 'string'/); }); it("should enforce action property names", () => { expectSnippet(stripIndent` const foo = action("FOO", payload<number>()); const fooAction = foo(42); const value = fooAction.bar; `).toFail(/'bar' does not exist on type/); }); }); describe("props", () => { it("should create an action", () => { const foo = action("FOO", props<{ foo: number }>()); const fooAction = foo({ foo: 42 }); expect(fooAction).to.have.property("type", "FOO"); expect(fooAction).to.have.property("foo", 42); }); it("should narrow the action", () => { const foo = action("FOO", props<{ foo: number }>()); const bar = action("BAR", props<{ bar: number }>()); const both = union(foo, bar); const narrow = (action: typeof both.actions) => { if (action.type === foo.type) { expect(action.foo).to.equal(42); } else { throw new Error("Should not get here."); } }; narrow(foo({ foo: 42 })); }); it("should be serializable", () => { const foo = action("FOO", props<{ foo: number }>()); const fooAction = foo({ foo: 42 }); const text = JSON.stringify(fooAction); expect(JSON.parse(text)).to.deep.equal({ foo: 42, type: "FOO" }); }); it("should support toString", () => { const foo = action("FOO", props<{ foo: number }>()); const fooAction = foo({ foo: 42 }); expect(fooAction).to.respondTo("toString"); }); it("should enforce creator parameters", () => { expectSnippet(stripIndent` const foo = action("FOO", props<{ foo: number }>()); const fooAction = foo({ foo: "42" }); `).toFail(/'string' is not assignable to type 'number'/); }); it("should enforce action property types", () => { expectSnippet(stripIndent` const foo = action("FOO", props<{ foo: number }>()); const fooAction = foo({ foo: 42 }); const value: string = fooAction.foo; `).toFail(/'number' is not assignable to type 'string'/); }); it("should enforce action property names", () => { expectSnippet(stripIndent` const foo = action("FOO", props<{ foo: number }>()); const fooAction = foo({ foo: 42 }); const value = fooAction.bar; `).toFail(/'bar' does not exist on type/); }); it("should prevent type properties", () => { expectSnippet(stripIndent` const foo = action("FOO", props<{ type: string }>()); foo({ type: "FOO" }); `).toFail(/should not include a type/); }); }); });
the_stack
import { Connection } from "./connection" import log from "./debug-logger" import { waitPromise } from "./retry" import { Transaction } from "./transaction" import { Vertex } from "./vertex" export interface QueryOptions { // Sorting order, e.g. "orderasc:age" or "orderdesc:createdAt" order?: string /** Maximum number of vertices to return, useful for pagination with offset. */ limit?: number /** Offset for paginated results. Use with limit. */ offset?: number } const SchemaBuildTime = 100 // ms to wait after schema change /** Graph represents a connected graph and convenient features graph operations * with vertices and edges. */ export class Graph { constructor(private connection: Connection) {} indices: string = "" types: string = "" /** Verifies that a connection can be made to the graph server */ async connect(announce: boolean = false) { if (!this.connection.verified) await this.connection.connect(announce) return await this.setIndicesAndTypes() } /** Connect to a given connection */ async connectTo(connection: Connection, announce: boolean = false) { this.connection = connection this.connect(announce) } /** Get a new transaction on the current connection. * @param autoCommit Automatically commit after first mutation. Default: false */ newTransaction(autoCommit: boolean = false) { return this.connection.newTransaction(autoCommit) } /** Deletes all vertices of matching */ async clear(type?: string) { await this.connection.clear(type) log("Warning: Schema was dropped - recreating.") if (type == undefined) { // schema was dropped, recreate await this.setIndicesAndTypes() } } /** Set up default Gverse schema and create all indices */ async setIndicesAndTypes() { log("Setting indices", this.indices) log("Setting types", this.types) await this.connection.applySchema(this.indices + "\n" + this.types) return await waitPromise("set indices", SchemaBuildTime) } /** Get a vertex from the graph with *all* predicates for given uid. */ async get( vertexClass: typeof Vertex, uid: string, depth: number = 3, transaction?: Transaction ): Promise<Vertex | undefined> { log("Graph.get", vertexClass.name, uid) if (!uid) throw Error("No uid provided") const tx = transaction || this.connection.newTransaction(true) const res = await tx.query( `{vertex(func:type(${ vertexClass.name })) @filter(uid(${uid})) { ${Graph.expansion(depth)} }}` ) if (res && res.vertex) return new vertexClass().unmarshal(res.vertex.pop()) return undefined } /** Get values of any Vertex type by uid */ async uid( uid: string, transaction?: Transaction, depth: number = 3 ): Promise<any> { log("Graph.uid", uid) if (!uid) throw "No uid provided" const tx = transaction || this.connection.newTransaction(true) const res = await tx.query( `{vertex(func:uid(${uid})) @filter(has(dgraph.type)) { ${Graph.expansion( depth )} }}` ) if (res && res.vertex) return res.vertex.pop() else return undefined } /** Load a vertex from the graph with *all* predicates for given uid for * given depth. */ async load( vertex: Vertex, depth: number = 3, transaction?: Transaction ): Promise<Vertex | undefined> { log("Graph.load", vertex.type, `(${vertex.uid})`) if (!vertex.uid) throw "Vertex instance requires uid" const tx = transaction || this.connection.newTransaction(true) const res = await tx.query( `{vertex(func:uid(${ vertex.uid })) @filter(has(dgraph.type)) { ${Graph.expansion(depth)} }}` ) if (res && res.vertex) return vertex.unmarshal(res.vertex.pop()) else return undefined } /** Query and unmarshal matching vertices using full GraphQL± query. * Result must be named "vertices" for unmarshaling to work. E.g. * `{vertices(func:uid("0x1)) { uid name }}`. * * For custom queries that do not require unmarshaling, use Transaction.query. */ async query( vertexClass: typeof Vertex, query: string, parameters: any = {}, transaction?: Transaction, depth: number = 3 ): Promise<Vertex[] | undefined> { log("Graph.query", vertexClass.name, query) const tx = transaction || this.connection.newTransaction(true) const res = await tx.query(query, parameters) if (!res) return [] const vertices: Vertex[] = res.vertices.map((values: any) => { return new vertexClass().unmarshal(values) }) return vertices } /** Query and unmarshal matching vertices based on given Dgraph function. * Query function Can include order. * * Examples: * ``` queryWithFunction(Pet, "eq(name, Oreo)") queryWithFunction(Pet, "eq(type, Pet), orderdesc:createdAt") queryWithFunction(Pet, "eq(type, Pet), orderasc:age") ``` */ async queryWithFunction( vertexClass: typeof Vertex, queryFunction: string, transaction?: Transaction, depth: number = 3 ): Promise<Vertex[] | undefined> { log("Graph.queryWithFunction", vertexClass.name, queryFunction) return await this.query( vertexClass, `{vertices(func:${queryFunction}) @filter(type( ${ vertexClass.name })) { ${Graph.expansion(depth)} }}`, {}, transaction, depth ) } /** Query and unmarshal matching vertices */ async all( vertexClass: typeof Vertex, { order, limit, offset }: QueryOptions = {}, transaction?: Transaction, depth: number = 3 ): Promise<Vertex[] | undefined> { limit = (limit && limit < 10000 && limit) || 1000 const orderPhrase = (order && `, ${order}`) || "" const limitPhrase = `, first:${limit}` const offsetPhrase = (offset && `, offset:${offset}`) || "" log("Graph.all", vertexClass.name) return await this.queryWithFunction( vertexClass, `type(${vertexClass.name}) ${orderPhrase} ${limitPhrase} ${offsetPhrase}`, transaction, depth ) } /** Get the first vertex from the graph with matching `predicate = value`. */ async first( vertexClass: typeof Vertex, { predicate, value }: { predicate: string; value: string }, transaction?: Transaction, depth: number = 3 ): Promise<Vertex | undefined> { log("Graph.first", vertexClass.name, predicate, "=", value) const matches = await this.queryWithFunction( vertexClass, `eq(${predicate}, ${value})`, transaction, depth ) return matches ? matches.pop() : undefined } /** Create a vertex in the graph based on given instance. Returns the vertex with new uid. */ async create( vertex: Vertex, traverse: boolean = false, transaction?: Transaction ): Promise<Vertex | undefined> { log("Graph.create", vertex) const tx = transaction || this.connection.newTransaction(true) await vertex.beforeCreate(vertex.marshal(traverse)) // marshal again to get any updated values from beforeUpdate let values: any = vertex.marshal(traverse) // Replacing type with dgraph.type values["dgraph.type"] = values.type delete values.type log("Graph.create after hook values:", values) const createdUid = await tx.mutate(values) if (createdUid) { vertex.uid = createdUid await vertex.afterCreate(values) } return vertex } /** Create a vertex in the graph based on given prototype. Returns the vertex with new uid. */ async delete( vertex: Vertex, traverse: boolean = false, transaction?: Transaction ): Promise<boolean> { log("Graph.delete", vertex) if (!vertex.uid) throw "Can not delete a vertex without a uid" const tx = transaction || this.connection.newTransaction(true) let values: any = vertex.marshal(traverse) await vertex.beforeDelete(values) const delMut = { uid: vertex.uid } const res = await tx.delete(delMut) log("Deleted", vertex.uid) await vertex.afterDelete(values) return true } /** Save the current values into the graph. Returns the vertex with uid. */ async update( vertex: Vertex, traverse: boolean = false, transaction?: Transaction ): Promise<Vertex | undefined> { log("Graph.save", vertex) if (!vertex.uid) throw "Can not save a vertex without a uid" const tx = transaction || this.connection.newTransaction(true) const currentValues = await this.uid(vertex.uid, tx, traverse ? 3 : 1) await vertex.beforeUpdate(currentValues, vertex.marshal(traverse)) // marshal again to get any updated values from beforeUpdate let values: any = vertex.marshal(traverse) const updated = await tx.mutate(values) if (updated) await vertex.afterUpdate(currentValues, values) return vertex } /** Save the current values into the graph. Returns the vertex with uid. */ async save( vertex: Vertex, traverse: boolean = false, transaction?: Transaction ): Promise<Vertex | undefined> { if (!vertex.uid) throw "Can not save a vertex without a uid" const tx = transaction || this.connection.newTransaction(true) const values = vertex.marshal(traverse) await tx.mutate(values) return vertex } /** High performance set properties (predicate values) as is on a vertex of given UID. * Do not pass vertices as values. Pass just the values you want to mutate. * * E.g.: `Graph.set(person.uid, {name: "Zak"})` * * Note: This method is for fast mutation without type-validation and hooks. */ async set( uid: string, values: any, transaction?: Transaction ): Promise<string | undefined> { log("Graph.set", uid, values) const tx = transaction || this.connection.newTransaction(true) values.uid = uid // flatten it for dgraph // remove special keys let vertexValues = Object.assign({}, values) Object.keys(values) .filter((k) => k.startsWith("_")) .forEach((k) => delete vertexValues[k]) return await tx.mutate(vertexValues) } /** Connect a vertex (subject) to another vertex (object) as predicate */ async link( from: Vertex, to: Vertex, predicate: string, transaction?: Transaction ): Promise<string | undefined> { if (from.uid && to.uid) { const tx = transaction || this.connection.newTransaction(true) return await tx.mutateNquads(`<${from.uid}>`, predicate, `<${to.uid}>`) } } /** Disconnect a vertex (object) from another vertex (subject) as predicate */ async unlink( from: Vertex, to: Vertex, predicate: string, transaction?: Transaction ): Promise<string | undefined> { if (from.uid && to.uid) { const tx = transaction || this.connection.newTransaction(true) return await tx.deleteNquads(`<${from.uid}>`, predicate, `<${to.uid}>`) } } /** Disconnect the associated connection */ async disconnect() { if (this.connection) await this.connection.disconnect() } /** Returns the JSON expansion phrase for nested vertices */ static expansion(depth: number) { if (depth < 1 || depth > 10) throw "Invalid depth. Should be between 1 and 10." return Graph.Depths[depth] } /** Create an array of expansion phrases */ static Depths: Array<string> = (() => { const nest = (s: string): string => `uid expand(_all_) { ${s} }` let expression = "uid expand(_all_)" let depths = [] for (var i = 1; i < 11; i++) { depths[i] = expression expression = nest(expression) } return depths })() }
the_stack
import {AriaColorAreaProps, ColorChannel} from '@react-types/color'; import {ColorAreaState} from '@react-stately/color'; import {focusWithoutScrolling, isAndroid, isIOS, mergeProps, useGlobalListeners, useLabels} from '@react-aria/utils'; // @ts-ignore import intlMessages from '../intl/*.json'; import React, {ChangeEvent, HTMLAttributes, InputHTMLAttributes, RefObject, useCallback, useRef} from 'react'; import {useColorAreaGradient} from './useColorAreaGradient'; import {useFocus, useFocusWithin, useKeyboard, useMove} from '@react-aria/interactions'; import {useLocale, useMessageFormatter} from '@react-aria/i18n'; import {useVisuallyHidden} from '@react-aria/visually-hidden'; interface ColorAreaAria { /** Props for the color area container element. */ colorAreaProps: HTMLAttributes<HTMLElement>, /** Props for the color area gradient foreground element. */ gradientProps: HTMLAttributes<HTMLElement>, /** Props for the thumb element. */ thumbProps: HTMLAttributes<HTMLElement>, /** Props for the visually hidden horizontal range input element. */ xInputProps: InputHTMLAttributes<HTMLInputElement>, /** Props for the visually hidden vertical range input element. */ yInputProps: InputHTMLAttributes<HTMLInputElement> } interface ColorAreaAriaProps extends AriaColorAreaProps { /** A ref to the input that represents the x axis of the color area. */ inputXRef: RefObject<HTMLElement>, /** A ref to the input that represents the y axis of the color area. */ inputYRef: RefObject<HTMLElement>, /** A ref to the color area containing element. */ containerRef: RefObject<HTMLElement> } /** * Provides the behavior and accessibility implementation for a color wheel component. * Color wheels allow users to adjust the hue of an HSL or HSB color value on a circular track. */ export function useColorArea(props: ColorAreaAriaProps, state: ColorAreaState): ColorAreaAria { let { isDisabled, inputXRef, inputYRef, containerRef, 'aria-label': ariaLabel } = props; let formatMessage = useMessageFormatter(intlMessages); let {addGlobalListener, removeGlobalListener} = useGlobalListeners(); let {direction, locale} = useLocale(); let focusedInputRef = useRef<HTMLElement>(null); let focusInput = useCallback((inputRef:RefObject<HTMLElement> = inputXRef) => { if (inputRef.current) { focusWithoutScrolling(inputRef.current); } }, [inputXRef]); let stateRef = useRef<ColorAreaState>(null); stateRef.current = state; let {xChannel, yChannel, zChannel} = stateRef.current.channels; let xChannelStep = stateRef.current.xChannelStep; let yChannelStep = stateRef.current.yChannelStep; let currentPosition = useRef<{x: number, y: number}>(null); let {keyboardProps} = useKeyboard({ onKeyDown(e) { // these are the cases that useMove doesn't handle if (!/^(PageUp|PageDown|Home|End)$/.test(e.key)) { e.continuePropagation(); return; } // same handling as useMove, don't need to stop propagation, useKeyboard will do that for us e.preventDefault(); // remember to set this and unset it so that onChangeEnd is fired stateRef.current.setDragging(true); valueChangedViaKeyboard.current = true; switch (e.key) { case 'PageUp': stateRef.current.incrementY(stateRef.current.yChannelPageStep); focusedInputRef.current = inputYRef.current; break; case 'PageDown': stateRef.current.decrementY(stateRef.current.yChannelPageStep); focusedInputRef.current = inputYRef.current; break; case 'Home': direction === 'rtl' ? stateRef.current.incrementX(stateRef.current.xChannelPageStep) : stateRef.current.decrementX(stateRef.current.xChannelPageStep); focusedInputRef.current = inputXRef.current; break; case 'End': direction === 'rtl' ? stateRef.current.decrementX(stateRef.current.xChannelPageStep) : stateRef.current.incrementX(stateRef.current.xChannelPageStep); focusedInputRef.current = inputXRef.current; break; } stateRef.current.setDragging(false); if (focusedInputRef.current) { focusInput(focusedInputRef.current ? focusedInputRef : inputXRef); } } }); let moveHandler = { onMoveStart() { currentPosition.current = null; stateRef.current.setDragging(true); }, onMove({deltaX, deltaY, pointerType, shiftKey}) { let { incrementX, decrementX, incrementY, decrementY, xChannelPageStep, xChannelStep, yChannelPageStep, yChannelStep, getThumbPosition, setColorFromPoint } = stateRef.current; if (currentPosition.current == null) { currentPosition.current = getThumbPosition(); } let {width, height} = containerRef.current.getBoundingClientRect(); let valueChanged = deltaX !== 0 || deltaY !== 0; if (pointerType === 'keyboard') { let deltaXValue = shiftKey && xChannelPageStep > xChannelStep ? xChannelPageStep : xChannelStep; let deltaYValue = shiftKey && yChannelPageStep > yChannelStep ? yChannelPageStep : yChannelStep; if ((deltaX > 0 && direction === 'ltr') || (deltaX < 0 && direction === 'rtl')) { incrementX(deltaXValue); } else if ((deltaX < 0 && direction === 'ltr') || (deltaX > 0 && direction === 'rtl')) { decrementX(deltaXValue); } else if (deltaY > 0) { decrementY(deltaYValue); } else if (deltaY < 0) { incrementY(deltaYValue); } valueChangedViaKeyboard.current = valueChanged; // set the focused input based on which axis has the greater delta focusedInputRef.current = valueChanged && Math.abs(deltaY) > Math.abs(deltaX) ? inputYRef.current : inputXRef.current; } else { currentPosition.current.x += (direction === 'rtl' ? -1 : 1) * deltaX / width ; currentPosition.current.y += deltaY / height; setColorFromPoint(currentPosition.current.x, currentPosition.current.y); } }, onMoveEnd() { isOnColorArea.current = undefined; stateRef.current.setDragging(false); focusInput(focusedInputRef.current ? focusedInputRef : inputXRef); } }; let {moveProps: movePropsThumb} = useMove(moveHandler); let valueChangedViaKeyboard = useRef<boolean>(false); let {focusWithinProps} = useFocusWithin({ onFocusWithinChange: (focusWithin:boolean) => { if (!focusWithin) { valueChangedViaKeyboard.current = false; focusedInputRef.current === undefined; } } }); let currentPointer = useRef<number | null | undefined>(undefined); let isOnColorArea = useRef<boolean>(false); let {moveProps: movePropsContainer} = useMove({ onMoveStart() { if (isOnColorArea.current) { moveHandler.onMoveStart(); } }, onMove(e) { if (isOnColorArea.current) { moveHandler.onMove(e); } }, onMoveEnd() { if (isOnColorArea.current) { moveHandler.onMoveEnd(); } } }); let onThumbDown = (id: number | null) => { if (!state.isDragging) { currentPointer.current = id; valueChangedViaKeyboard.current = false; focusInput(); state.setDragging(true); if (typeof PointerEvent !== 'undefined') { addGlobalListener(window, 'pointerup', onThumbUp, false); } else { addGlobalListener(window, 'mouseup', onThumbUp, false); addGlobalListener(window, 'touchend', onThumbUp, false); } } }; let onThumbUp = (e) => { let id = e.pointerId ?? e.changedTouches?.[0].identifier; if (id === currentPointer.current) { valueChangedViaKeyboard.current = false; focusInput(); state.setDragging(false); currentPointer.current = undefined; isOnColorArea.current = false; if (typeof PointerEvent !== 'undefined') { removeGlobalListener(window, 'pointerup', onThumbUp, false); } else { removeGlobalListener(window, 'mouseup', onThumbUp, false); removeGlobalListener(window, 'touchend', onThumbUp, false); } } }; let onColorAreaDown = (colorArea: Element, id: number | null, clientX: number, clientY: number) => { let rect = colorArea.getBoundingClientRect(); let {width, height} = rect; let x = (clientX - rect.x) / width; let y = (clientY - rect.y) / height; if (direction === 'rtl') { x = 1 - x; } if (x >= 0 && x <= 1 && y >= 0 && y <= 1 && !state.isDragging && currentPointer.current === undefined) { isOnColorArea.current = true; valueChangedViaKeyboard.current = false; currentPointer.current = id; state.setColorFromPoint(x, y); focusInput(); state.setDragging(true); if (typeof PointerEvent !== 'undefined') { addGlobalListener(window, 'pointerup', onColorAreaUp, false); } else { addGlobalListener(window, 'mouseup', onColorAreaUp, false); addGlobalListener(window, 'touchend', onColorAreaUp, false); } } }; let onColorAreaUp = (e) => { let id = e.pointerId ?? e.changedTouches?.[0].identifier; if (isOnColorArea.current && id === currentPointer.current) { isOnColorArea.current = false; valueChangedViaKeyboard.current = false; currentPointer.current = undefined; state.setDragging(false); focusInput(); if (typeof PointerEvent !== 'undefined') { removeGlobalListener(window, 'pointerup', onColorAreaUp, false); } else { removeGlobalListener(window, 'mouseup', onColorAreaUp, false); removeGlobalListener(window, 'touchend', onColorAreaUp, false); } } }; let colorAreaInteractions = isDisabled ? {} : mergeProps({ ...(typeof PointerEvent !== 'undefined' ? { onPointerDown: (e: React.PointerEvent) => { if (e.pointerType === 'mouse' && (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey)) { return; } onColorAreaDown(e.currentTarget, e.pointerId, e.clientX, e.clientY); }} : { onMouseDown: (e: React.MouseEvent) => { if (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey) { return; } onColorAreaDown(e.currentTarget, undefined, e.clientX, e.clientY); }, onTouchStart: (e: React.TouchEvent) => { onColorAreaDown(e.currentTarget, e.changedTouches[0].identifier, e.changedTouches[0].clientX, e.changedTouches[0].clientY); } }) }, movePropsContainer); let thumbInteractions = isDisabled ? {} : mergeProps({ ...(typeof PointerEvent !== 'undefined' ? { onPointerDown: (e: React.PointerEvent) => { if (e.pointerType === 'mouse' && (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey)) { return; } onThumbDown(e.pointerId); }} : { onMouseDown: (e: React.MouseEvent) => { if (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey) { return; } onThumbDown(undefined); }, onTouchStart: (e: React.TouchEvent) => { onThumbDown(e.changedTouches[0].identifier); } }) }, focusWithinProps, keyboardProps, movePropsThumb); let {focusProps: xInputFocusProps} = useFocus({ onFocus: () => { focusedInputRef.current = inputXRef.current; } }); let {focusProps: yInputFocusProps} = useFocus({ onFocus: () => { focusedInputRef.current = inputYRef.current; } }); let isMobile = isIOS() || isAndroid(); function getAriaValueTextForChannel(channel:ColorChannel) { return ( valueChangedViaKeyboard.current ? formatMessage('colorNameAndValue', {name: state.value.getChannelName(channel, locale), value: state.value.formatChannelValue(channel, locale)}) : [ formatMessage('colorNameAndValue', {name: state.value.getChannelName(channel, locale), value: state.value.formatChannelValue(channel, locale)}), formatMessage('colorNameAndValue', {name: state.value.getChannelName(channel === yChannel ? xChannel : yChannel, locale), value: state.value.formatChannelValue(channel === yChannel ? xChannel : yChannel, locale)}) ].join(', ') ); } let colorPickerLabel = formatMessage('colorPicker'); let xInputLabellingProps = useLabels({ ...props, 'aria-label': ariaLabel ? formatMessage('colorInputLabel', {label: ariaLabel, channelLabel: colorPickerLabel}) : colorPickerLabel }); let yInputLabellingProps = useLabels({ ...props, 'aria-label': ariaLabel ? formatMessage('colorInputLabel', {label: ariaLabel, channelLabel: colorPickerLabel}) : colorPickerLabel }); let colorAriaLabellingProps = useLabels( { ...props, 'aria-label': ariaLabel ? `${ariaLabel} ${colorPickerLabel}` : undefined }, isMobile ? colorPickerLabel : undefined ); let ariaRoleDescription = formatMessage('twoDimensionalSlider'); let {visuallyHiddenProps} = useVisuallyHidden({style: { opacity: '0.0001', width: '100%', height: '100%', pointerEvents: 'none' }}); let { colorAreaStyleProps, gradientStyleProps, thumbStyleProps } = useColorAreaGradient({ direction, state, xChannel, zChannel, isDisabled: props.isDisabled }); return { colorAreaProps: { ...colorAriaLabellingProps, ...colorAreaInteractions, ...colorAreaStyleProps, role: 'group' }, gradientProps: { ...gradientStyleProps, role: 'presentation' }, thumbProps: { ...thumbInteractions, ...thumbStyleProps, role: 'presentation' }, xInputProps: { ...xInputLabellingProps, ...visuallyHiddenProps, ...xInputFocusProps, type: 'range', min: state.value.getChannelRange(xChannel).minValue, max: state.value.getChannelRange(xChannel).maxValue, step: xChannelStep, 'aria-roledescription': ariaRoleDescription, 'aria-valuetext': getAriaValueTextForChannel(xChannel), disabled: isDisabled, value: state.value.getChannelValue(xChannel), tabIndex: (isMobile || !focusedInputRef.current || focusedInputRef.current === inputXRef.current ? undefined : -1), /* So that only a single "2d slider" control shows up when listing form elements for screen readers, add aria-hidden="true" to the unfocused control when the value has not changed via the keyboard, but remove aria-hidden to reveal the input for each channel when the value has changed with the keyboard. */ 'aria-hidden': (!isMobile && focusedInputRef.current === inputYRef.current && !valueChangedViaKeyboard.current ? 'true' : undefined), onChange: (e: ChangeEvent<HTMLInputElement>) => { state.setXValue(parseFloat(e.target.value)); } }, yInputProps: { ...yInputLabellingProps, ...visuallyHiddenProps, ...yInputFocusProps, type: 'range', min: state.value.getChannelRange(yChannel).minValue, max: state.value.getChannelRange(yChannel).maxValue, step: yChannelStep, 'aria-roledescription': ariaRoleDescription, 'aria-valuetext': getAriaValueTextForChannel(yChannel), 'aria-orientation': 'vertical', disabled: isDisabled, value: state.value.getChannelValue(yChannel), tabIndex: (isMobile || focusedInputRef.current === inputYRef.current ? undefined : -1), /* So that only a single "2d slider" control shows up when listing form elements for screen readers, add aria-hidden="true" to the unfocused input when the value has not changed via the keyboard, but remove aria-hidden to reveal the input for each channel when the value has changed with the keyboard. */ 'aria-hidden': (isMobile || focusedInputRef.current === inputYRef.current || valueChangedViaKeyboard.current ? undefined : 'true'), onChange: (e: ChangeEvent<HTMLInputElement>) => { state.setYValue(parseFloat(e.target.value)); } } }; }
the_stack
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; // mqtt import {Chat21Service} from './chat-service'; // models import { ConversationModel } from '../../models/conversation'; // services import { ConversationsHandlerService } from '../abstract/conversations-handler.service'; // import { DatabaseProvider } from 'src/app/services/database'; // utils import { TYPE_GROUP } from '../../utils/constants'; import { getImageUrlThumbFromFirebasestorage, avatarPlaceholder, getColorBck } from '../../utils/utils-user'; import { compareValues, getFromNow, conversationsPathForUserId, searchIndexInArrayForUid } from '../../utils/utils'; // import { ImageRepoService } from '../abstract/image-repo.service'; // import { ConsoleReporter } from 'jasmine'; // @Injectable({ providedIn: 'root' }) @Injectable() export class MQTTConversationsHandler extends ConversationsHandlerService { // BehaviorSubject BSConversationDetail: BehaviorSubject<ConversationModel>; conversationAdded: BehaviorSubject<ConversationModel>; conversationChanged: BehaviorSubject<ConversationModel>; conversationRemoved: BehaviorSubject<ConversationModel>; loadedConversationsStorage: BehaviorSubject<ConversationModel[]>; BSConversations: BehaviorSubject<ConversationModel[]> // readAllMessages: BehaviorSubject<string>; // imageRepo: ImageRepoService; // public variables conversations: Array<ConversationModel> = []; uidConvSelected: string; tenant: string; // FIREBASESTORAGE_BASE_URL_IMAGE: string; // urlStorageBucket: string; // private variables private loggedUserId: string; private translationMap: Map<string, string>; private isConversationClosingMap: Map<string, boolean>; private audio: any; private setTimeoutSound: any; constructor( // private tiledeskConversationsProvider: TiledeskConversationProvider, // public databaseProvider: DatabaseProvider, public chat21Service: Chat21Service ) { super(); } /** * inizializzo conversations handler */ initialize( tenant: string, userId: string, translationMap: Map<string, string> ) { console.log('initialize MQTTConversationsHandler'); this.loggedUserId = userId; this.translationMap = translationMap; this.conversations = []; // this.databaseProvider.initialize(userId, this.tenant); this.isConversationClosingMap = new Map(); // this.getConversationsFromStorage(); } public getConversationDetail(conversationWith: string, callback) { // 1 cerco array locale // 2 cerco remoto // callback const conversation = this.conversations.find(conv => conv.conversation_with === conversationWith); console.log('found locally? getConversationDetail *****: ', conversation); if (conversation) { console.log('found!'); callback(conversation); } else { console.log('Not found locally, remote.getConversationDetail *****: ', conversation); this.chat21Service.chatClient.conversationDetail(conversationWith, (conversation) => { if (conversation) { if (callback) { callback(this.completeConversation(conversation)); } } else { if (callback) { callback(null); } } }) } } setConversationRead(conversationrecipient): void { console.log("setConversationRead...") this.chat21Service.chatClient.updateConversationIsNew(conversationrecipient, false, (err) => { if (err) { console.error("setConversationRead: false. An error occurred", err); } else { console.log("setConversationRead: false. Ok"); } }); } /** * */ // private getConversationsFromStorage() { // const that = this; // this.databaseProvider.getConversations() // .then((conversations: [ConversationModel]) => { // that.loadedConversationsStorage.next(conversations); // // that.events.publish('loadedConversationsStorage', conversations); // }) // .catch((e) => { // console.log('error: ', e); // }); // } /** * connecting to conversations */ // connect() { // console.log('connecting MQTT conversations handler'); // const handlerConversationAdded = this.chat21Service.chatClient.onConversationAdded( (conv) => { // console.log('conversation added:', conv.text); // this.added(conv); // }); // const handlerConversationUpdated = this.chat21Service.chatClient.onConversationUpdated( (conv) => { // console.log('conversation updated:', conv.text); // this.changed(conv); // }); // const handlerConversationDeleted = this.chat21Service.chatClient.onConversationDeleted( (conv) => { // console.log('conversation deleted:', conv.text); // this.removed(conv); // }); // this.chat21Service.chatClient.lastConversations( (err, conversations) => { // console.log('Last conversations', conversations, 'err', err); // if (!err) { // conversations.forEach(conv => { // this.added(conv); // }); // } // }); // // SET AUDIO // this.audio = new Audio(); // this.audio.src = URL_SOUND; // this.audio.load(); // --------------------------------------------------------------------------------- // New connect - renamed subscribeToConversation //---------------------------------------------------------------------------------- subscribeToConversations(loaded) { console.log('connecting MQTT conversations handler'); const handlerConversationAdded = this.chat21Service.chatClient.onConversationAdded( (conv) => { let conversation = this.completeConversation(conv); // needed to get the "conversation_with", and find the conv in the conv-history const index = this.searchIndexInArrayForConversationWith(this.conversations, conversation.conversation_with); if (index > -1) { console.log("Added conv -> Changed!") this.changed(conversation); } else { console.log("Added conv -> Added!") this.added(conversation); } }); const handlerConversationUpdated = this.chat21Service.chatClient.onConversationUpdated( (conv, topic) => { console.log('conversation updated:', JSON.stringify(conv)); this.changed(conv); }); const handlerConversationDeleted = this.chat21Service.chatClient.onConversationDeleted( (conv, topic) => { console.log('conversation deleted:', conv, topic); // example topic: apps.tilechat.users.ME.conversations.CONVERS-WITH.clientdeleted const topic_parts = topic.split("/") console.debug("topic and parts", topic_parts) if (topic_parts.length < 7) { console.error("Error. Not a conversation-deleted topic:", topic); return } const convers_with = topic_parts[5]; this.removed({ uid: convers_with }); }); this.chat21Service.chatClient.lastConversations( false, (err, conversations) => { console.log('Last conversations', conversations, 'err', err); if (!err) { conversations.forEach(conv => { this.added(conv); }); loaded(); } }); } getLastConversation(callback: (conv: ConversationModel, error: string) => void): void { throw new Error('Method not implemented.'); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice /** * 1 - completo la conversazione con i parametri mancanti * 2 - verifico che sia una conversazione valida * 3 - salvo stato conversazione (false) nell'array delle conversazioni chiuse * 4 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni * o sostituisco la conversazione con quella preesistente * 5 - salvo la conversazione nello storage * 6 - ordino l'array per timestamp * 7 - pubblico conversations:update */ private added(conv: any) { console.log("NEW CONV childSnapshot", conv) let conversation = this.completeConversation(conv); if (this.isValidConversation(conversation)) { this.setClosingConversation(conversation.conversation_with, false); console.log("new conv.uid" + conversation.uid); console.log("conversations:", this.conversations); const index = this.searchIndexInArrayForConversationWith(this.conversations, conversation.conversation_with); console.log("found index:", index) console.log("NUOVA CONVER;.uid2" + conversation.uid) if (index > -1) { console.log("TROVATO") this.conversations.splice(index, 1, conversation); } else { console.log("NON TROVATO") this.conversations.splice(0, 0, conversation); // this.databaseProvider.setConversation(conversation); } console.log("NUOVA CONVER;.uid3" + conversation.uid) this.conversations.sort(compareValues('timestamp', 'desc')); console.log("NUOVA CONVER;.uid4" + conversation.uid) console.log("TUTTE:", this.conversations) // this.conversationChanged.next(conversation); console.log("NUOVA CONVER;.uid5" + conversation.uid) this.conversationAdded.next(conversation); console.log("NUOVA CONVER;.uid6" + conversation.uid) // this.events.publish('conversationsChanged', this.conversations); } else { console.error('ChatConversationsHandler::added::conversations with conversationId: ', conversation.conversation_with, 'is not valid'); } } searchIndexInArrayForConversationWith(conversations, conversation_with: string) { return conversations.findIndex(conv => conv.conversation_with === conversation_with); } /** * 1 - completo la conversazione con i parametri mancanti * 2 - verifico che sia una conversazione valida * 3 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni * 4 - salvo la conversazione nello storage * 5 - ordino l'array per timestamp * 6 - pubblico conversations:update * 7 - attivo sound se è un msg nuovo */ private changed(conversation: any) { // const childData: ConversationModel = childSnapshot; // childData.uid = childSnapshot.key; // console.log('changed conversation: ', childData); // const conversation = this.completeConversation(childData); console.log("Conversation changed:", conversation) // let conversation = this.completeConversation(childSnapshot); // childSnapshot.uid = childSnapshot.conversation_with; // let conversation = this.completeConversation(childSnapshot); // console.log("Conversation completed:", conversation); // conversation.uid = conversation.conversation_with; // console.log("conversation.uid" + conversation.uid) // console.log("conversation.uid", conversation.uid) // if (this.isValidConversation(conversation)) { // this.setClosingConversation(conversation.uid, false); if (!conversation.conversation_with) { conversation.conversation_with = conversation.conversWith // conversWith comes from remote } const index = searchIndexInArrayForUid(this.conversations, conversation.conversation_with); if (index > -1) { // const conv = this.conversations[index]; // console.log("Conversation to update found", conv); this.updateConversationWithSnapshot(this.conversations[index], conversation); console.log("conversationchanged.isnew", index, JSON.stringify(conversation)) this.conversations.sort(compareValues('timestamp', 'desc')); this.conversations.splice(index, 1, this.conversations[index]) this.conversationChanged.next(this.conversations[index]); } } private updateConversationWithSnapshot(conv: ConversationModel, snap: any) { console.log("updating conv", conv, "with snap", snap) console.log("print snap keys/values") Object.keys(snap).forEach(k => { console.log("key:" + k); if (k === 'is_new') { console.log("aggiorno key:" + k); conv.is_new = snap[k]; } if (k === 'text') { console.log("aggiorno key:" + k); conv.last_message_text = snap[k]; conv.text = snap[k]; } if (k === 'recipient') { console.log("aggiorno key:" + k); conv.recipient = snap[k]; } if (k === 'recipient_fullname') { console.log("aggiorno key:" + k); conv.recipient_fullname = snap[k]; } if (k === 'sender') { console.log("aggiorno key:" + k); conv.sender = snap[k]; } if (k === 'sender_fullname') { console.log("aggiorno key:" + k); conv.sender_fullname = snap[k]; } if (k === 'attributes') { console.log("aggiorno key:" + k); conv.attributes = snap[k]; } if (k === 'timestamp') { console.log("aggiorno key:" + k); conv.timestamp = snap[k]; //this.getTimeLastMessage(snap[k]); } if (k === 'status') { console.log("aggiorno key:" + k); conv.status = this.setStatusConversation(conv.sender, conv.uid); } if (k === 'type') { console.log("aggiorno key:" + k); conv.type = snap[k]; } }); console.log('listtttttt', this.conversations, conv, snap) // SCHEMA ConversationModel // public uid: string, // public attributes: any, // public channel_type: string, // public conversation_with_fullname: string, // public conversation_with: string, // public recipient: string, // public recipient_fullname: string, // public image: string, // public is_new: boolean, // public last_message_text: string, // public sender: string, // public senderAuthInfo: any, // public sender_fullname: string, // public status: string, // public timestamp: string, // public selected: boolean, // public color: string, // public avatar: string, // public archived: boolean } /** * 1 - cerco indice conversazione da eliminare * 2 - elimino conversazione da array conversations * 3 - elimino la conversazione dallo storage * 4 - pubblico conversations:update * 5 - elimino conversazione dall'array delle conversazioni chiuse */ private removed(childSnapshot) { const index = searchIndexInArrayForUid(this.conversations, childSnapshot.uid); if (index > -1) { const conversationRemoved = this.conversations[index] this.conversations.splice(index, 1); // this.conversations.sort(compareValues('timestamp', 'desc')); // this.databaseProvider.removeConversation(childSnapshot.key); console.debug("conversationRemoved::", conversationRemoved) this.conversationRemoved.next(conversationRemoved); } // remove the conversation from the isConversationClosingMap this.deleteClosingConversation(childSnapshot.uid); } /** * dispose reference di conversations */ dispose() { this.conversations.length = 0; this.conversations = []; this.uidConvSelected = ''; } getClosingConversation(conversationId: string) { return this.isConversationClosingMap[conversationId]; } setClosingConversation(conversationId: string, status: boolean) { this.isConversationClosingMap[conversationId] = status; } deleteClosingConversation(conversationId: string) { this.isConversationClosingMap.delete(conversationId); } archiveConversation(conversationId: string) { this.chat21Service.chatClient.archiveConversation(conversationId); } private completeConversation(conv): ConversationModel { console.log('completeConversation', conv); conv.selected = false; if (!conv.sender_fullname || conv.sender_fullname === 'undefined' || conv.sender_fullname.trim() === '') { conv.sender_fullname = conv.sender; } if (!conv.recipient_fullname || conv.recipient_fullname === 'undefined' || conv.recipient_fullname.trim() === '') { conv.recipient_fullname = conv.recipient; } let conversation_with_fullname = conv.sender_fullname; let conversation_with = conv.sender; if (conv.sender === this.loggedUserId) { conversation_with = conv.recipient; conversation_with_fullname = conv.recipient_fullname; conv.last_message_text = conv.last_message_text; } else if (this.isGroup(conv)) { conversation_with = conv.recipient; conversation_with_fullname = conv.recipient_fullname; conv.last_message_text = conv.last_message_text; } conv.conversation_with_fullname = conversation_with_fullname; conv.conversation_with = conversation_with; conv.status = this.setStatusConversation(conv.sender, conv.uid); conv.avatar = avatarPlaceholder(conversation_with_fullname); conv.color = getColorBck(conversation_with_fullname); if (!conv.last_message_text) { conv.last_message_text = conv.text; // building conv with a message } conv.uid = conv.conversation_with; return conv; } private isGroup(conv: ConversationModel) { if (conv.recipient.startsWith('group-') || conv.recipient.startsWith('support-group')) { return true; }; return false; } /** */ private setStatusConversation(sender, uid): string { let status = '0'; // letto if (sender === this.loggedUserId || uid === this.uidConvSelected) { status = '0'; } else { status = '1'; // non letto } return status; } /** * calcolo il tempo trascorso da ora al timestamp passato * @param timestamp */ private getTimeLastMessage(timestamp: string) { const timestampNumber = parseInt(timestamp) / 1000; const time = getFromNow(timestampNumber); return time; } /** * restituisce il numero di conversazioni nuove */ countIsNew(): number { let num = 0; this.conversations.forEach((element) => { if (element.is_new === true) { num++; } }); return num; } // ---------------------------------------------------------- // // END FUNCTIONS // ---------------------------------------------------------- // /** * attivo sound se è un msg nuovo */ private soundMessage() { console.log('****** soundMessage *****', this.audio); const that = this; // this.audio = new Audio(); // this.audio.src = 'assets/pling.mp3'; // this.audio.load(); this.audio.pause(); this.audio.currentTime = 0; clearTimeout(this.setTimeoutSound); this.setTimeoutSound = setTimeout(function () { //setTimeout(function() { that.audio.play() .then(function() { // console.log('****** then *****'); }) .catch(function() { // console.log('***//tiledesk-dashboard/chat*'); }); }, 1000); } // /** // * check if the conversations is valid or not // */ // private isValidConversation(convToCheckId, convToCheck: ConversationModel) : boolean { // //console.log("[BEGIN] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); // if (!this.isValidField(convToCheck.uid)) { // console.error("ChatConversationsHandler::isValidConversation:: 'uid is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.is_new)) { // console.error("ChatConversationsHandler::isValidConversation:: 'is_new is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.last_message_text)) { // console.error("ChatConversationsHandler::isValidConversation:: 'last_message_text is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.recipient)) { // console.error("ChatConversationsHandler::isValidConversation:: 'recipient is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.recipient_fullname)) { // console.error("ChatConversationsHandler::isValidConversation:: 'recipient_fullname is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.sender)) { // console.error("ChatConversationsHandler::isValidConversation:: 'sender is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.sender_fullname)) { // console.error("ChatConversationsHandler::isValidConversation:: 'sender_fullname is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.status)) { // console.error("ChatConversationsHandler::isValidConversation:: 'status is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.timestamp)) { // console.error("ChatConversationsHandler::isValidConversation:: 'timestamp is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.channel_type)) { // console.error("ChatConversationsHandler::isValidConversation:: 'channel_type is not valid' "); // return false; // } // //console.log("[END] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); // // any other case // return true; // } /** * check if the conversations is valid or not */ private isValidConversation(convToCheck: ConversationModel) : boolean { //console.log("[BEGIN] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); console.log("checking uid of", convToCheck) console.log("conversation.uid", convToCheck.uid) console.log("channel_type is:", convToCheck.channel_type) if (!this.isValidField(convToCheck.uid)) { console.error("ChatConversationsHandler::isValidConversation:: 'uid is not valid' "); return false; } // if (!this.isValidField(convToCheck.is_new)) { // console.error("ChatConversationsHandler::isValidConversation:: 'is_new is not valid' "); // return false; // } if (!this.isValidField(convToCheck.last_message_text)) { console.error("ChatConversationsHandler::isValidConversation:: 'last_message_text is not valid' "); return false; } if (!this.isValidField(convToCheck.recipient)) { console.error("ChatConversationsHandler::isValidConversation:: 'recipient is not valid' "); return false; } if (!this.isValidField(convToCheck.recipient_fullname)) { console.error("ChatConversationsHandler::isValidConversation:: 'recipient_fullname is not valid' "); return false; } if (!this.isValidField(convToCheck.sender)) { console.error("ChatConversationsHandler::isValidConversation:: 'sender is not valid' "); return false; } if (!this.isValidField(convToCheck.sender_fullname)) { console.error("ChatConversationsHandler::isValidConversation:: 'sender_fullname is not valid' "); return false; } if (!this.isValidField(convToCheck.status)) { console.error("ChatConversationsHandler::isValidConversation:: 'status is not valid' "); return false; } if (!this.isValidField(convToCheck.timestamp)) { console.error("ChatConversationsHandler::isValidConversation:: 'timestamp is not valid' "); return false; } if (!this.isValidField(convToCheck.channel_type)) { console.error("ChatConversationsHandler::isValidConversation:: 'channel_type is not valid' "); return false; } //console.log("[END] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); // any other case return true; } // checks if a conversation's field is valid or not private isValidField(field) : boolean{ return (field === null || field === undefined) ? false : true; } }
the_stack
import webpack, { Stats } from 'webpack'; import path from 'path'; import fs from 'fs'; import http from 'http'; import puppeteer from 'puppeteer'; import type * as UrlLoaderModule from '../src'; import { ExecutionResult, parse } from 'graphql'; describe('[url-loader] webpack bundle compat', () => { if (process.env['TEST_BROWSER']) { let httpServer: http.Server; let browser: puppeteer.Browser; let page: puppeteer.Page | undefined; const port = 8712; const httpAddress = 'http://localhost:8712'; const webpackBundlePath = path.resolve(__dirname, 'webpack.js'); let graphqlHandler: http.RequestListener | undefined; beforeAll(async () => { // bundle webpack js const stats = await new Promise<Stats | undefined>((resolve, reject) => { webpack( { mode: 'development', entry: path.resolve(__dirname, '..', 'dist', 'index.mjs'), output: { path: path.resolve(__dirname), filename: 'webpack.js', libraryTarget: 'umd', library: 'GraphQLToolsUrlLoader', umdNamedDefine: true, }, plugins: [ new webpack.DefinePlugin({ setImmediate: 'setTimeout', }), ], }, (err, stats) => { if (err) return reject(err); resolve(stats); } ); }); if (stats?.hasErrors()) { console.error(stats.toString({ colors: true })); } httpServer = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/') { res.statusCode = 200; res.writeHead(200, { 'Content-Type': 'text/html; charset=UTF-8', }); res.write(/** HTML */ ` <html> <title>Url Loader Test</title> <body> <script src="/webpack.js"></script> </body> </html> `); res.end(); return; } if (req.method === 'GET' && req.url === '/webpack.js') { const stat = fs.statSync(webpackBundlePath); res.writeHead(200, { 'Content-Type': 'application/javascript', 'Content-Length': stat.size, }); const readStream = fs.createReadStream(webpackBundlePath); readStream.pipe(res); return; } if (graphqlHandler) { graphqlHandler(req, res); return; } res.writeHead(404, 'Not found :('); }); await new Promise<void>(resolve => { httpServer.listen(port, () => { resolve(); }); }); browser = await puppeteer.launch({ // headless: false, }); }, 90_000); beforeEach(async () => { if (page !== undefined) { await page.close(); page = undefined; } graphqlHandler = undefined; }); afterAll(async () => { await browser.close(); await new Promise<void>((resolve, reject) => { httpServer.close(err => { if (err) return reject(err); resolve(); }); }); }); it('can be exposed as a global', async () => { page = await browser.newPage(); await page.goto(httpAddress); const result = await page.evaluate(async () => { return typeof window['GraphQLToolsUrlLoader']; }); expect(result).toEqual('object'); }); it('can be used for executing a basic http query operation', async () => { page = await browser.newPage(); await page.goto(httpAddress); const expectedData = { data: { foo: true, }, }; graphqlHandler = (_req, res) => { res.writeHead(200, { 'Content-Type': 'application/json', }); res.write(JSON.stringify(expectedData)); res.end(); }; const document = parse(/* GraphQL */ ` query { foo } `); const result = await page.evaluate( async (httpAddress, document) => { const module = window['GraphQLToolsUrlLoader'] as typeof UrlLoaderModule; const loader = new module.UrlLoader(); const executor = await loader.getExecutorAsync(httpAddress + '/graphql'); const result = await executor({ document, }); return result; }, httpAddress, document as any ); expect(result).toStrictEqual(expectedData); }); it('handles executing a operation using multipart responses', async () => { page = await browser.newPage(); await page.goto(httpAddress); graphqlHandler = async (_req, res) => { res.writeHead(200, { // prettier-ignore "Connection": "keep-alive", 'Content-Type': 'multipart/mixed; boundary="-"', 'Transfer-Encoding': 'chunked', }); res.write(`---`); let chunk = Buffer.from(JSON.stringify({ data: {} }), 'utf8'); let data = ['', 'Content-Type: application/json; charset=utf-8', '', chunk, '', `---`]; res.write(data.join('\r\n')); await new Promise(resolve => setTimeout(resolve, 300)); chunk = Buffer.from(JSON.stringify({ data: true, path: ['foo'] }), 'utf8'); data = ['', 'Content-Type: application/json; charset=utf-8', '', chunk, '', `---`]; res.write(data.join('\r\n')); res.end(); }; const document = parse(/* GraphQL */ ` query { ... on Query @defer(label: "foo") { foo } } `); const result = await page.evaluate( async (httpAddress, document) => { const module = window['GraphQLToolsUrlLoader'] as typeof UrlLoaderModule; const loader = new module.UrlLoader(); const executor = await loader.getExecutorAsync(httpAddress + '/graphql'); const result = await executor({ document, }); const results = []; for await (const currentResult of result as any) { results.push(JSON.parse(JSON.stringify(currentResult))); } return results; }, httpAddress, document as any ); expect(result).toEqual([{ data: {} }, { data: { foo: true } }]); }); it('handles SSE subscription operations', async () => { page = await browser.newPage(); await page.goto(httpAddress); const expectedDatas = [{ data: { foo: true } }, { data: { foo: false } }]; graphqlHandler = async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', // prettier-ignore "Connection": "keep-alive", 'Cache-Control': 'no-cache', }); for (const data of expectedDatas) { await new Promise(resolve => setTimeout(resolve, 300)); res.write(`data: ${JSON.stringify(data)}\n\n`); await new Promise(resolve => setTimeout(resolve, 300)); } res.end(); }; const document = parse(/* GraphQL */ ` subscription { foo } `); const result = await page.evaluate( async (httpAddress, document) => { const module = window['GraphQLToolsUrlLoader'] as typeof UrlLoaderModule; const loader = new module.UrlLoader(); const executor = await loader.getExecutorAsync(httpAddress + '/graphql', { subscriptionsProtocol: module.SubscriptionProtocol.SSE, }); const result = await executor({ document, }); const results = []; for await (const currentResult of result as AsyncIterable<ExecutionResult>) { results.push(currentResult); } return results; }, httpAddress, document as any ); expect(result).toStrictEqual(expectedDatas); }); it('terminates SSE subscriptions when calling return on the AsyncIterator', async () => { page = await browser.newPage(); await page.goto(httpAddress); const sentDatas = [{ data: { foo: true } }, { data: { foo: false } }, { data: { foo: true } }]; let responseClosed$: Promise<boolean>; graphqlHandler = async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', // prettier-ignore "Connection": "keep-alive", 'Cache-Control': 'no-cache', }); responseClosed$ = new Promise(resolve => res.once('close', () => resolve(true))); const ping = setInterval(() => { // Ping res.write(':\n\n'); }, 100); for (const data of sentDatas) { await new Promise(resolve => setTimeout(resolve, 300)); res.write(`data: ${JSON.stringify(data)}\n\n`); await new Promise(resolve => setTimeout(resolve, 300)); } clearInterval(ping); }; const document = parse(/* GraphQL */ ` subscription { foo } `); const result = await page.evaluate( async (httpAddress, document) => { const module = window['GraphQLToolsUrlLoader'] as typeof UrlLoaderModule; const loader = new module.UrlLoader(); const executor = await loader.getExecutorAsync(httpAddress + '/graphql', { subscriptionsProtocol: module.SubscriptionProtocol.SSE, }); const result = (await executor({ document, })) as AsyncIterableIterator<ExecutionResult>; const results = []; for await (const currentResult of result) { results.push(currentResult); if (results.length === 2) { break; } } return results; }, httpAddress, document as any ); expect(await responseClosed$!).toBe(true); expect(result).toStrictEqual(sentDatas.slice(0, 2)); }); } else { it('dummy', () => {}); } });
the_stack
import { OrderDirection, QueryBuilder } from "./querybuilder.ts"; import type { Adapter, DatabaseResult, DatabaseValues, } from "./adapters/adapter.ts"; import { createModel, createModels, findColumn, getColumns, getPrimaryKeyInfo, getRelations, getTableName, mapQueryResult, mapSingleQueryResult, mapValueProperties, } from "./utils/models.ts"; import { RelationType } from "./model.ts"; import { quote } from "./utils/dialect.ts"; import type { DeepPartial } from "./manager.ts"; import { Q } from "./q.ts"; /** * Perform query to a model. */ export class ModelQuery<T> { /** The query builder to construct the query */ private builder: QueryBuilder; /** The table to fetch */ private tableName: string; /** Included relationships */ private includes: string[] = []; // -------------------------------------------------------------------------------- // CONSTRUCTOR // -------------------------------------------------------------------------------- /** * Create a new model query. */ constructor(private modelClass: { new (): T }, private adapter: Adapter) { this.tableName = getTableName(modelClass); this.builder = new QueryBuilder(this.tableName, adapter); } // -------------------------------------------------------------------------------- // QUERY CONSTRAINTS // -------------------------------------------------------------------------------- /** * Add basic WHERE clause to query. * * @param column the table column name * @param value the expected value */ public where(column: string, value: DatabaseValues): this; /** * Add basic WHERE clause to query with custom query expression. * * @param column the table column name * @param expresion a custom SQL expression to filter the records */ public where(column: string, expression: Q): this; /** Add basic WHERE clause to query */ public where(column: string, expression: DatabaseValues | Q): this { this.builder.where( this.getColumnName(column), expression as DatabaseValues, ); return this; } /** * Add WHERE NOT clause to query. * * @param column the table column name * @param value the expected value */ public not(column: string, value: DatabaseValues): this; /** * Add WHERE NOT clause to query with custom query expression. * * @param column the table column name * @param expresion a custom SQL expression to filter the records */ public not(column: string, expression: Q): this; /** Add WHERE NOT clause to query. */ public not(column: string, expression: DatabaseValues | Q): this { this.builder.not(this.getColumnName(column), expression as DatabaseValues); return this; } /** * Add WHERE ... OR clause to query. * * @param column the table column name * @param value the expected value */ public or(column: string, value: DatabaseValues): this; /** * Add WHERE ... OR clause to query with custom query expression. * * @param column the table column name * @param expresion a custom SQL expression to filter the records */ public or(column: string, expression: Q): this; /** Add WHERE ... OR clause to query. */ public or(column: string, expression: DatabaseValues | Q): this { this.builder.or(this.getColumnName(column), expression as DatabaseValues); return this; } /** * Set the "limit" value for the query. * * @param limit maximum number of records */ public limit(limit: number): this { this.builder.limit(limit); return this; } /** * Set the "offset" value for the query. * * @param offset number of records to skip */ public offset(offset: number): this { this.builder.offset(offset); return this; } /** * Add an "order by" clause to the query. * * @param column the table column name * @param direction "ASC" or "DESC" */ public order( column: Extract<keyof T, string>, direction?: OrderDirection, ): this { this.builder.order(this.getColumnName(column as string), direction); return this; } // -------------------------------------------------------------------------------- // RELATIONSHIPS // -------------------------------------------------------------------------------- /** * Fetch relationships to the query. * * @param columns all relations you want to include */ public include(...columns: Extract<keyof T, string>[]): this { for (const relation of getRelations(this.modelClass, columns)) { const relationTableName = getTableName(relation.getModel()); const primaryKeyInfo = getPrimaryKeyInfo(this.modelClass); const relationPrimaryKeyInfo = getPrimaryKeyInfo(relation.getModel()); if (relation.type === RelationType.HasMany) { this.builder.leftJoin( relationTableName, relationTableName + "." + relation.targetColumn, this.tableName + "." + primaryKeyInfo.name, ); } else if (relation.type === RelationType.BelongsTo) { this.builder.leftJoin( relationTableName, relationTableName + "." + relationPrimaryKeyInfo.name, this.tableName + "." + relation.targetColumn, ); } this.selectModelColumns(relation.getModel()); this.includes.push(relation.propertyKey); } return this; } // -------------------------------------------------------------------------------- // FETCH QUERY // -------------------------------------------------------------------------------- /** * Count models with given conditions. */ public async count(): Promise<number> { const primaryKeyInfo = getPrimaryKeyInfo(this.modelClass); const result = await this.builder .countDistinct(primaryKeyInfo.name, "count") .execute(); return (Number(result[0].count) as number) || 0; } /** * Update models with given conditions. * * @param data the new data you want to update */ public async update(data: DeepPartial<T>): Promise<void> { const values = mapValueProperties(this.modelClass, data as any, "name"); await this.builder.update(values).execute(); } /** * Delete models with given conditions. */ public async delete(): Promise<void> { await this.builder.delete().execute(); } /** * Find a single record that match given conditions. If multiple * found, it will return the first one. */ public async first(): Promise<T | null> { // Select model columns this.selectModelColumns(this.modelClass); // Check whether this query contains a HasMany relationship const isIncludingHasMany = getRelations( this.modelClass, this.includes, ).find((item) => item.type === RelationType.HasMany); let result: DatabaseResult[]; // If the `includes` option contains a HasMany relationship, // we need to get the record primary key first, then, we can fetch // the whole data. if (isIncludingHasMany) { const primaryKeyInfo = getPrimaryKeyInfo(this.modelClass); const tableName = getTableName(this.modelClass); // Get the distinct query const alias = quote("distinctAlias", this.adapter.dialect); const primaryColumn = quote( tableName + "__" + primaryKeyInfo.name, this.adapter.dialect, ); const { text, values } = this.builder.toSQL(); const queryString = `SELECT DISTINCT ${alias}.${primaryColumn} FROM (${ text.slice( 0, text.length - 1, ) }) ${alias} LIMIT 1;`; // Execute the distinct query const recordIds = await this.adapter.query(queryString, values); // If the record found, fetch the relations if (recordIds.length === 1) { const id = recordIds[0][tableName + "__" + primaryKeyInfo.name]; result = await this.builder .where(primaryKeyInfo.name, Q.eq(id)) .execute(); } else { return null; } } else { result = await this.builder.first().execute(); } // Create the model instances if (result.length >= 1) { const record = this.includes.length >= 1 ? mapQueryResult( this.modelClass, result, this.includes.length >= 1 ? this.includes : undefined, )[0] : mapSingleQueryResult(this.modelClass, result[0]); return createModel(this.modelClass, record, true); } else { return null; } } /** * Find records that match given conditions. */ public async all(): Promise<T[]> { // Select model columns this.selectModelColumns(this.modelClass); // Execute the query const result = await this.builder.execute(); // Build the model objects return createModels( this.modelClass, mapQueryResult( this.modelClass, result, this.includes.length >= 1 ? this.includes : undefined, ), true, ); } // -------------------------------------------------------------------------------- // PRIVATE HELPERS // -------------------------------------------------------------------------------- /** * Select all columns of a model class. * * @param modelClass the model class to get the columns */ private selectModelColumns(modelClass: Function) { const tableName = getTableName(modelClass); const columns = getColumns(modelClass).map((column): [string, string] => [ tableName + "." + column.name, tableName + "__" + column.name, ]); this.builder.select(...columns); } /** * Get column name on the database from a column property key. * * @param propertyKey the property key of the column */ private getColumnName(propertyKey: string): string { const column = findColumn(this.modelClass, propertyKey); if (!column) { throw new Error( `Column '${propertyKey}' doesn't exist in model '${this.modelClass.name}'!`, ); } return column.name; } }
the_stack
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { AuthService } from './auth.service'; import 'rxjs/Rx'; import 'rxjs/add/operator/catch'; import { Observable } from 'rxjs'; import { EnvConfig } from './cla.env.utils'; @Injectable() export class ClaService { http: any; authService: AuthService; claApiUrl: string = ''; localTesting = false; v1ClaAPIURLLocal = 'http://localhost:5000'; v2ClaAPIURLLocal = 'http://localhost:5000'; v3ClaAPIURLLocal = 'http://localhost:8080'; constructor(http: Http, authService: AuthService) { this.http = http; this.authService = authService; } /** * Constructs a URL based on the path and endpoint host:port. * @param path the URL path * @returns a URL to the V1 endpoint with the specified path. If running in local mode, the endpoint will point to a * local host:port - otherwise the endpoint will point the appropriate environment endpoint running in the cloud. */ private getV1Endpoint(path: string) { let url: URL; if (this.localTesting) { url = new URL(this.v1ClaAPIURLLocal + path); } else { url = new URL(this.claApiUrl + path); } return url; } /** * Constructs a URL based on the path and endpoint host:port. * @param path the URL path * @returns a URL to the V2 endpoint with the specified path. If running in local mode, the endpoint will point to a * local host:port - otherwise the endpoint will point the appropriate environment endpoint running in the cloud. */ private getV2Endpoint(path: string) { let url: URL; if (this.localTesting) { url = new URL(this.v2ClaAPIURLLocal + path); } else { url = new URL(this.claApiUrl + path); } return url; } /** * Constructs a URL based on the path and endpoint host:port. * @param path the URL path * @returns a URL to the V3 endpoint with the specified path. If running in local mode, the endpoint will point to a * local host:port - otherwise the endpoint will point the appropriate environment endpoint running in the cloud. */ private getV3Endpoint(path: string) { let url: URL; if (this.localTesting) { url = new URL(this.v3ClaAPIURLLocal + path); } else { url = new URL(this.claApiUrl + path); } return url; } public isLocalTesting(flag: boolean) { if (flag) { console.log('Running in local services mode'); } else { console.log('Running in deployed services mode'); } this.localTesting = flag; } public setApiUrl(claApiUrl: string) { this.claApiUrl = claApiUrl; } public setHttp(http: any) { this.http = http; // allow configuration for alternate http library } ////////////////////////////////////////////////////////////////////////////// /** * This service should ONLY contain methods calling CLA API **/ ////////////////////////////////////////////////////////////////////////////// /** * GET /v3/users/{userId} **/ getUserByUserId(userId) { const url: URL = this.getV3Endpoint('/v3/users/' + userId); return this.http .getWithCreds(url) .map((res) => { return res.json(); }) .catch(this.handleServiceError); } /** * GET /v3/users/username/{userName} **/ getUserByUserName(userName) { const url: URL = this.getV3Endpoint('/v3/users/username/' + userName); return this.http .getWithCreds(url) .map((res) => res.json()) .catch((err) => this.handleServiceError(err)); } /** * POST /v3/user **/ createUserV3(user) { /* { 'user_email': 'user@email.com', 'user_name': 'User Name', 'user_company_id': '<org-id>', 'user_github_id': 12345 } */ const url: URL = this.getV3Endpoint('/v3/users'); return this.http .post(url, user) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * PUT /v3/user **/ updateUserV3(user) { /* { "lfUsername": "<some-username>", "lfEmail": "<some-updated-value>", "companyID": "<some-updated-value>" } */ const url: URL = this.getV3Endpoint('/v3/users'); return this.http .putWithCreds(url, user) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * GET /v2/user/{user_id} **/ getUser(userId) { const url: URL = this.getV2Endpoint('/v2/user/' + userId); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } putSignature(signature) { /* signature: { 'signature_id': '<signature-id>', 'signature_type': ('cla' | 'dco'), 'signature_signed': true, 'signature_approved': true, 'signature_sign_url': 'http://sign.com/here', 'signature_return_url': 'http://cla-system.com/signed', 'signature_project_id': '<project-id>', 'signature_reference_id': '<ref-id>', 'signature_reference_type': ('individual' | 'corporate'), } */ const url: URL = this.getV1Endpoint('/v1/signature'); return this.http .put(url, signature) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * GET /v3/signatures/user/{user_id} * * @param userId the user ID * @param pageSize the optional page size - default is 50 * @param nextKey the next key used when asking for the next page of results */ getSignaturesUser(userId, pageSize = 50, nextKey = '') { //const url: URL = this.getV1Endpoint('/v1/signatures/user/' + userId); // Leverage the new go backend v3 endpoint let path: string = '/v3/signatures/user/' + userId + '?pageSize=' + pageSize; if (nextKey != null && nextKey !== '' && nextKey.trim().length > 0) { path += '&nextKey=' + nextKey; } const url: URL = this.getV3Endpoint(path); return this.http.getWithCreds(url).map((res) => res.json()); } /** * GET /v3/signatures/company/{company_id} * * @param companyId the company ID * @param pageSize the optional page size - default is 50 * @param nextKey the next key used when asking for the next page of results */ getCompanySignatures(companyId, pageSize = 50, nextKey = '') { //const url: URL = this.getV1Endpoint('/v1/signatures/company/' + companyId); // Leverage the new go backend v3 endpoint let path: string = '/v3/signatures/company/' + companyId + '?pageSize=' + pageSize; if (nextKey != null && nextKey !== '' && nextKey.trim().length > 0) { path += '&nextKey=' + nextKey; } const url: URL = this.getV3Endpoint(path); return this.http.getWithCreds(url).map((res) => res.json()); } /** * GET /v3/signatures/project/{project_id}/company/{company_id} * * @param companyId the company ID * @param projectId the project ID * @param pageSize the optional page size - default is 50 * @param nextKey the next key used when asking for the next page of results */ getCompanyProjectSignatures(companyId, projectId, pageSize = 50, nextKey = '') { // Leverage the new go backend v3 endpoint - note the slightly different path layout let path: string = '/v3/signatures/project/' + projectId + '/company/' + companyId + '?pageSize=' + pageSize; if (nextKey != null && nextKey !== '' && nextKey.trim().length > 0) { path += '&nextKey=' + nextKey; } const url: URL = this.getV3Endpoint(path); return this.http.getWithCreds(url).map((res) => res.json()); } /** * GET /v3/signatures/project/{project_id}/company/{company_id}/employee * * @param companyId the company ID * @param projectId the project ID * @param pageSize the optional page size - default is 50 * @param nextKey the next key used when asking for the next page of results */ getEmployeeProjectSignatures(companyId, projectId, pageSize = 50, nextKey = '') { //const url: URL = this.getV1Endpoint('/v1/signatures/company/' + companyId + '/project/' + projectId + '/employee'); // Leverage the new go backend v3 endpoint - note the different order of the parameters in the path let path: string = '/v3/signatures/project/' + projectId + '/company/' + companyId + '/employee' + '?pageSize=' + pageSize; if (nextKey != null && nextKey !== '' && nextKey.trim().length > 0) { path += '&nextKey=' + nextKey; } const url: URL = this.getV3Endpoint(path); return this.http.getWithCreds(url).map((res) => res.json()); } /** * GET /v3/signatures/project/{project_id} * * @param projectId the project ID * @param pageSize the optional page size - default is 50 * @param nextKey the next key used when asking for the next page of results */ getProjectSignatures(projectId, pageSize = 50, nextKey = '') { // Leverage the new go backend v3 endpoint - note the slightly different path let path: string = '/v3/signatures/project/' + projectId + '?pageSize=' + pageSize; if (nextKey != null && nextKey !== '' && nextKey.trim().length > 0) { path += '&nextKey=' + nextKey; } const url: URL = this.getV3Endpoint(path); return this.http.getWithCreds(url).map((res) => res.json()); } /** * GET /v3/company/user/{userID}/invites Returns list of companies for current * user where they are in the access control list or have a pending or rejected invitation * * Response looks the same as the above getCompaniesByUserManager(userID) except it * also includes invitations. * * of note, when reviewing the output JSON: * 1) when the user's name is in the ACL - you should see that the status is “approved” * 2) when the user's is NOT in the ACL - you should see the status as “pending” or “rejected” */ getCompaniesByUserManagerWithInvites(userID) { const url: URL = this.getV3Endpoint('/v3/company/user/' + userID + '/invites'); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * GET /v2/company Returns all the companies */ getAllCompanies() { const url: URL = this.getV2Endpoint('/v2/company'); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * GET /v3/company Returns all the companies */ getAllV3Companies() { const url: URL = this.getV3Endpoint('/v3/company'); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * POST /v1/company */ postCompany(company) { /* { 'company_name': 'Org Name', 'company_whitelist': ['safe@email.org'], 'company_whitelist': ['*@email.org'] } */ const url: URL = this.getV1Endpoint('/v1/company'); return this.http .post(url, company) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * PUT /v1/company */ putCompany(company) { /* { 'company_id': '<company-id>', 'company_name': 'New Company Name' } */ const url: URL = this.getV1Endpoint('/v1/company'); return this.http .put(url, company) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * GET /v2/company/{company_id} */ getCompany(companyId) { const url: URL = this.getV2Endpoint('/v2/company/' + companyId); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * GET /v1/signature/{signature_id}/manager */ getCLAManagers(signatureId) { const url: URL = this.getV1Endpoint('/v1/signature/' + signatureId + '/manager'); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * Add the specified user to the Project/Company ACL list. * POST /v1/signature/{signature_id}/manager */ addCLAManager(companyID: string, projectID: string, payload) { const url: URL = this.getV3Endpoint(`/v3/company/${companyID}/project/${projectID}/cla-manager`); let data = { userName: payload.managerName, userEmail: payload.managerEmail, userLFID: payload.managerLFID, }; return this.http.post(url, data).map((res) => res); } /** * Deletes the specified user from the Project/Company ACL list. * DELETE /company/${companyID}/project/${projectID}/cla-manager/${lfid} * @param companyID the company ID * @param projectID the project ID * @param lfid the LFID of the user to remove from the ACL */ deleteCLAManager(companyID: string, projectID: string, lfid: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyID}/project/${projectID}/cla-manager/${lfid}`); return this.http.delete(url); } /** * GET /v1/project */ getProjects() { const url: URL = this.getV1Endpoint('/v1/project'); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } getCompanyUnsignedProjects(companyId) { const url: URL = this.getV1Endpoint('/v1/company/' + companyId + '/project/unsigned'); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * GET /v2/project/{project_id} */ getProject(projectId) { const url: URL = this.getV2Endpoint('/v2/project/' + projectId); return this.http .get(url) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * POST /v1/request-corporate-signature */ postCorporateSignatureRequest(signatureRequest) { /* { 'project_id': <project-id>, 'company_id': <company-id>, 'return_url': <optional-return-url>, } */ const url: URL = this.getV1Endpoint('/v1/request-corporate-signature'); return this.http .post(url, signatureRequest) .map((res) => res.json()) .catch((error) => this.handleServiceError(error)); } /** * /github/login */ githubLogin(companyID, corporateClaID) { if (this.localTesting) { window.location.assign( this.v3ClaAPIURLLocal + `/v3/github/login?callback=https://${window.location.host}/#/company/${companyID}/project/${corporateClaID}/orgwhitelist` ); } else { window.location.assign( this.claApiUrl + `/v3/github/login?callback=https://${window.location.host}/#/company/${companyID}/project/${corporateClaID}/orgwhitelist` ); } } /** * GET /signatures/{signatureID} **/ getGithubOrganizationWhitelistEntries(signatureID) { const url: URL = this.getV3Endpoint(`/v3/signatures/${signatureID}/gh-org-whitelist`); return this.http.getWithCreds(url).map((res) => res.json()); } /** * POST /signatures/{signatureID} **/ addGithubOrganizationWhitelistEntry(signatureID, organizationId) { const path = `/v3/signatures/${signatureID}/gh-org-whitelist`; const data = { organization_id: organizationId }; const url: URL = this.getV3Endpoint(path); return this.http.postWithCreds(url, data).map((res) => res.json()); } /** * DELETE /signatures/{signatureID} **/ removeGithubOrganizationWhitelistEntry(signatureID, organizationId) { const path = `/v3/signatures/${signatureID}/gh-org-whitelist`; const data = { organization_id: organizationId }; const url: URL = this.getV3Endpoint(path); return this.http.deleteWithCredsAndBody(url, data).map((res) => res.json()); } /** * POST /v3/company/{companyID}/cla/{corporateClaID}/whitelist/githuborg **/ addGithubOrganizationWhitelist(signatureID, companyID, corporateClaID, organizationId) { const path = `/v3/company/${companyID}/cla/${corporateClaID}/whitelist/githuborg`; const data = { id: organizationId }; const url: URL = this.getV3Endpoint(path); return this.http.postWithCreds(url, data).map((res) => res.json()); } /** * /company/{companyID}/cla/{corporateClaID}/whitelist/githuborg **/ removeGithubOrganizationWhitelist(companyID, corporateClaID, organizationId) { const path = `/v3/company/${companyID}/cla/${corporateClaID}/whitelist/githuborg`; const data = { id: organizationId }; const url: URL = this.getV3Endpoint(path); return this.http.deleteWithCredsAndBody(url, data).map((res) => res.json()); } /** * POST /v3/company/{companyId}/invite-request **/ sendInviteRequestEmail(companyId: string, userId: string, userEmail: string, userName: string): Observable<any> { const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/cla/accesslist/request`); const data = { userID: userId, lfUsername: userId, lfEmail: userEmail, username: userName }; return this.http.putWithCreds(url, data); } /** * GET /v3/company/{companyID}/cla/invitelist: * Example: * [ * { * "inviteId": "1e5debac-57fd-4b1f-9669-cfa4c30d7b22", * "status": "pending", * "userEmail": "ahampras@proximabiz.com", * "userLFID": "ahampras", * "userName": "Abhijeet Hampras" * }, * { * "inviteId": "1e5debac-57fd-4b1f-9669-cfa4c30d7b33", * "status": "rejected", * "userEmail": "davifowl@microsoft.com", * "userLFID": "davidfowl" * } * ] * * @param companyId the company ID * @param status the status value - one of: {pending, approved, rejected} **/ getCompanyInvites(companyId: string, status: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/cla/invitelist?status=${status}`); return this.http.getWithCreds(url).map((res) => res.json()); } /** * GET /v3/company/{companyID}/{userID}/invitelist: * Example (pending): * { * "inviteId": "1e5debac-57fd-4b1f-9669-cfa4c30d7b22", * "status": "pending", * "userEmail": "ahampras@proximabiz.com", * "userLFID": "ahampras", * "userName": "Abhijeet Hampras", * "companyName: "my company name" * } * * Example (rejected): * { * "inviteId": "1e5debac-57fd-4b1f-9669-cfa4c30d7b22", * "status": "rejected", * "userEmail": "ahampras@proximabiz.com", * "userLFID": "ahampras", * "userName": "Abhijeet Hampras", * "companyName: "my company name" * } * * Returns HTTP status 404 if company and user invite is not found * * @param companyId the company ID * @param userID the user ID */ getPendingUserInvite(companyId, userID) { const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/${userID}/invitelist`); return this.http.getWithCreds(url).map((res) => res.json()); } /** * Approve the company invite service method. * @param companyId * @param requestId */ approveCompanyInvite(companyId: string, requestId: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/cla/accesslist/${requestId}/approve`); return this.http.putWithCreds(url); } /** * Reject the company invite service method. * * @param companyId the company ID * @param requestId the request ID */ rejectCompanyInvite(companyId: string, requestId: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/cla/accesslist/${requestId}/reject`); return this.http.putWithCreds(url); } /** * Creates a new CLA Manager Request with the specified parameters. * */ createCLAManagerRequest(companyID: string, projectID: string, userName: string, userEmail: string, userLFID: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyID}/project/${projectID}/cla-manager/requests`); const requestBody = { userName: userName, userEmail: userEmail, userLFID: userLFID, }; return this.http.postWithCreds(url, requestBody).map((res) => res.json()); } /** * Returns zero or more CLA manager requests based on the user LFID. * * @param companyID the company ID * @param projectID the project ID */ getCLAManagerRequests(companyID: string, projectID: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyID}/project/${projectID}/cla-manager/requests`); return this.http.getWithCreds(url).map((res) => res.json()); } /** * Approves the CLA manager request using the specified parameters. * * @param companyID the company ID * @param projectID the project ID * @param requestID the unique request id */ approveCLAManagerRequest(companyID: string, projectID: string, requestID: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyID}/project/${projectID}/cla-manager/requests/${requestID}/approve`); return this.http.putWithCreds(url).map((res) => res.json()); } /** * Deny the CLA manager request using the specified parameters. * * @param companyID the company ID * @param projectID the project ID * @param requestID the unique request id */ denyCLAManagerRequest(companyID: string, projectID: string, requestID: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyID}/project/${projectID}/cla-manager/requests/${requestID}/deny`); return this.http.putWithCreds(url).map((res) => res.json()); } /** * Handle service error is a common routine to handle HTTP response errors * @param error the error */ private handleServiceError(error: any) { if (error.status && error._body && error.status === 500 && error._body.includes('Token is expired')) { this.authService.logout(); return Observable.throw(error); } else if (error.status && error.status === 401) { this.authService.logout(); return Observable.throw(error); } console.log('problem invoking service: '); console.log(error); return Observable.throw(error); } getReleaseVersion() { const url: URL = this.getV3Endpoint('/v3/ops/version'); return this.http.getWithoutAuth(url).map((res) => res.json()); } getProjectWhitelistRequest(companyId: string, projectId: string, status: string) { let statusFilter = ''; if (status != null && status.length > 0) { statusFilter = `?status=${status}`; } const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/ccla-whitelist-requests/${projectId}${statusFilter}`); return this.http.get(url).map((res) => res.json()) } approveCclaWhitelistRequest(companyId: string, projectId: string, requestID: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/ccla-whitelist-requests/${projectId}/${requestID}/approve`); return this.http.put(url); } rejectCclaWhitelistRequest(companyId: string, projectId: string, requestID: string) { const url: URL = this.getV3Endpoint(`/v3/company/${companyId}/ccla-whitelist-requests/${projectId}/${requestID}/reject`); return this.http.put(url); } ////////////////////////////////////////////////////////////////////////////// }
the_stack
import { AfterViewInit, Component, EventEmitter, HostListener, Input, Output } from '@angular/core'; import Konva from 'konva'; import { AddPipelineDialogComponent } from '../../dialog/add-pipeline/add-pipeline-dialog.component'; import { MatDialog } from '@angular/material/dialog'; import { ShapeService } from '../../services/shape.service'; import { SelectedVisualizationData } from '../../model/selected-visualization-data.model'; import { SaveDashboardDialogComponent } from '../../dialog/save-dashboard/save-dashboard-dialog.component'; import { PanelType, DialogService } from '@streampipes/shared-ui'; import { DashboardConfiguration } from '../../model/dashboard-configuration.model'; import { RestService } from '../../services/rest.service'; import { AddLinkDialogComponent } from '../../dialog/add-link/add-link-dialog.component'; interface Window { Image: any; } declare const window: Window; @Component({ selector: 'sp-create-asset', templateUrl: './create-asset.component.html', styleUrls: ['./create-asset.component.css'] }) export class CreateAssetComponent implements AfterViewInit { fileName: any; selectedUploadFile: File; mainCanvasStage: Konva.Stage; backgroundImageLayer: any; mainLayer: any; currentlySelectedShape: any; IMAGE_ID = 'main-image'; selectedVisualizationData: SelectedVisualizationData; backgroundImagePresent = false; measurementPresent = false; editMode = false; @Input() dashboardConfig: DashboardConfiguration; @Output() dashboardClosed = new EventEmitter<boolean>(); keyboardListenerActive = true; constructor(public dialog: MatDialog, public shapeService: ShapeService, private dialogService: DialogService, private restService: RestService) { } ngAfterViewInit() { const width = 1400; const height = 900; if (!this.dashboardConfig) { this.mainCanvasStage = new Konva.Stage({ container: 'asset-configuration-board-canvas', width, height }); this.initLayers(); } else { this.editMode = true; this.makeEditable(); this.mainCanvasStage = Konva.Node.create(this.dashboardConfig, 'asset-configuration-board-canvas'); this.mainCanvasStage.draw(); this.backgroundImageLayer = this.mainCanvasStage.children[0]; this.mainLayer = this.mainCanvasStage.children[1]; const groups = this.mainLayer.getChildren().find('Group'); groups.forEach(g => { const id = this.makeId(); g.id(id); g.setDraggable(true); this.addTransformerToShape(id, g); }); this.makeClickable(); this.showImage(); this.backgroundImageLayer.moveToBottom(); this.mainCanvasStage.draw(); this.measurementPresent = true; } const container = this.mainCanvasStage.container(); container.focus(); } makeEditable() { this.dashboardConfig.imageInfo.draggable = true; this.dashboardConfig.imageInfo.id = this.IMAGE_ID; } initLayers() { this.mainLayer = new Konva.Layer(); this.backgroundImageLayer = new Konva.Layer(); this.makeClickable(); this.mainCanvasStage.add(this.backgroundImageLayer); this.mainCanvasStage.add(this.mainLayer); } makeClickable() { this.backgroundImageLayer.on('click', evt => { this.currentlySelectedShape = evt.target; }); this.mainLayer.on('click', evt => { let parentElement = evt.target.getParent(); while (!parentElement.id()) { parentElement = parentElement.getParent(); } this.currentlySelectedShape = parentElement; }); } handleFileInput(event: any) { const files: any = event.target.files; this.selectedUploadFile = files[0]; this.fileName = this.selectedUploadFile.name; const image = new window.Image(); image.onload = () => { const desiredWidth = Math.min(this.mainCanvasStage.width(), image.width); const aspectRatio = image.width / image.height; const desiredHeight = image.width > image.height ? desiredWidth / aspectRatio : desiredWidth * aspectRatio; const imageCanvas = new Konva.Image({ image, width: desiredWidth, height: desiredHeight, x: 0, y: 0, draggable: true, id: this.IMAGE_ID }); this.addImageTransformer(imageCanvas); this.currentlySelectedShape = imageCanvas; }; const reader = new FileReader(); reader.onload = e => image.src = reader.result; reader.readAsDataURL(this.selectedUploadFile); event.target.value = null; } addImageTransformer(imageCanvas: any) { this.backgroundImageLayer.add(imageCanvas); this.backgroundImageLayer.draw(); const tr = this.getNewTransformer(this.IMAGE_ID); this.backgroundImageLayer.add(tr); tr.attachTo(imageCanvas); this.backgroundImageLayer.moveToBottom(); this.backgroundImageLayer.draw(); this.backgroundImagePresent = true; } prepareDashboard() { const dialogRef = this.dialogService.open(SaveDashboardDialogComponent, { panelType: PanelType.SLIDE_IN_PANEL, title: 'Save asset dashboard', width: '50vw', data: { dashboardCanvas: this.mainCanvasStage as any, file: this.selectedUploadFile, editMode: this.editMode, dashboardConfig: this.dashboardConfig } }); dialogRef.afterClosed().subscribe(closed => { this.dashboardClosed.emit(true); }); } clearCanvas() { this.backgroundImageLayer.destroy(); this.mainLayer.destroy(); this.initLayers(); this.backgroundImagePresent = false; this.measurementPresent = false; } openAddPipelineDialog(): void { this.keyboardListenerActive = false; const dialogRef = this.dialogService.open(AddPipelineDialogComponent, { panelType: PanelType.SLIDE_IN_PANEL, title: 'Add visualization', width: '50vw', data: { } }); dialogRef.afterClosed().subscribe(result => { if (result) { const visGroup = this.shapeService.makeNewMeasurementShape(result); this.addNewVisulizationItem(visGroup); this.measurementPresent = true; this.mainLayer.draw(); } this.keyboardListenerActive = true; }); } openAddLinkDialog() { this.keyboardListenerActive = false; const dialogRef = this.dialogService.open(AddLinkDialogComponent, { panelType: PanelType.SLIDE_IN_PANEL, title: 'Add link', width: '50vw', data: { } }); dialogRef.afterClosed().subscribe(result => { if (result) { console.log(result); this.addNewVisulizationItem(result); } this.keyboardListenerActive = true; }); } @HostListener('document:keydown', ['$event']) handleKeyboardEvent(event: KeyboardEvent) { if (this.keyboardListenerActive) { const delta = 4; if (event.code === 'Delete') { const id = this.currentlySelectedShape.id(); this.mainCanvasStage.findOne('#' + id + '-transformer').destroy(); this.currentlySelectedShape.destroy(); if (id === this.IMAGE_ID) { this.backgroundImagePresent = false; } else { const remainingElementIds = this.mainLayer.find('Group'); if (remainingElementIds.length === 0) { this.measurementPresent = false; } } } else if (event.code === 'ArrowLeft') { this.currentlySelectedShape.x(this.currentlySelectedShape.x() - delta); } else if (event.code === 'ArrowRight') { this.currentlySelectedShape.x(this.currentlySelectedShape.x() + delta); } else if (event.code === 'ArrowDown') { this.currentlySelectedShape.y(this.currentlySelectedShape.y() + delta); } else if (event.code === 'ArrowUp') { this.currentlySelectedShape.y(this.currentlySelectedShape.y() - delta); } this.backgroundImageLayer.draw(); this.mainLayer.draw(); } } addNewVisulizationItem(visGroup) { const id = this.makeId(); visGroup.id(id); this.mainLayer.add(visGroup); this.addTransformerToShape(id, visGroup); } addTransformerToShape(id: string, visGroup: any) { const tr = this.getNewTransformer(id); this.mainLayer.add(tr); tr.attachTo(visGroup); this.mainLayer.draw(); this.currentlySelectedShape = visGroup; } getNewTransformer(id: string): Konva.Transformer { return new Konva.Transformer({ anchorStroke: 'white', anchorFill: '#39B54A', anchorSize: 10, borderStroke: 'green', borderDash: [3, 3], keepRatio: true, id: id + '-transformer' }); } makeId() { let text = ''; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 6; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } showImage() { const image = new window.Image(); image.src = this.restService.getImageUrl(this.dashboardConfig.imageInfo.imageName); this.dashboardConfig.imageInfo.image = image; image.onload = () => { const imageCanvas = new Konva.Image(this.dashboardConfig.imageInfo); this.addImageTransformer(imageCanvas); }; } }
the_stack
import { act, fireEvent, screen } from '@testing-library/react' import React, { useState } from 'react' import useSWR, { SWRConfig } from 'swr' import { createKey, renderWithConfig, sleep } from './utils' // This has to be an async function to wait a microtask to flush updates const advanceTimers = async (ms: number) => jest.advanceTimersByTime(ms) // This test heavily depends on setInterval/setTimeout timers, which makes tests slower and flaky. // So we use Jest's fake timers describe('useSWR - refresh', () => { beforeAll(() => { jest.useFakeTimers() }) afterAll(() => { jest.useRealTimers() }) it('should rerender automatically on interval', async () => { let count = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: 200, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(200)) // update screen.getByText('count: 1') await act(() => advanceTimers(50)) // no update screen.getByText('count: 1') await act(() => advanceTimers(150)) // update screen.getByText('count: 2') }) it('should dedupe requests combined with intervals', async () => { let count = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: 100, dedupingInterval: 500 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(100)) // no update (deduped) screen.getByText('count: 0') await act(() => advanceTimers(400)) // reach dudupingInterval await act(() => advanceTimers(100)) // update screen.getByText('count: 1') await act(() => advanceTimers(100)) // no update (deduped) screen.getByText('count: 1') await act(() => advanceTimers(400)) // reach dudupingInterval await act(() => advanceTimers(100)) // update screen.getByText('count: 2') }) it('should update data upon interval changes', async () => { let count = 0 const key = createKey() function Page() { const [int, setInt] = React.useState(100) const { data } = useSWR(key, () => count++, { refreshInterval: int, dedupingInterval: 50 }) return ( <div onClick={() => setInt(num => (num < 200 ? num + 50 : 0))}> count: {data} </div> ) } renderWithConfig(<Page />) screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(100)) screen.getByText('count: 1') await act(() => advanceTimers(50)) screen.getByText('count: 1') await act(() => advanceTimers(50)) screen.getByText('count: 2') fireEvent.click(screen.getByText('count: 2')) await act(() => advanceTimers(100)) screen.getByText('count: 2') await act(() => advanceTimers(50)) screen.getByText('count: 3') await act(() => advanceTimers(150)) screen.getByText('count: 4') fireEvent.click(screen.getByText('count: 4')) await act(() => { // it will clear 150ms timer and setup a new 200ms timer return advanceTimers(150) }) screen.getByText('count: 4') await act(() => advanceTimers(50)) screen.getByText('count: 5') fireEvent.click(screen.getByText('count: 5')) await act(() => { // it will clear 200ms timer and stop return advanceTimers(50) }) screen.getByText('count: 5') await act(() => advanceTimers(50)) screen.getByText('count: 5') }) it('should update data upon interval changes -- changes happened during revalidate', async () => { let count = 0 const STOP_POLLING_THRESHOLD = 2 const key = createKey() function Page() { const [flag, setFlag] = useState(0) const shouldPoll = flag < STOP_POLLING_THRESHOLD const { data } = useSWR(key, () => count++, { refreshInterval: shouldPoll ? 100 : 0, dedupingInterval: 50, onSuccess() { setFlag(value => value + 1) } }) return ( <div onClick={() => setFlag(0)}> count: {data} {flag} </div> ) } renderWithConfig(<Page />) screen.getByText('count: 0') await screen.findByText('count: 0 1') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') fireEvent.click(screen.getByText('count: 1 2')) await act(() => { // it will setup a new 100ms timer return advanceTimers(50) }) screen.getByText('count: 1 0') await act(() => advanceTimers(50)) screen.getByText('count: 2 1') await act(() => advanceTimers(100)) screen.getByText('count: 3 2') await act(() => advanceTimers(100)) screen.getByText('count: 3 2') await act(() => advanceTimers(100)) screen.getByText('count: 3 2') }) it('should allow use custom compare method', async () => { let count = 0 const key = createKey() const fetcher = jest.fn(() => ({ timestamp: ++count, version: '1.0' })) function Page() { const { data, mutate: change } = useSWR(key, fetcher, { compare: function compare(a, b) { if (a === b) { return true } if (!a || !b) { return false } return a.version === b.version } }) if (!data) { return <div>loading</div> } return <button onClick={() => change()}>{data.timestamp}</button> } let customCache function App() { return ( <SWRConfig value={{ provider: () => { return (customCache = new Map()) } }} > <Page /> </SWRConfig> ) } renderWithConfig(<App />) screen.getByText('loading') await screen.findByText('1') expect(fetcher).toBeCalledTimes(1) expect(fetcher).toReturnWith({ timestamp: 1, version: '1.0' }) fireEvent.click(screen.getByText('1')) await act(() => advanceTimers(1)) expect(fetcher).toBeCalledTimes(2) expect(fetcher).toReturnWith({ timestamp: 2, version: '1.0' }) const cachedData = customCache.get(key) expect(cachedData.timestamp.toString()).toEqual('1') screen.getByText('1') }) it('should not let the previous interval timer to set new timer if key changes too fast', async () => { const key = createKey() const fetcherWithToken = jest.fn(async token => { await sleep(200) return token }) function Page() { const [count, setCount] = useState(0) const { data } = useSWR(`${key}-${count}`, fetcherWithToken, { refreshInterval: 100, dedupingInterval: 50 }) return ( <button onClick={() => setCount(count + 1)} >{`click me ${data}`}</button> ) } renderWithConfig(<Page />) // initial revalidate await act(() => advanceTimers(200)) expect(fetcherWithToken).toBeCalledTimes(1) // first refresh await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(2) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-0`) await act(() => advanceTimers(200)) // second refresh start await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(3) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-0`) // change the key during revalidation // The second refresh will not start a new timer fireEvent.click(screen.getByText(`click me ${key}-0`)) // first refresh with new key 1 await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(4) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-1`) await act(() => advanceTimers(200)) // second refresh with new key 1 await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(5) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-1`) }) it('should not call onSuccess from the previous interval if key has changed', async () => { const fetcherWithToken = jest.fn(async token => { await sleep(100) return token }) const onSuccess = jest.fn((data, key) => { return `${data} ${key}` }) const key = createKey() function Page() { const [count, setCount] = useState(0) const { data } = useSWR(`${count.toString()}-${key}`, fetcherWithToken, { refreshInterval: 50, dedupingInterval: 25, onSuccess }) return ( <button onClick={() => setCount(count + 1)} >{`click me ${data}`}</button> ) } renderWithConfig(<Page />) // initial revalidate await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(1) expect(onSuccess).toBeCalledTimes(1) expect(onSuccess).toHaveLastReturnedWith(`0-${key} 0-${key}`) // first refresh await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(2) expect(fetcherWithToken).toHaveBeenLastCalledWith(`0-${key}`) await act(() => advanceTimers(100)) expect(onSuccess).toBeCalledTimes(2) expect(onSuccess).toHaveLastReturnedWith(`0-${key} 0-${key}`) // second refresh start await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(3) expect(fetcherWithToken).toHaveBeenLastCalledWith(`0-${key}`) // change the key during revalidation // The second refresh will not start a new timer fireEvent.click(screen.getByText(`click me 0-${key}`)) // first refresh with new key 1 await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(4) expect(fetcherWithToken).toHaveBeenLastCalledWith(`1-${key}`) await act(() => advanceTimers(100)) expect(onSuccess).toBeCalledTimes(3) expect(onSuccess).toHaveLastReturnedWith(`1-${key} 1-${key}`) // second refresh with new key 1 await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(5) expect(fetcherWithToken).toHaveBeenLastCalledWith(`1-${key}`) }) it('should allow using function as an interval', async () => { let count = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: () => 200, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(200)) // update screen.getByText('count: 1') await act(() => advanceTimers(50)) // no update screen.getByText('count: 1') await act(() => advanceTimers(150)) // update screen.getByText('count: 2') }) it('should pass updated data to refreshInterval', async () => { let count = 1 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: updatedCount => updatedCount * 1000, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 1') await act(() => advanceTimers(1000)) // updated after 1s screen.getByText('count: 2') await act(() => advanceTimers(1000)) // no update screen.getByText('count: 2') await act(() => advanceTimers(1000)) // updated after 2s screen.getByText('count: 3') await act(() => advanceTimers(2000)) // no update screen.getByText('count: 3') await act(() => advanceTimers(1000)) // updated after 3s screen.getByText('count: 4') }) it('should disable refresh if function returns 0', async () => { let count = 1 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: () => 0, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 1') await act(() => advanceTimers(9999)) // no update screen.getByText('count: 1') }) })
the_stack
import {WorkerAssociation} from './interfaces/workerassociation-params'; import {MetaUtils } from "../metadata/utils"; import {Decorators} from '../constants/decorators'; import {DecoratorType} from '../enums/decorator-type'; var child_process = require('child_process'); import * as Enumerable from 'linq'; import {winstonLog} from '../../logging/winstonLog'; import {WorkerParams} from './interfaces/worker-params'; import {workerParamsDto} from "./interfaces/workerParamsDto"; import * as configUtil from '../utils'; import {PrincipalContext} from '../../security/auth/principalContext'; var fs = require('fs'); var defaultWorkerName = "core/decorators/worker.js"; var cls = require('continuation-local-storage'); var uuid = require('uuid'); var workerProcess: Array<WorkerProcess> = new Array<WorkerProcess>(); var tasks: Array<workerParamsDto> = new Array<workerParamsDto>(); //update from configuration var _appRoot = process.cwd(); var _defaultWorker = 'worker.js'; var _defaultNumnberOfWorker = 1; class WorkerProcess { name: string; processId: number; executing: workerParamsDto; initialized: boolean; fork: any; } export function Worker(params?: WorkerAssociation): any { params = params || <any>{}; var session = PrincipalContext.getSession(); return function (target: any, propertyKey: string, descriptor: any) { console.log("target is: " + target + " propertyKey " + propertyKey + " descriptor is: " + descriptor); MetaUtils.addMetaData(target, { decorator: Decorators.WORKER, decoratorType: DecoratorType.METHOD, params: params, propertyKey: propertyKey }); var originalMethod = descriptor.value; winstonLog.logDebug("Input params for worker: " + params.workerParams); descriptor.value = executeWorkerHandler(params, target, propertyKey, originalMethod, Decorators.WORKER); } } // Add debug options function getDebugOption(offset: number) { var execArgv = (<any>process).execArgv.slice(); //create args shallow copy var debugPort = (<any>process).debugPort + offset + 1; console.log("Debugging port:", debugPort); for (var i = 0; i < execArgv.length; i++) { var match = execArgv[i].match(/^(--debug|--debug-brk)(=\d+)?$/); if (match) { execArgv[i] = match[1] + '=' + debugPort; break; } } //var options = { env: process.env, silent:false, execArgv: execArgv, cwd: targetProcessCwd }; var options = { env: process.env, silent: false, execArgv: execArgv }; return options; } function sendNextMessage(process: WorkerProcess, received: workerParamsDto) { if (received) { console.log('success message from Child Process: ' + received); } process.initialized = true; process.executing = null; if (tasks.length > 0) { var par = tasks.shift(); par.processId = process.processId; process.executing = par; process.fork.send(par); } } function executeNextProcess(param: workerParamsDto) { var proc: WorkerProcess; var workerName = configUtil.config().Config.worker ? (_appRoot + '/' + configUtil.config().Config.worker) : (_appRoot + '/' + _defaultWorker); var thread: number = configUtil.config().Config.process ? configUtil.config().Config.process : _defaultNumnberOfWorker; if (thread > 0) { tasks.push(param); if (workerProcess.length < thread) { // create new process entry and spawn it proc = new WorkerProcess(); proc.name = 'worker' + workerProcess.length + 1; var path = workerName; if (configUtil.config().Config.worker) { path = _appRoot + '/' + configUtil.config().Config.worker; } proc.fork = child_process.fork(path, [], getDebugOption(workerProcess.length)); winstonLog.logInfo(`Forking a new child_process: path- ${path}, p id-${proc.fork.pid} `); if (proc.fork.error == null) { proc.processId = proc.fork.pid; proc.executing = <workerParamsDto>({ initialize: true, processId: proc.processId }); winstonLog.logInfo('Child process created with id: ' + proc.fork.pid); proc.fork.on('message', function (message: any) { // notify service attached with this process try { var par: workerParamsDto = <workerParamsDto>(message); console.log('received message parsed successful'); var proc = Enumerable.from(workerProcess).firstOrDefault(x => x.processId == par.processId); if (proc) { sendNextMessage(proc, par); } } catch (exc) { console.log("failed message from Child Process: "); console.log(exc); } }); proc.fork.on('error', function (err) { winstonLog.logError('Error : ' + err); // notify service attached with this process }); proc.fork.on('close', function (code, signal) { winstonLog.logInfo('Child process exited with code: ' + code + ' signal: ' + signal); // notify service attached with this process }); workerProcess.push(proc); winstonLog.logInfo('sending worker:' + proc.executing); proc.fork.send(proc.executing); } else { winstonLog.logError("Error during creating child Process: " + proc.fork.error); } } else { proc = Enumerable.from(workerProcess).firstOrDefault(x => !x.executing); if (proc) { sendNextMessage(proc, null); } } } else { // always create new process and terminate on execution } return process; } export function executeWorkerHandler(params, target, propertyKey, originalMethod, type: string,noExecution?:boolean) { return function () { if (MetaUtils.childProcessId || !configUtil.config().Config.isMultiThreaded) { winstonLog.logInfo("Executing method from child Process with id: " + process.pid); return originalMethod.apply(this, arguments); } var targetObjectId: any; if (params.indexofArgumentForTargetObjectId) targetObjectId = arguments[params.indexofArgumentForTargetObjectId]; if (params.indexofArgumentForTargetObject) targetObjectId = arguments[params.indexofArgumentForTargetObject]._id; var serviceName, servicemethodName, paramsArguments; var name = params.name; var workerParams = new workerParamsDto(); if (params.workerParams == null) { winstonLog.logInfo("No Params sent with Worker()"); var decorators = MetaUtils.getMetaData(target); var dec = Enumerable.from(decorators).where(x => x.decorator == Decorators.SERVICE).firstOrDefault(); if (dec) { workerParams.serviceName = dec.params.serviceName; } servicemethodName = propertyKey; workerParams.servicemethodName = servicemethodName; paramsArguments = arguments; workerParams.arguments = paramsArguments; } else { if (params.workerParams.serviceName != null && params.workerParams.serviceName != '') { serviceName = params.workerParams.serviceName; workerParams.serviceName = serviceName; } else { var decorators = MetaUtils.getMetaData(target); var dec = Enumerable.from(decorators).where(x => x.decorator == Decorators.SERVICE).firstOrDefault(); if (dec) { workerParams.serviceName = dec.params.serviceName; } workerParams.serviceName = serviceName; } if (params.workerParams.servicemethodName != null && params.workerParams.servicemethodName != '') { servicemethodName = params.workerParams.servicemethodName; workerParams.servicemethodName = servicemethodName; } else { servicemethodName = propertyKey; workerParams.servicemethodName = servicemethodName; } if (params.workerParams.arguments != null && params.workerParams.arguments != '') { paramsArguments = params.workerParams.arguments; workerParams.arguments = paramsArguments; } else { paramsArguments = arguments; workerParams.arguments = paramsArguments; } } workerParams.arguments = Array.prototype.slice.call(workerParams.arguments); workerParams.arguments = <any>workerParams.arguments.slice(0, originalMethod.length); //winstonLog.logInfo("Worker Params: " + workerParams); //PrincipalContext.save('workerParams', JSON.stringify(workerParams)); workerParams.principalContext = PrincipalContext.getAllKeyValues(); let reqHeaders = workerParams.principalContext['req'].headers; if (workerParams.principalContext['req']) { delete workerParams.principalContext['req']; workerParams.principalContext['req'] = {}; workerParams.principalContext['req'].headers = reqHeaders; } if (workerParams.principalContext['res']) { delete workerParams.principalContext['res']; } //console.log(`task will execute: Service Name ${workerParams.serviceName}, Method Name ${workerParams.servicemethodName}, Args ${workerParams.arguments}`); if (workerParams.serviceName != null) { workerParams.id = uuid.v4(); if (!noExecution) { var proc = executeNextProcess(workerParams); } // console.log("Context at Worker: " + workerParams.principalContext); // console.log("PrincipalConext at Parent: " + PrincipalContext.getSession()); } return workerParams; }; }
the_stack
import { deepCopy } from '../utils/deep-copy'; import { isNonNullObject } from '../utils/validator'; import * as utils from '../utils'; import { AuthClientErrorCode, FirebaseAuthError } from '../utils/error'; /** * 'REDACTED', encoded as a base64 string. */ const B64_REDACTED = Buffer.from('REDACTED').toString('base64'); /** * Parses a time stamp string or number and returns the corresponding date if valid. * * @param time - The unix timestamp string or number in milliseconds. * @returns The corresponding date as a UTC string, if valid. Otherwise, null. */ function parseDate(time: any): string | null { try { const date = new Date(parseInt(time, 10)); if (!isNaN(date.getTime())) { return date.toUTCString(); } } catch (e) { // Do nothing. null will be returned. } return null; } export interface MultiFactorInfoResponse { mfaEnrollmentId: string; displayName?: string; phoneInfo?: string; enrolledAt?: string; [key: string]: any; } export interface ProviderUserInfoResponse { rawId: string; displayName?: string; email?: string; photoUrl?: string; phoneNumber?: string; providerId: string; federatedId?: string; } export interface GetAccountInfoUserResponse { localId: string; email?: string; emailVerified?: boolean; phoneNumber?: string; displayName?: string; photoUrl?: string; disabled?: boolean; passwordHash?: string; salt?: string; customAttributes?: string; validSince?: string; tenantId?: string; providerUserInfo?: ProviderUserInfoResponse[]; mfaInfo?: MultiFactorInfoResponse[]; createdAt?: string; lastLoginAt?: string; lastRefreshAt?: string; [key: string]: any; } enum MultiFactorId { Phone = 'phone', } /** * Interface representing the common properties of a user-enrolled second factor. */ export abstract class MultiFactorInfo { /** * The ID of the enrolled second factor. This ID is unique to the user. */ public readonly uid: string; /** * The optional display name of the enrolled second factor. */ public readonly displayName?: string; /** * The type identifier of the second factor. For SMS second factors, this is `phone`. */ public readonly factorId: string; /** * The optional date the second factor was enrolled, formatted as a UTC string. */ public readonly enrollmentTime?: string; /** * Initializes the MultiFactorInfo associated subclass using the server side. * If no MultiFactorInfo is associated with the response, null is returned. * * @param response - The server side response. * @internal */ public static initMultiFactorInfo(response: MultiFactorInfoResponse): MultiFactorInfo | null { let multiFactorInfo: MultiFactorInfo | null = null; // Only PhoneMultiFactorInfo currently available. try { multiFactorInfo = new PhoneMultiFactorInfo(response); } catch (e) { // Ignore error. } return multiFactorInfo; } /** * Initializes the MultiFactorInfo object using the server side response. * * @param response - The server side response. * @constructor * @internal */ constructor(response: MultiFactorInfoResponse) { this.initFromServerResponse(response); } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ public toJSON(): object { return { uid: this.uid, displayName: this.displayName, factorId: this.factorId, enrollmentTime: this.enrollmentTime, }; } /** * Returns the factor ID based on the response provided. * * @param response - The server side response. * @returns The multi-factor ID associated with the provided response. If the response is * not associated with any known multi-factor ID, null is returned. * * @internal */ protected abstract getFactorId(response: MultiFactorInfoResponse): string | null; /** * Initializes the MultiFactorInfo object using the provided server response. * * @param response - The server side response. */ private initFromServerResponse(response: MultiFactorInfoResponse): void { const factorId = response && this.getFactorId(response); if (!factorId || !response || !response.mfaEnrollmentId) { throw new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor info response'); } utils.addReadonlyGetter(this, 'uid', response.mfaEnrollmentId); utils.addReadonlyGetter(this, 'factorId', factorId); utils.addReadonlyGetter(this, 'displayName', response.displayName); // Encoded using [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. // For example, "2017-01-15T01:30:15.01Z". // This can be parsed directly via Date constructor. // This can be computed using Data.prototype.toISOString. if (response.enrolledAt) { utils.addReadonlyGetter( this, 'enrollmentTime', new Date(response.enrolledAt).toUTCString()); } else { utils.addReadonlyGetter(this, 'enrollmentTime', null); } } } /** * Interface representing a phone specific user-enrolled second factor. */ export class PhoneMultiFactorInfo extends MultiFactorInfo { /** * The phone number associated with a phone second factor. */ public readonly phoneNumber: string; /** * Initializes the PhoneMultiFactorInfo object using the server side response. * * @param response - The server side response. * @constructor * @internal */ constructor(response: MultiFactorInfoResponse) { super(response); utils.addReadonlyGetter(this, 'phoneNumber', response.phoneInfo); } /** * {@inheritdoc MultiFactorInfo.toJSON} */ public toJSON(): object { return Object.assign( super.toJSON(), { phoneNumber: this.phoneNumber, }); } /** * Returns the factor ID based on the response provided. * * @param response - The server side response. * @returns The multi-factor ID associated with the provided response. If the response is * not associated with any known multi-factor ID, null is returned. * * @internal */ protected getFactorId(response: MultiFactorInfoResponse): string | null { return (response && response.phoneInfo) ? MultiFactorId.Phone : null; } } /** * The multi-factor related user settings. */ export class MultiFactorSettings { /** * List of second factors enrolled with the current user. * Currently only phone second factors are supported. */ public enrolledFactors: MultiFactorInfo[]; /** * Initializes the MultiFactor object using the server side or JWT format response. * * @param response - The server side response. * @constructor * @internal */ constructor(response: GetAccountInfoUserResponse) { const parsedEnrolledFactors: MultiFactorInfo[] = []; if (!isNonNullObject(response)) { throw new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor response'); } else if (response.mfaInfo) { response.mfaInfo.forEach((factorResponse) => { const multiFactorInfo = MultiFactorInfo.initMultiFactorInfo(factorResponse); if (multiFactorInfo) { parsedEnrolledFactors.push(multiFactorInfo); } }); } // Make enrolled factors immutable. utils.addReadonlyGetter( this, 'enrolledFactors', Object.freeze(parsedEnrolledFactors)); } /** * Returns a JSON-serializable representation of this multi-factor object. * * @returns A JSON-serializable representation of this multi-factor object. */ public toJSON(): object { return { enrolledFactors: this.enrolledFactors.map((info) => info.toJSON()), }; } } /** * Represents a user's metadata. */ export class UserMetadata { /** * The date the user was created, formatted as a UTC string. */ public readonly creationTime: string; /** * The date the user last signed in, formatted as a UTC string. */ public readonly lastSignInTime: string; /** * The time at which the user was last active (ID token refreshed), * formatted as a UTC Date string (eg 'Sat, 03 Feb 2001 04:05:06 GMT'). * Returns null if the user was never active. */ public readonly lastRefreshTime?: string | null; /** * @param response - The server side response returned from the getAccountInfo * endpoint. * @constructor * @internal */ constructor(response: GetAccountInfoUserResponse) { // Creation date should always be available but due to some backend bugs there // were cases in the past where users did not have creation date properly set. // This included legacy Firebase migrating project users and some anonymous users. // These bugs have already been addressed since then. utils.addReadonlyGetter(this, 'creationTime', parseDate(response.createdAt)); utils.addReadonlyGetter(this, 'lastSignInTime', parseDate(response.lastLoginAt)); const lastRefreshAt = response.lastRefreshAt ? new Date(response.lastRefreshAt).toUTCString() : null; utils.addReadonlyGetter(this, 'lastRefreshTime', lastRefreshAt); } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ public toJSON(): object { return { lastSignInTime: this.lastSignInTime, creationTime: this.creationTime, }; } } /** * Represents a user's info from a third-party identity provider * such as Google or Facebook. */ export class UserInfo { /** * The user identifier for the linked provider. */ public readonly uid: string; /** * The display name for the linked provider. */ public readonly displayName: string; /** * The email for the linked provider. */ public readonly email: string; /** * The photo URL for the linked provider. */ public readonly photoURL: string; /** * The linked provider ID (for example, "google.com" for the Google provider). */ public readonly providerId: string; /** * The phone number for the linked provider. */ public readonly phoneNumber: string; /** * @param response - The server side response returned from the `getAccountInfo` * endpoint. * @constructor * @internal */ constructor(response: ProviderUserInfoResponse) { // Provider user id and provider id are required. if (!response.rawId || !response.providerId) { throw new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user info response'); } utils.addReadonlyGetter(this, 'uid', response.rawId); utils.addReadonlyGetter(this, 'displayName', response.displayName); utils.addReadonlyGetter(this, 'email', response.email); utils.addReadonlyGetter(this, 'photoURL', response.photoUrl); utils.addReadonlyGetter(this, 'providerId', response.providerId); utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber); } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ public toJSON(): object { return { uid: this.uid, displayName: this.displayName, email: this.email, photoURL: this.photoURL, providerId: this.providerId, phoneNumber: this.phoneNumber, }; } } /** * Represents a user. */ export class UserRecord { /** * The user's `uid`. */ public readonly uid: string; /** * The user's primary email, if set. */ public readonly email?: string; /** * Whether or not the user's primary email is verified. */ public readonly emailVerified: boolean; /** * The user's display name. */ public readonly displayName?: string; /** * The user's photo URL. */ public readonly photoURL?: string; /** * The user's primary phone number, if set. */ public readonly phoneNumber?: string; /** * Whether or not the user is disabled: `true` for disabled; `false` for * enabled. */ public readonly disabled: boolean; /** * Additional metadata about the user. */ public readonly metadata: UserMetadata; /** * An array of providers (for example, Google, Facebook) linked to the user. */ public readonly providerData: UserInfo[]; /** * The user's hashed password (base64-encoded), only if Firebase Auth hashing * algorithm (SCRYPT) is used. If a different hashing algorithm had been used * when uploading this user, as is typical when migrating from another Auth * system, this will be an empty string. If no password is set, this is * null. This is only available when the user is obtained from * {@link BaseAuth.listUsers}. */ public readonly passwordHash?: string; /** * The user's password salt (base64-encoded), only if Firebase Auth hashing * algorithm (SCRYPT) is used. If a different hashing algorithm had been used to * upload this user, typical when migrating from another Auth system, this will * be an empty string. If no password is set, this is null. This is only * available when the user is obtained from {@link BaseAuth.listUsers}. */ public readonly passwordSalt?: string; /** * The user's custom claims object if available, typically used to define * user roles and propagated to an authenticated user's ID token. * This is set via {@link BaseAuth.setCustomUserClaims} */ public readonly customClaims?: {[key: string]: any}; /** * The ID of the tenant the user belongs to, if available. */ public readonly tenantId?: string | null; /** * The date the user's tokens are valid after, formatted as a UTC string. * This is updated every time the user's refresh token are revoked either * from the {@link BaseAuth.revokeRefreshTokens} * API or from the Firebase Auth backend on big account changes (password * resets, password or email updates, etc). */ public readonly tokensValidAfterTime?: string; /** * The multi-factor related properties for the current user, if available. */ public readonly multiFactor?: MultiFactorSettings; /** * @param response - The server side response returned from the getAccountInfo * endpoint. * @constructor * @internal */ constructor(response: GetAccountInfoUserResponse) { // The Firebase user id is required. if (!response.localId) { throw new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user response'); } utils.addReadonlyGetter(this, 'uid', response.localId); utils.addReadonlyGetter(this, 'email', response.email); utils.addReadonlyGetter(this, 'emailVerified', !!response.emailVerified); utils.addReadonlyGetter(this, 'displayName', response.displayName); utils.addReadonlyGetter(this, 'photoURL', response.photoUrl); utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber); // If disabled is not provided, the account is enabled by default. utils.addReadonlyGetter(this, 'disabled', response.disabled || false); utils.addReadonlyGetter(this, 'metadata', new UserMetadata(response)); const providerData: UserInfo[] = []; for (const entry of (response.providerUserInfo || [])) { providerData.push(new UserInfo(entry)); } utils.addReadonlyGetter(this, 'providerData', providerData); // If the password hash is redacted (probably due to missing permissions) // then clear it out, similar to how the salt is returned. (Otherwise, it // *looks* like a b64-encoded hash is present, which is confusing.) if (response.passwordHash === B64_REDACTED) { utils.addReadonlyGetter(this, 'passwordHash', undefined); } else { utils.addReadonlyGetter(this, 'passwordHash', response.passwordHash); } utils.addReadonlyGetter(this, 'passwordSalt', response.salt); if (response.customAttributes) { utils.addReadonlyGetter( this, 'customClaims', JSON.parse(response.customAttributes)); } let validAfterTime: string | null = null; // Convert validSince first to UTC milliseconds and then to UTC date string. if (typeof response.validSince !== 'undefined') { validAfterTime = parseDate(parseInt(response.validSince, 10) * 1000); } utils.addReadonlyGetter(this, 'tokensValidAfterTime', validAfterTime || undefined); utils.addReadonlyGetter(this, 'tenantId', response.tenantId); const multiFactor = new MultiFactorSettings(response); if (multiFactor.enrolledFactors.length > 0) { utils.addReadonlyGetter(this, 'multiFactor', multiFactor); } } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ public toJSON(): object { const json: any = { uid: this.uid, email: this.email, emailVerified: this.emailVerified, displayName: this.displayName, photoURL: this.photoURL, phoneNumber: this.phoneNumber, disabled: this.disabled, // Convert metadata to json. metadata: this.metadata.toJSON(), passwordHash: this.passwordHash, passwordSalt: this.passwordSalt, customClaims: deepCopy(this.customClaims), tokensValidAfterTime: this.tokensValidAfterTime, tenantId: this.tenantId, }; if (this.multiFactor) { json.multiFactor = this.multiFactor.toJSON(); } json.providerData = []; for (const entry of this.providerData) { // Convert each provider data to json. json.providerData.push(entry.toJSON()); } return json; } }
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/fusiontables/v2/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Fusion Tables API v2 */ function load(name: "fusiontables", version: "v2"): PromiseLike<void>; function load(name: "fusiontables", version: "v2", callback: () => any): void; const column: fusiontables.ColumnResource; const query: fusiontables.QueryResource; const style: fusiontables.StyleResource; const table: fusiontables.TableResource; const task: fusiontables.TaskResource; const template: fusiontables.TemplateResource; namespace fusiontables { interface Bucket { /** Color of line or the interior of a polygon in #RRGGBB format. */ color?: string; /** Icon name used for a point. */ icon?: string; /** Maximum value in the selected column for a row to be styled according to the bucket color, opacity, icon, or weight. */ max?: number; /** Minimum value in the selected column for a row to be styled according to the bucket color, opacity, icon, or weight. */ min?: number; /** Opacity of the color: 0.0 (transparent) to 1.0 (opaque). */ opacity?: number; /** Width of a line (in pixels). */ weight?: number; } interface Column { /** Identifier of the base column. If present, this column is derived from the specified base column. */ baseColumn?: { /** The id of the column in the base table from which this column is derived. */ columnId?: number; /** Offset to the entry in the list of base tables in the table definition. */ tableIndex?: number; }; /** Identifier for the column. */ columnId?: number; /** JSON schema for interpreting JSON in this column. */ columnJsonSchema?: string; /** JSON object containing custom column properties. */ columnPropertiesJson?: string; /** Column description. */ description?: string; /** * Format pattern. * Acceptable values are DT_DATE_MEDIUMe.g Dec 24, 2008 DT_DATE_SHORTfor example 12/24/08 DT_DATE_TIME_MEDIUMfor example Dec 24, 2008 8:30:45 PM * DT_DATE_TIME_SHORTfor example 12/24/08 8:30 PM DT_DAY_MONTH_2_DIGIT_YEARfor example 24/12/08 DT_DAY_MONTH_2_DIGIT_YEAR_TIMEfor example 24/12/08 20:30 * DT_DAY_MONTH_2_DIGIT_YEAR_TIME_MERIDIANfor example 24/12/08 8:30 PM DT_DAY_MONTH_4_DIGIT_YEARfor example 24/12/2008 DT_DAY_MONTH_4_DIGIT_YEAR_TIMEfor * example 24/12/2008 20:30 DT_DAY_MONTH_4_DIGIT_YEAR_TIME_MERIDIANfor example 24/12/2008 8:30 PM DT_ISO_YEAR_MONTH_DAYfor example 2008-12-24 * DT_ISO_YEAR_MONTH_DAY_TIMEfor example 2008-12-24 20:30:45 DT_MONTH_DAY_4_DIGIT_YEARfor example 12/24/2008 DT_TIME_LONGfor example 8:30:45 PM UTC-6 * DT_TIME_MEDIUMfor example 8:30:45 PM DT_TIME_SHORTfor example 8:30 PM DT_YEAR_ONLYfor example 2008 HIGHLIGHT_UNTYPED_CELLSHighlight cell data that does * not match the data type NONENo formatting (default) NUMBER_CURRENCYfor example $1234.56 NUMBER_DEFAULTfor example 1,234.56 NUMBER_INTEGERfor example * 1235 NUMBER_NO_SEPARATORfor example 1234.56 NUMBER_PERCENTfor example 123,456% NUMBER_SCIENTIFICfor example 1E3 STRING_EIGHT_LINE_IMAGEDisplays * thumbnail images as tall as eight lines of text STRING_FOUR_LINE_IMAGEDisplays thumbnail images as tall as four lines of text STRING_JSON_TEXTAllows * editing of text as JSON in UI STRING_JSON_LISTAllows editing of text as a JSON list in UI STRING_LINKTreats cell as a link (must start with http:// or * https://) STRING_ONE_LINE_IMAGEDisplays thumbnail images as tall as one line of text STRING_VIDEO_OR_MAPDisplay a video or map thumbnail */ formatPattern?: string; /** * Column graph predicate. * Used to map table to graph data model (subject,predicate,object) * See W3C Graph-based Data Model. */ graphPredicate?: string; /** The kind of item this is. For a column, this is always fusiontables#column. */ kind?: string; /** Name of the column. */ name?: string; /** Type of the column. */ type?: string; /** List of valid values used to validate data and supply a drop-down list of values in the web application. */ validValues?: string[]; /** If true, data entered via the web application is validated. */ validateData?: boolean; } interface ColumnList { /** List of all requested columns. */ items?: Column[]; /** The kind of item this is. For a column list, this is always fusiontables#columnList. */ kind?: string; /** Token used to access the next page of this result. No token is displayed if there are no more pages left. */ nextPageToken?: string; /** Total number of columns for the table. */ totalItems?: number; } interface Geometry { /** The list of geometries in this geometry collection. */ geometries?: any[]; geometry?: any; /** Type: A collection of geometries. */ type?: string; } interface Import { /** The kind of item this is. For an import, this is always fusiontables#import. */ kind?: string; /** The number of rows received from the import request. */ numRowsReceived?: string; } interface Line { /** The coordinates that define the line. */ coordinates?: number[][]; /** Type: A line geometry. */ type?: string; } interface LineStyle { /** Color of the line in #RRGGBB format. */ strokeColor?: string; /** Column-value, gradient or buckets styler that is used to determine the line color and opacity. */ strokeColorStyler?: StyleFunction; /** Opacity of the line : 0.0 (transparent) to 1.0 (opaque). */ strokeOpacity?: number; /** Width of the line in pixels. */ strokeWeight?: number; /** Column-value or bucket styler that is used to determine the width of the line. */ strokeWeightStyler?: StyleFunction; } interface Point { /** The coordinates that define the point. */ coordinates?: number[]; /** Point: A point geometry. */ type?: string; } interface PointStyle { /** Name of the icon. Use values defined in http://www.google.com/fusiontables/DataSource?dsrcid=308519 */ iconName?: string; /** Column or a bucket value from which the icon name is to be determined. */ iconStyler?: StyleFunction; } interface Polygon { /** The coordinates that define the polygon. */ coordinates?: number[][][]; /** Type: A polygon geometry. */ type?: string; } interface PolygonStyle { /** Color of the interior of the polygon in #RRGGBB format. */ fillColor?: string; /** Column-value, gradient, or bucket styler that is used to determine the interior color and opacity of the polygon. */ fillColorStyler?: StyleFunction; /** Opacity of the interior of the polygon: 0.0 (transparent) to 1.0 (opaque). */ fillOpacity?: number; /** Color of the polygon border in #RRGGBB format. */ strokeColor?: string; /** Column-value, gradient or buckets styler that is used to determine the border color and opacity. */ strokeColorStyler?: StyleFunction; /** Opacity of the polygon border: 0.0 (transparent) to 1.0 (opaque). */ strokeOpacity?: number; /** Width of the polyon border in pixels. */ strokeWeight?: number; /** Column-value or bucket styler that is used to determine the width of the polygon border. */ strokeWeightStyler?: StyleFunction; } interface Sqlresponse { /** Columns in the table. */ columns?: string[]; /** The kind of item this is. For responses to SQL queries, this is always fusiontables#sqlresponse. */ kind?: string; /** * The rows in the table. For each cell we print out whatever cell value (e.g., numeric, string) exists. Thus it is important that each cell contains only * one value. */ rows?: any[][]; } interface StyleFunction { /** Bucket function that assigns a style based on the range a column value falls into. */ buckets?: Bucket[]; /** Name of the column whose value is used in the style. */ columnName?: string; /** Gradient function that interpolates a range of colors based on column value. */ gradient?: { /** Array with two or more colors. */ colors?: Array<{ /** Color in #RRGGBB format. */ color?: string; /** Opacity of the color: 0.0 (transparent) to 1.0 (opaque). */ opacity?: number; }>; /** Higher-end of the interpolation range: rows with this value will be assigned to colors[n-1]. */ max?: number; /** Lower-end of the interpolation range: rows with this value will be assigned to colors[0]. */ min?: number; }; /** * Stylers can be one of three kinds: "fusiontables#fromColumn if the column value is to be used as is, i.e., the column values can have colors in * #RRGGBBAA format or integer line widths or icon names; fusiontables#gradient if the styling of the row is to be based on applying the gradient function * on the column value; or fusiontables#buckets if the styling is to based on the bucket into which the the column value falls. */ kind?: string; } interface StyleSetting { /** * The kind of item this is. A StyleSetting contains the style definitions for points, lines, and polygons in a table. Since a table can have any one or * all of them, a style definition can have point, line and polygon style definitions. */ kind?: string; /** Style definition for points in the table. */ markerOptions?: PointStyle; /** Optional name for the style setting. */ name?: string; /** Style definition for polygons in the table. */ polygonOptions?: PolygonStyle; /** Style definition for lines in the table. */ polylineOptions?: LineStyle; /** Identifier for the style setting (unique only within tables). */ styleId?: number; /** Identifier for the table. */ tableId?: string; } interface StyleSettingList { /** All requested style settings. */ items?: StyleSetting[]; /** The kind of item this is. For a style list, this is always fusiontables#styleSettingList . */ kind?: string; /** Token used to access the next page of this result. No token is displayed if there are no more styles left. */ nextPageToken?: string; /** Total number of styles for the table. */ totalItems?: number; } interface Table { /** Attribution assigned to the table. */ attribution?: string; /** Optional link for attribution. */ attributionLink?: string; /** Base table identifier if this table is a view or merged table. */ baseTableIds?: string[]; /** Default JSON schema for validating all JSON column properties. */ columnPropertiesJsonSchema?: string; /** Columns in the table. */ columns?: Column[]; /** Description assigned to the table. */ description?: string; /** Variable for whether table is exportable. */ isExportable?: boolean; /** The kind of item this is. For a table, this is always fusiontables#table. */ kind?: string; /** Name assigned to a table. */ name?: string; /** SQL that encodes the table definition for derived tables. */ sql?: string; /** Encrypted unique alphanumeric identifier for the table. */ tableId?: string; /** JSON object containing custom table properties. */ tablePropertiesJson?: string; /** JSON schema for validating the JSON table properties. */ tablePropertiesJsonSchema?: string; } interface TableList { /** List of all requested tables. */ items?: Table[]; /** The kind of item this is. For table list, this is always fusiontables#tableList. */ kind?: string; /** Token used to access the next page of this result. No token is displayed if there are no more pages left. */ nextPageToken?: string; } interface Task { /** Type of the resource. This is always "fusiontables#task". */ kind?: string; /** Task percentage completion. */ progress?: string; /** false while the table is busy with some other task. true if this background task is currently running. */ started?: boolean; /** Identifier for the task. */ taskId?: string; /** Type of background task. */ type?: string; } interface TaskList { /** List of all requested tasks. */ items?: Task[]; /** Type of the resource. This is always "fusiontables#taskList". */ kind?: string; /** Token used to access the next page of this result. No token is displayed if there are no more pages left. */ nextPageToken?: string; /** Total number of tasks for the table. */ totalItems?: number; } interface Template { /** List of columns from which the template is to be automatically constructed. Only one of body or automaticColumns can be specified. */ automaticColumnNames?: string[]; /** * Body of the template. It contains HTML with {column_name} to insert values from a particular column. The body is sanitized to remove certain tags, * e.g., script. Only one of body or automaticColumns can be specified. */ body?: string; /** The kind of item this is. For a template, this is always fusiontables#template. */ kind?: string; /** Optional name assigned to a template. */ name?: string; /** Identifier for the table for which the template is defined. */ tableId?: string; /** Identifier for the template, unique within the context of a particular table. */ templateId?: number; } interface TemplateList { /** List of all requested templates. */ items?: Template[]; /** The kind of item this is. For a template list, this is always fusiontables#templateList . */ kind?: string; /** Token used to access the next page of this result. No token is displayed if there are no more pages left. */ nextPageToken?: string; /** Total number of templates for the table. */ totalItems?: number; } interface ColumnResource { /** Deletes the specified column. */ delete(request: { /** Data format for the response. */ alt?: string; /** Name or identifier for the column being deleted. */ columnId: 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; /** * 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; /** Table from which the column is being deleted. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Retrieves a specific column by its ID. */ get(request: { /** Data format for the response. */ alt?: string; /** Name or identifier for the column that is being requested. */ columnId: 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; /** * 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; /** Table to which the column belongs. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Column>; /** Adds a new column to the table. */ 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; /** * 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; /** Table for which a new column is being added. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Column>; /** Retrieves a list of columns. */ 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 number of columns to return. Default is 5. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token specifying which result page to return. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Table whose columns are being listed. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<ColumnList>; /** Updates the name or type of an existing column. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** Name or identifier for the column that is being updated. */ columnId: 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; /** * 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; /** Table for which the column is being updated. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Column>; /** Updates the name or type of an existing column. */ update(request: { /** Data format for the response. */ alt?: string; /** Name or identifier for the column that is being updated. */ columnId: 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; /** * 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; /** Table for which the column is being updated. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Column>; } interface QueryResource { /** * Executes a Fusion Tables SQL statement, which can be any of * - SELECT * - INSERT * - UPDATE * - DELETE * - SHOW * - DESCRIBE * - CREATE statement. */ sql(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Whether column names are included in the first row. Default is true. */ hdrs?: boolean; /** 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; /** * 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; /** * A Fusion Tables SQL statement, which can be any of * - SELECT * - INSERT * - UPDATE * - DELETE * - SHOW * - DESCRIBE * - CREATE */ sql: string; /** Whether typed values are returned in the (JSON) response: numbers for numeric values and parsed geometries for KML values. Default is true. */ typed?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Sqlresponse>; /** * Executes a SQL statement which can be any of * - SELECT * - SHOW * - DESCRIBE */ sqlGet(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Whether column names are included (in the first row). Default is true. */ hdrs?: boolean; /** 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; /** * 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; /** * A SQL statement which can be any of * - SELECT * - SHOW * - DESCRIBE */ sql: string; /** Whether typed values are returned in the (JSON) response: numbers for numeric values and parsed geometries for KML values. Default is true. */ typed?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Sqlresponse>; } interface StyleResource { /** Deletes a style. */ 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; /** * 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; /** Identifier (within a table) for the style being deleted */ styleId: number; /** Table from which the style is being deleted */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets a specific style. */ 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; /** * 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; /** Identifier (integer) for a specific style in a table */ styleId: number; /** Table to which the requested style belongs */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<StyleSetting>; /** Adds a new style for the table. */ 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; /** * 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; /** Table for which a new style is being added */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<StyleSetting>; /** Retrieves a list of styles. */ 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 number of styles to return. Optional. Default is 5. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Table whose styles are being listed */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<StyleSettingList>; /** Updates an existing style. This method supports patch semantics. */ patch(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; /** * 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; /** Identifier (within a table) for the style being updated. */ styleId: number; /** Table whose style is being updated. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<StyleSetting>; /** Updates an existing style. */ update(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; /** * 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; /** Identifier (within a table) for the style being updated. */ styleId: number; /** Table whose style is being updated. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<StyleSetting>; } interface TableResource { /** Copies a table. */ copy(request: { /** Data format for the response. */ alt?: string; /** Whether to also copy tabs, styles, and templates. Default is false. */ copyPresentation?: boolean; /** 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; /** * 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; /** ID of the table that is being copied. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Table>; /** Deletes a table. */ 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; /** * 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; /** ID of the table to be deleted. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Retrieves a specific table by its ID. */ 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; /** * 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; /** Identifier for the table being requested. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Table>; /** Imports more rows into a table. */ importRows(request: { /** Data format for the response. */ alt?: string; /** The delimiter used to separate cell values. This can only consist of a single character. Default is ,. */ delimiter?: string; /** The encoding of the content. Default is UTF-8. Use auto-detect if you are unsure of the encoding. */ encoding?: string; /** * The index of the line up to which data will be imported. Default is to import the entire file. If endLine is negative, it is an offset from the end of * the file; the imported content will exclude the last endLine lines. */ endLine?: number; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * Whether the imported CSV must have the same number of values for each row. If false, rows with fewer values will be padded with empty values. Default * is true. */ isStrict?: boolean; /** 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; /** * 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 index of the first line from which to start importing, inclusive. Default is 0. */ startLine?: number; /** The table into which new rows are being imported. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Import>; /** Imports a new table. */ importTable(request: { /** Data format for the response. */ alt?: string; /** The delimiter used to separate cell values. This can only consist of a single character. Default is ,. */ delimiter?: string; /** The encoding of the content. Default is UTF-8. Use auto-detect if you are unsure of the encoding. */ encoding?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name to be assigned to the new table. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<Table>; /** Creates a new table. */ 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; /** * 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; }): Request<Table>; /** Retrieves a list of tables a user owns. */ 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 number of tables to return. Default is 5. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token specifying which result page to return. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<TableList>; /** * Updates an existing table. Unless explicitly requested, only the name, description, and attribution will be updated. This method supports patch * semantics. */ patch(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; /** * 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; /** Whether the view definition is also updated. The specified view definition replaces the existing one. Only a view can be updated with a new definition. */ replaceViewDefinition?: boolean; /** ID of the table that is being updated. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Table>; /** Replaces rows of an existing table. Current rows remain visible until all replacement rows are ready. */ replaceRows(request: { /** Data format for the response. */ alt?: string; /** The delimiter used to separate cell values. This can only consist of a single character. Default is ,. */ delimiter?: string; /** The encoding of the content. Default is UTF-8. Use 'auto-detect' if you are unsure of the encoding. */ encoding?: string; /** * The index of the line up to which data will be imported. Default is to import the entire file. If endLine is negative, it is an offset from the end of * the file; the imported content will exclude the last endLine lines. */ endLine?: number; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * Whether the imported CSV must have the same number of column values for each row. If true, throws an exception if the CSV does not have the same number * of columns. If false, rows with fewer column values will be padded with empty values. Default is true. */ isStrict?: boolean; /** 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; /** * 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 index of the first line from which to start importing, inclusive. Default is 0. */ startLine?: number; /** Table whose rows will be replaced. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Task>; /** Updates an existing table. Unless explicitly requested, only the name, description, and attribution will be updated. */ update(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; /** * 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; /** Whether the view definition is also updated. The specified view definition replaces the existing one. Only a view can be updated with a new definition. */ replaceViewDefinition?: boolean; /** ID of the table that is being updated. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Table>; } interface TaskResource { /** Deletes a specific task by its ID, unless that task has already started running. */ 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; /** * 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; /** Table from which the task is being deleted. */ tableId: string; /** The identifier of the task to delete. */ taskId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Retrieves a specific task by its ID. */ 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; /** * 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; /** Table to which the task belongs. */ tableId: string; /** The identifier of the task to get. */ taskId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Task>; /** Retrieves a list of tasks. */ 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 number of tasks to return. Default is 5. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token specifying which result page to return. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Index of the first result returned in the current page. */ startIndex?: number; /** Table whose tasks are being listed. */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<TaskList>; } interface TemplateResource { /** Deletes a template */ 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; /** * 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; /** Table from which the template is being deleted */ tableId: string; /** Identifier for the template which is being deleted */ templateId: number; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Retrieves a specific template by its id */ 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; /** * 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; /** Table to which the template belongs */ tableId: string; /** Identifier for the template that is being requested */ templateId: number; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Template>; /** Creates a new template for the table. */ 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; /** * 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; /** Table for which a new template is being created */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Template>; /** Retrieves a list of templates. */ 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 number of templates to return. Optional. Default is 5. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token specifying which results page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Identifier for the table whose templates are being requested */ tableId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<TemplateList>; /** Updates an existing template. This method supports patch semantics. */ patch(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; /** * 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; /** Table to which the updated template belongs */ tableId: string; /** Identifier for the template that is being updated */ templateId: number; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Template>; /** Updates an existing template */ update(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; /** * 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; /** Table to which the updated template belongs */ tableId: string; /** Identifier for the template that is being updated */ templateId: number; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Template>; } } }
the_stack
import {Subject} from "../Subject"; import {QueryRunner} from "../../query-runner/QueryRunner"; import {OrmUtils} from "../../util/OrmUtils"; import {NestedSetMultipleRootError} from "../../error/NestedSetMultipleRootError"; import {ObjectLiteral} from "../../common/ObjectLiteral"; import {EntityMetadata} from "../../metadata/EntityMetadata"; class NestedSetIds { left: number; right: number; } /** * Executes subject operations for nested set tree entities. */ export class NestedSetSubjectExecutor { // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- constructor(protected queryRunner: QueryRunner) { } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Executes operations when subject is being inserted. */ async insert(subject: Subject): Promise<void> { const escape = (alias: string) => this.queryRunner.connection.driver.escape(alias); const tableName = this.getTableName(subject.metadata.tablePath); const leftColumnName = escape(subject.metadata.nestedSetLeftColumn!.databaseName); const rightColumnName = escape(subject.metadata.nestedSetRightColumn!.databaseName); let parent = subject.metadata.treeParentRelation!.getEntityValue(subject.entity!); // if entity was attached via parent if (!parent && subject.parentSubject && subject.parentSubject.entity) // if entity was attached via children parent = subject.parentSubject.insertedValueSet ? subject.parentSubject.insertedValueSet : subject.parentSubject.entity; const parentId = subject.metadata.getEntityIdMap(parent); let parentNsRight: number|undefined = undefined; if (parentId) { parentNsRight = await this.queryRunner.manager .createQueryBuilder() .select(subject.metadata.targetName + "." + subject.metadata.nestedSetRightColumn!.propertyPath, "right") .from(subject.metadata.target, subject.metadata.targetName) .whereInIds(parentId) .getRawOne() .then(result => { const value: any = result ? result["right"] : undefined; // CockroachDB returns numeric types as string return typeof value === "string" ? parseInt(value) : value; }); } if (parentNsRight !== undefined) { await this.queryRunner.query(`UPDATE ${tableName} SET ` + `${leftColumnName} = CASE WHEN ${leftColumnName} > ${parentNsRight} THEN ${leftColumnName} + 2 ELSE ${leftColumnName} END,` + `${rightColumnName} = ${rightColumnName} + 2 ` + `WHERE ${rightColumnName} >= ${parentNsRight}`); OrmUtils.mergeDeep( subject.insertedValueSet, subject.metadata.nestedSetLeftColumn!.createValueMap(parentNsRight), subject.metadata.nestedSetRightColumn!.createValueMap(parentNsRight + 1), ); } else { const isUniqueRoot = await this.isUniqueRootEntity(subject, parent); // Validate if a root entity already exits and throw an exception if (!isUniqueRoot) throw new NestedSetMultipleRootError(); OrmUtils.mergeDeep( subject.insertedValueSet, subject.metadata.nestedSetLeftColumn!.createValueMap(1), subject.metadata.nestedSetRightColumn!.createValueMap(2), ); } } /** * Executes operations when subject is being updated. */ async update(subject: Subject): Promise<void> { let parent = subject.metadata.treeParentRelation!.getEntityValue(subject.entity!); // if entity was attached via parent if (!parent && subject.parentSubject && subject.parentSubject.entity) // if entity was attached via children parent = subject.parentSubject.entity; let entity = subject.databaseEntity; // if entity was attached via parent if (!entity && parent) // if entity was attached via children entity = subject.metadata.treeChildrenRelation!.getEntityValue(parent).find((child: any) => { return Object.entries(subject.identifier!).every(([key, value]) => child[key] === value); }); // Exit if the parent or the entity where never set if (entity === undefined || parent === undefined) { return; } const oldParent = subject.metadata.treeParentRelation!.getEntityValue(entity!); const oldParentId = subject.metadata.getEntityIdMap(oldParent); const parentId = subject.metadata.getEntityIdMap(parent); // Exit if the new and old parents are the same if (OrmUtils.compareIds(oldParentId, parentId)) { return; } if (parent) { const escape = (alias: string) => this.queryRunner.connection.driver.escape(alias); const tableName = this.getTableName(subject.metadata.tablePath); const leftColumnName = escape(subject.metadata.nestedSetLeftColumn!.databaseName); const rightColumnName = escape(subject.metadata.nestedSetRightColumn!.databaseName); const entityId = subject.metadata.getEntityIdMap(entity); let entityNs: NestedSetIds | undefined = undefined; if (entityId) { entityNs = (await this.getNestedSetIds(subject.metadata, entityId))[0]; } let parentNs: NestedSetIds | undefined = undefined; if (parentId) { parentNs = (await this.getNestedSetIds(subject.metadata, parentId))[0]; } if (entityNs !== undefined && parentNs !== undefined) { const isMovingUp = parentNs.left > entityNs.left; const treeSize = entityNs.right - entityNs.left + 1; let entitySize: number; if (isMovingUp) { entitySize = parentNs.left - entityNs.right; } else { entitySize = parentNs.right - entityNs.left; } // Moved entity logic const updateLeftSide = `WHEN ${leftColumnName} >= ${entityNs.left} AND ` + `${leftColumnName} < ${entityNs.right} ` + `THEN ${leftColumnName} + ${entitySize} `; const updateRightSide = `WHEN ${rightColumnName} > ${entityNs.left} AND ` + `${rightColumnName} <= ${entityNs.right} ` + `THEN ${rightColumnName} + ${entitySize} `; // Update the surrounding entities if (isMovingUp) { await this.queryRunner.query(`UPDATE ${tableName} ` + `SET ${leftColumnName} = CASE ` + `WHEN ${leftColumnName} > ${entityNs.right} AND ` + `${leftColumnName} <= ${parentNs.left} ` + `THEN ${leftColumnName} - ${treeSize} ` + updateLeftSide + `ELSE ${leftColumnName} ` + `END, ` + `${rightColumnName} = CASE ` + `WHEN ${rightColumnName} > ${entityNs.right} AND ` + `${rightColumnName} < ${parentNs.left} ` + `THEN ${rightColumnName} - ${treeSize} ` + updateRightSide + `ELSE ${rightColumnName} ` + `END`); } else { await this.queryRunner.query(`UPDATE ${tableName} ` + `SET ${leftColumnName} = CASE ` + `WHEN ${leftColumnName} < ${entityNs.left} AND ` + `${leftColumnName} > ${parentNs.right} ` + `THEN ${leftColumnName} + ${treeSize} ` + updateLeftSide + `ELSE ${leftColumnName} ` + `END, ` + `${rightColumnName} = CASE ` + `WHEN ${rightColumnName} < ${entityNs.left} AND ` + `${rightColumnName} >= ${parentNs.right} ` + `THEN ${rightColumnName} + ${treeSize} ` + updateRightSide + `ELSE ${rightColumnName} ` + `END`); } } } else { const isUniqueRoot = await this.isUniqueRootEntity(subject, parent); // Validate if a root entity already exits and throw an exception if (!isUniqueRoot) throw new NestedSetMultipleRootError(); } } /** * Executes operations when subject is being removed. */ async remove(subjects: Subject|Subject[]): Promise<void> { if (!Array.isArray(subjects)) subjects = [subjects]; const metadata = subjects[0].metadata; const escape = (alias: string) => this.queryRunner.connection.driver.escape(alias); const tableName = this.getTableName(metadata.tablePath); const leftColumnName = escape(metadata.nestedSetLeftColumn!.databaseName); const rightColumnName = escape(metadata.nestedSetRightColumn!.databaseName); let entitiesIds: ObjectLiteral[] = []; for (const subject of subjects) { const entityId = metadata.getEntityIdMap(subject.entity); if (entityId) { entitiesIds.push(entityId); } } let entitiesNs = await this.getNestedSetIds(metadata, entitiesIds); for (const entity of entitiesNs) { const treeSize = entity.right - entity.left + 1; await this.queryRunner.query(`UPDATE ${tableName} ` + `SET ${leftColumnName} = CASE ` + `WHEN ${leftColumnName} > ${entity.left} THEN ${leftColumnName} - ${treeSize} ` + `ELSE ${leftColumnName} ` + `END, ` + `${rightColumnName} = CASE ` + `WHEN ${rightColumnName} > ${entity.right} THEN ${rightColumnName} - ${treeSize} ` + `ELSE ${rightColumnName} ` + `END`); } } /** * Get the nested set ids for a given entity */ protected getNestedSetIds(metadata: EntityMetadata, ids: ObjectLiteral | ObjectLiteral[]): Promise<NestedSetIds[]> { const select = { left: `${metadata.targetName}.${metadata.nestedSetLeftColumn!.propertyPath}`, right: `${metadata.targetName}.${metadata.nestedSetRightColumn!.propertyPath}` }; const queryBuilder = this.queryRunner.manager.createQueryBuilder(); Object.entries(select).forEach(([key, value]) => { queryBuilder.addSelect(value, key); }); return queryBuilder .from(metadata.target, metadata.targetName) .whereInIds(ids) .orderBy(select.right, "DESC") .getRawMany() .then(results => { const data: NestedSetIds[] = []; for (const result of results) { const entry: any = {}; for (const key of Object.keys(select)) { const value = result ? result[key] : undefined; // CockroachDB returns numeric types as string entry[key] = typeof value === "string" ? parseInt(value) : value; } data.push(entry); } return data; }); } private async isUniqueRootEntity(subject: Subject, parent: any): Promise<boolean> { const escape = (alias: string) => this.queryRunner.connection.driver.escape(alias); const tableName = this.getTableName(subject.metadata.tablePath); const parameters: any[] = []; const whereCondition = subject.metadata.treeParentRelation!.joinColumns.map(column => { const columnName = escape(column.databaseName); const parameter = column.getEntityValue(parent); if (parameter == null) { return `${columnName} IS NULL`; } parameters.push(parameter); const parameterName = this.queryRunner.connection.driver.createParameter("entity_" + column.databaseName, parameters.length - 1); return `${columnName} = ${parameterName}`; }).join(" AND "); const countAlias = "count"; const result = await this.queryRunner.query( `SELECT COUNT(1) AS ${escape(countAlias)} FROM ${tableName} WHERE ${whereCondition}`, parameters, true ); return parseInt(result.records[0][countAlias]) === 0; } /** * Gets escaped table name with schema name if SqlServer or Postgres driver used with custom * schema name, otherwise returns escaped table name. */ protected getTableName(tablePath: string): string { return tablePath.split(".") .map(i => { // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string return i === "" ? i : this.queryRunner.connection.driver.escape(i); }).join("."); } }
the_stack
import HaikuBase from '../HaikuBase'; import {RFO} from '../reflection/functionToRFO'; export interface IHaikuElement extends HaikuBase { tagName: string|HaikuBytecode; node: BytecodeNode; parentNode?: BytecodeNode; target?: Element; originX: number; originY: number; size: ThreeDimensionalLayoutProperty; visit: ( iteratee: (component: IHaikuElement) => any, filter?: (value: IHaikuElement, index: number, array: IHaikuElement[]) => boolean, ) => any; getComponentId: () => string; getNearestDefinedNonZeroAncestorSizeX: () => number; getNearestDefinedNonZeroAncestorSizeY: () => number; isHovered: boolean; } export interface IHaikuClock { destroy (): void; getExplicitTime (): number; getFrameDuration (): number; getTime (): number; setTime (time: number): void; isRunning (): boolean; run (): void; start (): void; assignOptions (options: ClockConfig): void; GLOBAL_ANIMATION_HARNESS?: { cancel (): void; }; } export interface IHaikuComponent extends IHaikuElement { bytecode: HaikuBytecode; config: BytecodeOptions; patches: BytecodeNode[]; context: IHaikuContext; doPreserve3d: boolean; state: {[key in string]: any}; host?: IHaikuComponent; eachEventHandler: ( iteratee: (eventSelector: string, eventName: string, descriptor: BytecodeEventHandlerDescriptor) => void, ) => void; callHook: (hookName: string, ...args: any[]) => void; clearCaches: () => void; markForFullFlush: () => void; getClock: () => IHaikuClock; emitFromRootComponent: (eventName: string, attachedObject: any) => void; routeEventToHandlerAndEmit: (eventSelectorGiven: string, eventNameGiven: string, eventArgs: any) => void; routeEventToHandlerAndEmitWithoutBubbling: ( eventSelectorGiven: string, eventNameGiven: string, eventArgs: any, ) => void; getTimelineDescriptor: (timelineName: string) => BytecodeTimeline; lastHoveredElement: IHaikuElement; isDeactivated: boolean; routeEventToHandlerAndEmitWithoutBubblingAndWithoutGlobalHandlers: (...args: any[]) => void; } export interface MountLayout { layout?: { computed: { size: { x: number; y: number; }; }; }; } export interface IRenderer { mount?: Element; mountEventListener: (component: IHaikuComponent, selector: string, name: string, listener: Function) => void; } export interface IHaikuContext { // #FIXME: This is not necessarily going to be the renderer. renderer: IRenderer; config: BytecodeOptions; clock: IHaikuClock; getClock: () => IHaikuClock; getContainer: (doForceRecalc: boolean) => MountLayout; getGlobalUserState: () => any; contextMount: () => void; contextUnmount: () => void; tick: () => void; destroy: () => void; assignConfig: (config: BytecodeOptions, options?: {skipComponentAssign?: boolean}) => void; } export type PrimitiveType = string|number|object|boolean|null; /** * Allowed state types, including function return type for timeline functions, * state getter and setter. */ export type BytecodeStateType = PrimitiveType|PrimitiveType[]; /** * `BytecodeSummonable` defines functions that can be called on timeline * property value */ export interface BytecodeSummonable { (...params: any[]): BytecodeStateType; specification: RFO; } /** * All possible types for timeline property value */ export type BytecodeInjectable = BytecodeStateType|BytecodeSummonable; export type BytecodeNodeStyle = { [key in string]: PrimitiveType; }; export interface BytecodeNodeAttributes { [attribute: string]: any; style?: BytecodeNodeStyle; /** * @deprecated */ source?: string; identifier?: string; } export type PlaceholderSurrogate = any; export interface RepeaterSpec { changed: boolean; instructions: any[]; repeatees: BytecodeNode[]; } export interface RepeateeSpec { index: number; instructions: any[]; payload: any; source: BytecodeNode; } export interface IfSpec { answer: boolean; } export interface PlaceholderSpec { surrogate: PlaceholderSurrogate; } export interface BytecodeNodeMemoryObject { context?: IHaikuContext; element?: IHaikuElement; containee?: IHaikuComponent; children?: (string|BytecodeNode)[]; if?: IfSpec; instance?: IHaikuComponent; listener?: Function; // Bound event listener function parent?: BytecodeNode; placeholder?: PlaceholderSpec; repeatee?: RepeateeSpec; repeater?: RepeaterSpec; scope?: string; subcomponent?: IHaikuComponent; targets?: any[]; // DOM (or platform-specific) render targets } /** * Haiku bytecode element tree. eg. <div><svg>...</svg></div>. * `source` and `identifier` are rarely used. */ export interface BytecodeNode { elementName: string|HaikuBytecode; attributes: BytecodeNodeAttributes; isRootNode?: boolean; layout?: LayoutSpec; children?: (BytecodeNode|string)[]; __memory?: BytecodeNodeMemoryObject; /** * @deprecated */ rect?: DomRect; } export type MaybeBytecodeNode = BytecodeNode|null; /** * Haiku bytecode state. */ export interface BytecodeState { value: BytecodeStateType; type?: string; access?: string; edited?: boolean; mock?: boolean; getter?: () => BytecodeStateType; setter?: (param: BytecodeStateType) => void; } /** * Haiku bytecode state list. */ export interface BytecodeStates { [stateName: string]: BytecodeState; } /** * Haiku bytecode function `handler` for a specific `eventSelector`. */ export interface BytecodeEventHandlerCallable { (target?: any, event?: any): void; __rfo?: RFO; } export interface BytecodeEventHandlerDescriptor { handler: BytecodeEventHandlerCallable; } export interface BytecodeEventHandler { [eventSelector: string]: BytecodeEventHandlerDescriptor; } /** * Tuples of `elementName` and `BytecodeEventHandler`. */ export interface BytecodeEventHandlers { [elementName: string]: BytecodeEventHandler; } /** * Tuples of `elementName` and `BytecodeEventHandler`. */ export interface BytecodeHelpers { [helperName: string]: (...inputs: any[]) => any; } /** * Value of an element property in a given frame. */ export interface BytecodeTimelineValue { value: BytecodeInjectable; edited?: boolean; curve?: CurveDefinition; } /** * Map `frameNum` to a to a `BytecodeTimelineValue`. */ export interface BytecodeTimelineProperty { [frameNum: string]: BytecodeTimelineValue; } /** * Map `propertyName` to a `BytecodeTimelineProperty` */ export interface BytecodeTimelineProperties { [propertyName: string]: BytecodeTimelineProperty; } /** * Tuples of `haikuId` and `BytecodeTimelineProperties`. */ export interface BytecodeTimeline { [haikuId: string]: BytecodeTimelineProperties; } /** * Tuples of `timelineName` and `BytecodeTimeline`. */ export interface BytecodeTimelines { [timelineId: string]: BytecodeTimeline; } /** * Haiku bytecode metadata. */ export interface BytecodeMetadata { root?: string; folder?: string; uuid?: string; player?: string; type?: string; name?: string; relpath?: string; core?: string; version?: string; username?: string; organization?: string; project?: string; branch?: string; title?: string; /** * @deprecated as of 3.2.20 */ } export type ComponentEventHandler = (component: IHaikuComponent) => void; export interface ClockConfig { frameDuration?: number; frameDelay?: number; marginOfErrorForDelta?: number; run?: boolean; } /** * Bytecode options. */ export interface BytecodeOptions { // Random seed used for producing deterministic randomness // and namespacing CSS selector behavior seed?: string; // Timestamp reflecting the point in time that rendering begin, // for deterministic timestamp production timestamp?: number; // Whitelist of events that should fire during Edit Mode editModeEvents?: string[]; // Whether we should mount the given context to the mount // element automatically automount?: boolean; // Whether we should begin playing the context's animation automatically autoplay?: boolean; // If enabled (e.g. in the Haiku desktop app), bytecode is not cloned when a component is instantiated, and made be // live-edited. hotEditingMode?: boolean; // String used for asset resolution; normally enabled in Haiku desktop. folder?: string; // Whether to fully flush the component on every single frame // (warning: this can severely deoptimize animation) forceFlush?: boolean; // Whether we should freeze timelines and not update per global // timeline; useful in headless freeze?: boolean; // Whether we should loop the animation, i.e. restart from // the first frame after reaching the last loop?: boolean; // Optional function that we will call on every frame, provided // for developer convenience frame?: (() => void); hooks?: {[key: string]: Function}; helpers?: {[key: string]: Function}; // Configuration options that will be passed to the HaikuClock instance. // See HaikuClock.js for info. clock?: ClockConfig; // Configures the sizing mode of the component; may be 'normal', // 'stretch', 'contain', or 'cover'. See HaikuComponent.js for info. sizing?: string; // Whether we should always assume the size of the mount will change on every tick. There is a significant // performance boost for all non-'normal' sizing modes if we *don't* always assume this, but the size of the // mount might change underneath for reasons other than changes in media queries. To be safe, we leave this on // by default. alwaysComputeSizing?: boolean; // Placeholder for an option to control whether to enable // preserve-3d mode in DOM environments. [UNUSED] preserve3d?: string; // Whether or not the Haiku context menu should display when the // component is right-clicked; may be 'enabled' or 'disabled'. contextMenu?: string; // CSS position setting for the root of the component in DOM; // recommended to keep as 'relative'. position?: string; // CSS overflow-x setting for the component. Convenience for allows user // to specify the overflow setting without needing a wrapper element. overflowX?: string; // CSS overflow-x setting for the component. Convenience for allows user // to specify the overflow setting without needing a wrapper element. overflowY?: string; // CSS overflow setting for the component. Use this OR overflowX/overflowY overflow?: string; // If provided, a Mixpanel tracking instance will be created using this // string as the API token. The default token is Haiku's production token. mixpanel?: string|false; // Control how this instance handles interaction, e.g. preview mode // TODO: create an use an enum from @haiku/core/src/helpers/interactionModes.ts interactionMode?: number; // A unique ID used during migrations. referenceUniqueness?: string; // Allow states to be passed in at runtime (ASSIGNED) states?: object; // Allow custom event handlers to be passed in at runtime (ASSIGNED) eventHandlers?: object; // Allow timelines to be passed in at runtime (ASSIGNED) timelines?: object; // Allow vanities to be passed in at runtime (ASSIGNED) vanities?: object; // Children may be passed in, typically via the React adapter children?: PrimitiveType[]; // Key/values representing placeholders to inject, usually via React adapter placeholder?: object; // Event handlers. onHaikuComponentWillInitialize?: ComponentEventHandler; onHaikuComponentDidInitialize?: ComponentEventHandler; onHaikuComponentDidMount?: ComponentEventHandler; onHaikuComponentWillUnmount?: ComponentEventHandler; } /** * Bytecode definition. Properties are *rarely* used. */ export interface HaikuBytecode { template: BytecodeNode; states?: BytecodeStates; eventHandlers?: BytecodeEventHandlers; helpers?: BytecodeHelpers; timelines: BytecodeTimelines; metadata?: BytecodeMetadata; methods?: { [key in string]: Function; }; /** * @deprecated as of 3.2.20 */ properties?: any[]; options?: BytecodeOptions; } export type Mat4 = number[]; export interface ThreeDimensionalLayoutProperty { x: number; y: number; z: number; } export interface DomRect { width: number; height: number; left: number; top: number; } // The layout specification naming in createLayoutSpec is derived in part from: // https://github.com/Famous/engine/blob/master/core/Transform.js which is MIT licensed. export interface LayoutSpec { shown: boolean; opacity: number; offset: ThreeDimensionalLayoutProperty; origin: ThreeDimensionalLayoutProperty; translation: ThreeDimensionalLayoutProperty; rotation: ThreeDimensionalLayoutProperty; scale: ThreeDimensionalLayoutProperty; sizeMode: ThreeDimensionalLayoutProperty; sizeProportional: ThreeDimensionalLayoutProperty; sizeDifferential: ThreeDimensionalLayoutProperty; sizeAbsolute: ThreeDimensionalLayoutProperty; shear: { xy: number; xz: number; yz: number; }; matrix?: Mat4; format?: number; computed?: ComputedLayoutSpec; } export interface LayoutSpecPartial { shown?: boolean; opacity?: number; mount?: ThreeDimensionalLayoutProperty; offset?: ThreeDimensionalLayoutProperty; origin?: ThreeDimensionalLayoutProperty; translation?: ThreeDimensionalLayoutProperty; rotation?: ThreeDimensionalLayoutProperty; scale?: ThreeDimensionalLayoutProperty; sizeMode?: ThreeDimensionalLayoutProperty; sizeProportional?: ThreeDimensionalLayoutProperty; sizeDifferential?: ThreeDimensionalLayoutProperty; sizeAbsolute?: ThreeDimensionalLayoutProperty; shear?: { xy: number; xz: number; yz: number; }; computed: ComputedLayoutSpecPartial; } export interface ComputedLayoutSpec extends LayoutSpec { matrix: Mat4; size: ThreeDimensionalLayoutProperty; bounds: BoundsSpecPartial; } export interface ComputedLayoutSpecPartial { shown?: boolean; opacity?: number; mount?: ThreeDimensionalLayoutProperty; offset?: ThreeDimensionalLayoutProperty; origin?: ThreeDimensionalLayoutProperty; translation?: ThreeDimensionalLayoutProperty; rotation?: ThreeDimensionalLayoutProperty; scale?: ThreeDimensionalLayoutProperty; sizeMode?: ThreeDimensionalLayoutProperty; sizeProportional?: ThreeDimensionalLayoutProperty; sizeDifferential?: ThreeDimensionalLayoutProperty; sizeAbsolute?: ThreeDimensionalLayoutProperty; shear?: { xy: number; xz: number; yz: number; }; matrix: Mat4; size: ThreeDimensionalLayoutProperty; bounds: BoundsSpecPartial; } export interface StringableThreeDimensionalLayoutProperty { x: number|string; y: number|string; z: number|string; } export interface TwoPointFiveDimensionalLayoutProperty { x: number; y: number; z?: number; } export interface ClientRect { left: number; top: number; right: number; bottom: number; width: number; height: number; } export interface BoundsSpecX { left: number; right: number; } export interface BoundsSpecY { top: number; bottom: number; } export interface BoundsSpecZ { front: number; back: number; } export interface BoundsSpec extends BoundsSpecX, BoundsSpecY, BoundsSpecZ {} export interface BoundsSpecPartial { left?: number; right?: number; top?: number; bottom?: number; front?: number; back?: number; } export type AxisString = 'x'|'y'|'z'; export enum Curve { EaseInBack = 'easeInBack', EaseInCirc = 'easeInCirc', EaseInCubic = 'easeInCubic', EaseInExpo = 'easeInExpo', EaseInQuad = 'easeInQuad', EaseInQuart = 'easeInQuart', EaseInBounce = 'easeInBounce', EaseInElastic = 'easeInElastic', EaseInQuint = 'easeInQuint', EaseInSine = 'easeInSine', EaseOutBack = 'easeOutBack', EaseOutCirc = 'easeOutCirc', EaseOutCubic = 'easeOutCubic', EaseOutExpo = 'easeOutExpo', EaseOutQuad = 'easeOutQuad', EaseOutQuart = 'easeOutQuart', EaseOutBounce = 'easeOutBounce', EaseOutElastic = 'easeOutElastic', EaseOutQuint = 'easeOutQuint', EaseOutSine = 'easeOutSine', EaseInOutBack = 'easeInOutBack', EaseInOutCirc = 'easeInOutCirc', EaseInOutCubic = 'easeInOutCubic', EaseInOutExpo = 'easeInOutExpo', EaseInOutQuad = 'easeInOutQuad', EaseInOutQuart = 'easeInOutQuart', EaseInOutBounce = 'easeInOutBounce', EaseInOutElastic = 'easeInOutElastic', EaseInOutQuint = 'easeInOutQuint', EaseInOutSine = 'easeInOutSine', Linear = 'linear', } /** * Defines a normalized curve, to be used in BytecodeTimelineValue and also in * state transition */ export type CurveFunction = ((offset: number) => number); /** * Can be a function or a string from just-curves. The string is * converted into CuverFunction inside Interpolate */ export type CurveDefinition = Curve|CurveFunction|number[]; export interface ParsedValueCluster { parsee: { [ms: number]: { expression?: boolean; value: any; curve?: CurveDefinition; }; }; keys: number[]; } /** * Similar to BytecodeTimelines, but storing parsed value clusters instead of literal timelines. */ export interface ParsedValueClusterCollection { [timelineName: string]: { [selector: string]: { [propertyName: string]: ParsedValueCluster; }; }; }
the_stack
import React from 'react' import { Text, Box, StdinContext, Color } from 'ink' import { IStarter, SearchContext, IStarterDependency, searchStarters, searchDependencies, IStarterDependencyFacet, } from './algolia' import DependencyFacet from './components/DependencyFacet' import Footer from './components/Footer' import Overview from './components/Overview' import Starter from './components/Starter' import Scroll from './components/Scroll' import Search from './components/Search' import { WithStdin } from './utils' const ENTER = '\r' const CTRL_C = '\x03' type State = | { view: 'DEPENDENCIES_SEARCH' /* Facets search */ query: string facets: IStarterDependencyFacet[] loading: boolean /* User selection */ dependencies: IStarterDependency[] /* Preview */ starters: IStarter[] } | { view: 'STARTERS_SEARCH' /* Prior selection */ dependencies: IStarterDependency[] /* Starters search */ query: string page: number loading: boolean starters: IStarter[] } interface Props { onSelect: (starter: IStarter) => any } class Emma extends React.Component<WithStdin<Props>, State> { state: State = { view: 'DEPENDENCIES_SEARCH', query: '', facets: [], loading: false, dependencies: [], starters: [], } constructor(props: WithStdin<Props>) { super(props) this.handleQueryChange = this.handleQueryChange.bind(this) this.handleInput = this.handleInput.bind(this) this.handleWillReachEnd = this.handleWillReachEnd.bind(this) this.handleDependencyToggle = this.handleDependencyToggle.bind(this) } componentDidMount() { const { stdin, setRawMode } = this.props if (setRawMode) setRawMode(true) stdin.setMaxListeners(100) stdin.on('data', this.handleInput) } componentWillUnmount() { const { stdin, setRawMode } = this.props stdin.removeListener('data', this.handleInput) if (setRawMode) setRawMode(false) } /** * Keyboard events manager split based on the active view. */ async handleInput(data: any) { const s = String(data) /** * Create an exit listener. */ if (s === CTRL_C) { process.exit(0) } switch (this.state.view) { case 'DEPENDENCIES_SEARCH': { if (s === ENTER) { const { starters, dependencies } = this.state this.setState({ view: 'STARTERS_SEARCH', query: '', page: 0, loading: false, starters: starters, dependencies: dependencies, }) } return } } } /** * Whenever input changes, switch to the initial screen, change the value * of the query accordingly, reset pagination and perform search. */ async handleQueryChange(query: string) { switch (this.state.view) { case 'DEPENDENCIES_SEARCH': { this.setState({ view: 'DEPENDENCIES_SEARCH', query: query, loading: true, }) const [starters, facets] = await Promise.all([ searchStarters('', this.state.dependencies, 0, query), searchDependencies(query, this.state.dependencies), ]) if ( this.state.view === 'DEPENDENCIES_SEARCH' && starters.state === this.state.query ) { this.setState({ view: 'DEPENDENCIES_SEARCH', query: query, facets: facets, loading: false, dependencies: this.state.dependencies, starters: starters.hits, }) } return } case 'STARTERS_SEARCH': { this.setState({ view: 'STARTERS_SEARCH', query: query, page: 0, dependencies: this.state.dependencies, starters: this.state.starters, loading: true, }) const starters = await searchStarters(query, this.state.dependencies) if ( starters.query === this.state.query && this.state.view === 'STARTERS_SEARCH' ) { this.setState({ view: 'STARTERS_SEARCH', loading: false, starters: starters.hits, dependencies: this.state.dependencies, }) } } } } /** * Start querying new hits and update pagination. But limit pagniation to * ten pages. */ async handleWillReachEnd() { switch (this.state.view) { case 'STARTERS_SEARCH': { const { query, starters, dependencies, page } = this.state /* Memory leak. */ if (page > 10) return /* Perform search of the next page. */ const res = await searchStarters(query, dependencies, page + 1) if ( res.query === this.state.query && this.state.view === 'STARTERS_SEARCH' && res.page - 1 === this.state.page ) { this.setState({ view: 'STARTERS_SEARCH', page: res.page, starters: [...starters, ...res.hits], dependencies: [], query: query, loading: false, }) } } } } /** * Creates a new dependency if newly selected or toggles the existing one. */ async handleDependencyToggle({ value }: IStarterDependencyFacet) { switch (this.state.view) { case 'DEPENDENCIES_SEARCH': { const { dependencies } = this.state /* Search to see whether the dependency is already selected. */ const foundDependency = dependencies.find(({ name }) => name === value) /* Add/Remove dependency from the list. */ if (foundDependency === undefined) { this.setState({ view: 'DEPENDENCIES_SEARCH', dependencies: [...dependencies, { name: value }], }) } else { this.setState({ view: 'DEPENDENCIES_SEARCH', dependencies: dependencies.filter(({ name }) => name !== value), }) } /* Perform search. */ const [starters, facets] = await Promise.all([ searchStarters('', this.state.dependencies), searchDependencies('', this.state.dependencies), ]) if (this.state.view === 'DEPENDENCIES_SEARCH') { this.setState({ view: 'DEPENDENCIES_SEARCH', query: this.state.query, facets: facets, loading: false, dependencies: this.state.dependencies, starters: starters.hits, }) } } } } render() { switch (this.state.view) { case 'DEPENDENCIES_SEARCH': { const { query, loading, starters, facets, dependencies } = this.state return ( <SearchContext.Provider value={{ starters, facets }}> <Box flexDirection="column"> <Search heading={<Text underline>Search tools:</Text>} value={query} onChange={this.handleQueryChange} loading={loading} active /> <Overview dependencies={this.state.dependencies}></Overview> <Box flexDirection="column"> <Color cyan underline> Search: </Color> <Scroll placeholder="Packages will appear as you start searching!" values={this.state.facets} active > {dependency => ( <DependencyFacet key={`${query}-dependency-${dependency.value}`} dependency={dependency} onClick={this.handleDependencyToggle} selected={dependencies.some( d => d.name === dependency.value, )} active={dependency.active} /> )} </Scroll> </Box> <Box flexDirection="column"> <Text>Starters:</Text> <Scroll placeholder="" values={this.state.starters} active={false} > {starter => ( <Starter key={starter.objectID} starter={starter} active={false} /> )} </Scroll> </Box> <Footer /> </Box> </SearchContext.Provider> ) } case 'STARTERS_SEARCH': { const { query, loading, starters } = this.state return ( <SearchContext.Provider value={{ starters, facets: [] }}> <Box flexDirection="column"> <Overview dependencies={this.state.dependencies}></Overview> <Search heading={ <Color yellow underline> Search starters: </Color> } value={query} onChange={this.handleQueryChange} loading={loading} active /> <Scroll placeholder="We couldn't find anything. Try changing the search!" values={this.state.starters} onWillReachEnd={this.handleWillReachEnd} active > {starter => ( <Starter key={starter.objectID} starter={starter} onSubmit={this.props.onSelect} active={starter.active} /> )} </Scroll> <Footer /> </Box> </SearchContext.Provider> ) } } } } export default class EmmaWithStdin extends React.Component<Props, {}> { render() { return ( <StdinContext.Consumer> {({ stdin, setRawMode }) => ( <Emma {...this.props} stdin={stdin} setRawMode={setRawMode} /> )} </StdinContext.Consumer> ) } }
the_stack
import PropTypes from "prop-types"; import React, { FocusEvent, FormEvent } from "react"; import isEqual from "react-fast-compare"; type FieldValue = | boolean | number | Date | string | string[] | { value: string; files: string[] }; type Validator = (value: FieldValue) => string | Promise<string>; type Dictionary<T> = Record<string, T>; type Data = { values: Dictionary<FieldValue>; errors: Dictionary<string>; blurred: Dictionary<boolean>; touched: Dictionary<boolean>; dirty: Dictionary<boolean>; isValidating: boolean; isDirty: boolean; isValid: boolean; submitCount: number; }; type FormProps = { onBlur: (event: FocusEvent) => void; onChange: (event: FormEvent) => void; onChangeWithData: ( event: FormEvent, formState: any, form: HTMLFormElement ) => void; onData: (formState: Data, form: HTMLFormElement) => void; onFocus: (event: FocusEvent) => void; onReset: (event: FormEvent) => void; onResetWithData: ( event: FormEvent, formState: any, form: HTMLFormElement ) => void; onSubmit: (event: FormEvent) => void; onSubmitWithData: ( event: FormEvent, formState: any, form: HTMLFormElement ) => void; } & { domValidation: boolean; validateOnBlur: Dictionary<undefined | Validator>; validateOnChange: Dictionary<undefined | Validator>; }; class Form extends React.PureComponent<FormProps> { static defaultProps = { domValidation: false, onBlur: () => {}, onChange: () => {}, onChangeWithData: () => {}, onData: () => {}, onFocus: () => {}, onReset: () => {}, onResetWithData: () => {}, onSubmit: () => {}, onSubmitWithData: () => {}, validateOnBlur: {}, validateOnChange: {} }; static propTypes = { children: PropTypes.node.isRequired, domValidation: PropTypes.bool, onBlur: PropTypes.func, onChange: PropTypes.func, onChangeWithData: PropTypes.func, onData: PropTypes.func, onFocus: PropTypes.func, onReset: PropTypes.func, onResetWithData: PropTypes.func, onSubmit: PropTypes.func, onSubmitWithData: PropTypes.func, validateOnBlur: PropTypes.object, // eslint-disable-line validateOnChange: PropTypes.object // eslint-disable-line }; private form: HTMLFormElement = null; private defaultValues: Data["values"] = {}; private values: Data["values"] = {}; private errors: Data["errors"] = {}; private blurred: Data["blurred"] = {}; private touched: Data["touched"] = {}; private dirty: Data["dirty"] = {}; private isValidating: Data["isValidating"] = false; private isDirty: Data["isDirty"] = false; private isValid: Data["isValid"] = true; private submitCount: Data["submitCount"] = 0; componentDidMount() { const formState = this.getFormState(); this.defaultValues = formState.values; this.values = formState.values; this.props.onData(formState, this.form); } handleTextInput = (field: HTMLInputElement, validator?: Validator) => {}; handleFileInput = (field: HTMLInputElement, validator?: Validator) => { field.setCustomValidity(""); this.values[field.name] = { value: field.value, files: Array.from(field.files).map(file => file.name) }; if (validator) pact(validator(field.value)).then((message: string) => { field.setCustomValidity(message); }); }; handleRadioInput = (field: HTMLInputElement, validator?: Validator) => {}; handleCheckboxInput = (field: HTMLInputElement, validator?: Validator) => {}; handleSelectMultipe = (field: HTMLInputElement, validator?: Validator) => {}; handleUnknown = (field: HTMLInputElement, validateOnBlur?: Validator) => {}; getFormState = ({ resetting, submitting }: { resetting?: boolean; submitting?: boolean } = {}): Data => { // Iterate in reverse order so we can focus the first element with an error for (let i = this.form.elements.length - 1; i >= 0; i -= 1) { const element = this.form.elements[i]; // button's don't have values we can use if (element instanceof HTMLButtonElement) continue; // element's without name's cannot be stored if (!element.name) continue; // Piggy back off this for-loop when calling onReset if (resetting) { // Reset to a blank state element.setCustomValidity(""); // Set the value to the original value when the component was mounted if (this.values[element.name]) { /** @fixme this should be behind a guard for HTMLInputElement */ this.values[element.name] = (element as HTMLInputElement).defaultValue || ""; element.checkValidity(); // recheck the validity, order here is important } // If the input wasn't there when we rendered the component // we remove it from the values object if (!Object.prototype.hasOwnProperty.call(this.values, element.name)) { delete this.values[element.name]; } delete this.errors[element.name]; delete this.dirty[element.name]; delete this.touched[element.name]; delete this.blurred[element.name]; continue; } switch (element.type) { case "file": this.values[element.name] = { value: (element as HTMLInputElement).value, files: [].concat((element as HTMLInputElement).files) }; break; case "checkbox": if (!this.values[element.name]) { if ((element as HTMLInputElement).checked) { this.values[element.name] = (element as HTMLInputElement).value === "on" ? true : (element as HTMLInputElement).value; } else if ((element as HTMLInputElement).indeterminate) { this.values[element.name] = undefined; } else { this.values[element.name] = false; } } else { // Convert to an array of values since we're probably in a fieldset // (Or at least, the user has declared multiple checkboxes with the same name) if (!Array.isArray(this.values[element.name])) { this.values[element.name] = [].concat( this.values[element.name] as string[] ); } if ((element as HTMLInputElement).checked) { (this.values[element.name] as string[]).push( (element as HTMLInputElement).value ); } } break; case "radio": if ((element as HTMLInputElement).checked) { this.values[element.name] = (element as HTMLInputElement).value; } else if ((element as HTMLInputElement).indeterminate) { this.values[element.name] = undefined; } break; case "select-multiple": // Placeholders for select-multiple const elementOptions = (element as HTMLSelectElement).options; const elementValues = []; for (let j = 0; j < elementOptions.length; j += 1) { if (elementOptions[j].selected) { elementValues.push(elementOptions[j].value); } } this.values[element.name] = elementValues; if (element.validationMessage.length > 0) { this.errors[element.name] = element.validationMessage; } break; default: this.values[element.name] = (element as any).value; } // Override our value in case the user has supplied `data-valueasdate` or 'data-valueasnumber` attribute // Important, valueAsNumber should always override valueAsDate // see https://www.w3.org/TR/2011/WD-html5-20110405/common-input-element-attributes.html if ( element instanceof HTMLInputElement && element.hasAttribute("data-valueasdate") ) { if ("valueAsDate" in element) { this.values[element.name] = element.valueAsDate; } else { this.values[element.name] = new Date(element.value); } } if ( element instanceof HTMLInputElement && element.hasAttribute("data-valueasbool") ) { this.values[element.name] = (value => { /** @fixme I don't think it's possible to have a non-string value */ // Look for string values that if executed in eval would be falsey if (typeof value === "string") { const trimmed = value.trim(); if ( trimmed === "false" || trimmed === "" || trimmed === "0" || trimmed === "undefined" || trimmed === "null" ) { return false; } return true; } return !!value; })(element.value); } /** @fixme * @test @todo to ensure new elements don't sneak in * @see __tests__/compatibility/sneaky-field.js */ if ( element instanceof HTMLInputElement && element.hasAttribute("data-valueasnumber") ) { this.values[element.name] = element.valueAsNumber; } // Save the error message // Important error checking comes after setting the defaultValue above when resetting if (element.validationMessage.length > 0) { if (!this.props.domValidation && submitting) { element.focus(); } this.errors[element.name] = element.validationMessage; if (element.hasAttribute("data-errormessage")) { this.errors[element.name] = element.getAttribute("data-errormessage"); if (this.props.domValidation) { element.setCustomValidity(this.errors[element.name]); } } } // Perform any custom validation if (this.props.validateOnChange[element.name]) { const errorMessage = this.props.validateOnChange[element.name]( this.values[element.name] ); if (errorMessage instanceof Promise) { if (this.props.domValidation) { errorMessage.then(message => { element.setCustomValidity(message); this.errors[element.name] = message; }); } else if (submitting) { errorMessage.then(message => { element.focus(); this.errors[element.name] = message; }); } } else if (errorMessage) { if (this.props.domValidation) { element.setCustomValidity(errorMessage); } else if (submitting) { element.focus(); } this.errors[element.name] = errorMessage; } else { this.errors[element.name] = ""; element.setCustomValidity(""); } } } let isDirty; if (!this.values) { isDirty = false; // not dirty on first load } else { isDirty = resetting ? false : !isEqual(this.values, this.defaultValues); } return { values: this.values, errors: this.errors, blurred: this.blurred, dirty: this.dirty, touched: this.touched, isValidating: this.isValidating, isDirty, isValid: Object.keys(this.errors).length === 0 && this.errors.constructor === Object, submitCount: this.submitCount }; }; handleBlur = async (event: FocusEvent) => { const target = event.target as HTMLFormControl; if (!("name" in target)) return; this.props.onBlur(event); // Let the user know what’s been blurred if (target.name) { this.blurred[target.name] = true; this.props.onData(this.getFormState(), this.form); } if (this.props.validateOnBlur[target.name]) { this.isValidating = true; event.persist(); const errorMessage = this.props.validateOnBlur[target.name]( (target as HTMLInputElement).value ); if (errorMessage instanceof Promise) { this.props.onData(this.getFormState(), this.form); errorMessage.then(message => { target.setCustomValidity(message); this.errors[target.name] = message; this.isValidating = false; this.props.onData(this.getFormState(), this.form); }); } else if (errorMessage) { target.setCustomValidity(errorMessage); this.errors[target.name] = errorMessage; this.isValidating = false; this.props.onData(this.getFormState(), this.form); } else { target.setCustomValidity(""); this.isValidating = false; this.props.onData(this.getFormState(), this.form); } } }; handleChange = (event: FormEvent) => { const target = event.target as HTMLFormControl; if (!("name" in target)) return; const formState = this.getFormState(); this.dirty[target.name] = true; this.props.onChange(event); this.props.onData(formState, this.form); this.props.onChangeWithData(event, formState, this.form); }; handleFocus = (event: FocusEvent) => { const target = event.target as HTMLFormControl; if (!("name" in target)) return; this.touched[target.name] = true; this.props.onFocus(event); this.props.onData(this.getFormState(), this.form); }; handleReset = (event: FormEvent) => { // Wrap in setTimeout(0) to wait for internal .reset to finish setTimeout(() => { this.submitCount = 0; this.blurred = {}; this.dirty = {}; this.touched = {}; const formState = this.getFormState({ resetting: true }); this.props.onReset(event); this.props.onData(formState, this.form); this.props.onResetWithData(event, formState, this.form); }, 0); }; handleSubmit = (event: FormEvent) => { this.submitCount += 1; const formState = this.getFormState({ submitting: true }); this.props.onSubmit(event); this.props.onData(formState, this.form); if (typeof this.props.onSubmitWithData === "function") { event.preventDefault(); this.props.onSubmitWithData(event, formState, this.form); } }; render() { const { domValidation, onData, onChangeWithData, onResetWithData, onSubmitWithData, validateOnBlur, validateOnChange, ...rest } = this.props; return ( <form {...rest} noValidate={!this.props.domValidation} onBlur={this.handleBlur} onChange={this.handleChange} onFocus={this.handleFocus} onReset={this.handleReset} onSubmit={this.handleSubmit} ref={c => { this.form = c; }} > {this.props.children} </form> ); } } export default Form; export const defaultFormState = { values: {}, errors: {}, dirty: {}, touched: {}, blurred: {}, isDirty: false, isValid: false, isValidating: false, submitCount: 0 }; /** * @todo * handlers to be used on a per-input level * */ /** handles non-promises synchronously */ function pact<T>(promising: Promise<T> | T): any { if (promising instanceof Promise) return promising; else return { then: (cb: (t: T) => any) => cb(promising) }; } // */
the_stack
import { OrgFormationError } from '../org-formation-error'; import { ConsoleUtil } from '../util/console-util'; import { IStorageProvider, S3StorageProvider } from './storage-provider'; import { OrgResourceTypes } from '~parser/model'; export class PersistedState { public static async Load(provider: IStorageProvider, masterAccountId: string): Promise<PersistedState> { try { const contents = await provider.get(); let object = {} as IState; if (contents && contents.trim().length > 0) { object = JSON.parse(contents); } if (object.stacks === undefined) { object.stacks = {}; } if (object.bindings === undefined) { object.bindings = {}; } if (object.masterAccountId === undefined) { object.masterAccountId = masterAccountId; } /** * Obviously this needs to not be commented out, but since the partition master is different from the commercial, * it's the only way to run update-stacks in partition at the moment. */ // else if (object.masterAccountId !== masterAccountId) { // throw new OrgFormationError('state and session do not belong to the same organization'); // } return new PersistedState(object, provider); } catch (err) { if (err instanceof SyntaxError) { throw new OrgFormationError(`unable to parse state file ${err}`); } if (provider instanceof S3StorageProvider) { throw new OrgFormationError(`unable to load state, bucket: ${provider.bucketName}, key: ${provider.objectKey}. Err: ${err}`); } throw err; } } public static CreateEmpty(masterAccountId: string): PersistedState { const empty = new PersistedState({ masterAccountId, bindings: {}, stacks: {}, values: {}, previousTemplate: '', trackedTasks: {}, }); empty.dirty = true; return empty; } public readonly masterAccount: string; private provider?: IStorageProvider; private state: IState; private dirty = false; private organizationState: PersistedState; private readonly = false; private organizationLevelState = true; constructor(state: IState, provider?: IStorageProvider) { this.provider = provider; this.state = state; this.masterAccount = state.masterAccountId; this.organizationState = this; } public setReadonlyOrganizationState(organizationState: PersistedState): void { this.organizationState = organizationState; this.organizationState.readonly = true; this.organizationState.organizationLevelState = true; this.organizationLevelState = false; } public putTemplateHash(val: string): void { if (!this.organizationLevelState) { return; } this.putValue('organization.template.hash', val); } public getTemplateHash(): string { return this.organizationState.getValue('organization.template.hash'); } public putTemplateHashLastPublished(val: string): void { if (!this.organizationLevelState) { return; } this.organizationState.putValue('organization.template-last-published.hash', val); } public getTemplateHashLastPublished(): string { return this.organizationState.getValue('organization.template-last-published.hash'); } public putValue(key: string, val: string): void { if (this.readonly) { throw new OrgFormationError('attempt to modify to read-only organization level state'); } if (this.state.values === undefined) { this.state.values = {}; } this.state.values[key] = val; this.dirty = true; } public getValue(key: string): string | undefined { return this.state.values?.[key]; } public getTrackedTasks(tasksFileName: string): ITrackedTask[] { if (this.state.trackedTasks === undefined) { return []; } const trackedForTasksFile = this.state.trackedTasks[tasksFileName]; if (trackedForTasksFile === undefined) { return []; } return trackedForTasksFile; } public setTrackedTasks(tasksFileName: string, trackedTasks: ITrackedTask[]): void { if (this.state.trackedTasks === undefined) { this.state.trackedTasks = {}; } this.state.trackedTasks[tasksFileName] = trackedTasks; this.dirty = true; } public getGenericTarget<ITaskDefinition>(type: string, organizationLogicalName: string, logicalNamespace: string | undefined, logicalName: string, accountId: string, region?: string): IGenericTarget<ITaskDefinition> | undefined { if (!region) { region = 'no-region'; } if (logicalNamespace === undefined) { logicalNamespace = 'default'; } const targetsOfType = this.state.targets?.[type]; if (!targetsOfType) { return undefined; } const targetsWithOrganization = targetsOfType[organizationLogicalName]; if (!targetsWithOrganization) { return undefined; } const targetsWithNamespace = targetsWithOrganization[logicalNamespace]; if (!targetsWithNamespace) { return undefined; } const targetsWithName = targetsWithNamespace[logicalName]; if (!targetsWithName) { return undefined; } const targetsForAccount = targetsWithName[accountId]; if (!targetsForAccount) { return undefined; } return targetsForAccount[region] as IGenericTarget<ITaskDefinition>; } public setGenericTarget<ITaskDefinition>(target: IGenericTarget<ITaskDefinition>): void { const namespace = target.logicalNamePrefix ?? 'default'; if (this.state.targets === undefined) { this.state.targets = {}; } let targetsOfType = this.state.targets[target.targetType]; if (!targetsOfType) { targetsOfType = this.state.targets[target.targetType] = {}; } let targetsOfOrganization = targetsOfType[target.organizationLogicalName]; if (!targetsOfOrganization) { targetsOfOrganization = targetsOfType[target.organizationLogicalName] = {}; } let targetsWithNameSpace = targetsOfOrganization[namespace]; if (!targetsWithNameSpace) { targetsWithNameSpace = targetsOfOrganization[namespace] = {}; } let targetsWithName = targetsWithNameSpace[target.logicalName]; if (!targetsWithName) { targetsWithName = targetsWithNameSpace[target.logicalName] = {}; } let targetsForAccount = targetsWithName[target.accountId]; if (!targetsForAccount) { targetsForAccount = targetsWithName[target.accountId] = {}; } let region = target.region; if (!region) { region = 'no-region'; } targetsForAccount[region] = target; this.dirty = true; } public removeGenericTarget(type: string, organizationLogicalName: string, namespace = 'default', logicalName: string, accountId: string, region?: string): void { if (!region) { region = 'no-region'; } const root = this.state.targets; if (!root) { return; } const organizations = root[type]; if (!organizations) { return; } const namespaces = organizations[organizationLogicalName]; if (!namespaces) { return; } const names = namespaces[namespace]; if (!names) { return; } const accounts = names[logicalName]; if (!accounts) { return; } const regions: Record<string, any> = accounts[accountId]; if (!regions) { return; } delete regions[region]; this.dirty = true; if (Object.keys(regions).length === 0) { delete accounts[accountId]; if (Object.keys(accounts).length === 0) { delete names[logicalName]; if (Object.keys(names).length === 0) { delete namespaces[namespace]; if (Object.keys(namespaces).length === 0) { delete organizations[organizationLogicalName]; if (Object.keys(organizations).length === 0) { delete root[type]; } } } } } } public getTarget(stackName: string, accountId: string, region: string): ICfnTarget | undefined { const accounts = this.state.stacks?.[stackName]; if (!accounts) { return undefined; } const regions = accounts[accountId]; if (!regions) { return undefined; } return regions[region]; } public setTarget(templateTarget: ICfnTarget): void { if (this.state.stacks === undefined) { this.state.stacks = {}; } let accounts = this.state.stacks[templateTarget.stackName]; if (!accounts) { accounts = this.state.stacks[templateTarget.stackName] = {}; } let regions: Record<string, ICfnTarget> = accounts[templateTarget.accountId]; if (!regions) { regions = accounts[templateTarget.accountId] = {}; } regions[templateTarget.region] = templateTarget; this.dirty = true; } public listStacks(): string[] { return Object.entries(this.state.stacks).map(x => x[0]); } public enumTargets(stackName: string): ICfnTarget[] { const stacks = this.state.stacks; if (!stacks) { return []; } const result: ICfnTarget[] = []; for (const stack in stacks) { if (stack !== stackName) { continue; } const accounts = stacks[stack]; for (const account in accounts) { const regions = accounts[account]; for (const region in regions) { result.push(regions[region]); } } } return result; } public removeTarget(stackName: string, accountId: string, region: string): void { const accounts = this.state.stacks[stackName]; if (!accounts) { return; } const regions: Record<string, ICfnTarget> = accounts[accountId]; if (!regions) { return; } delete regions[region]; this.dirty = true; if (Object.keys(regions).length === 0) { delete accounts[accountId]; if (Object.keys(accounts).length === 0) { delete this.state.stacks[stackName]; } } } public getAccountBinding(logicalId: string): IBinding | undefined { if (this.organizationLevelState === false) { return this.organizationState.getAccountBinding(logicalId); } const typeDict = this.state.bindings?.[OrgResourceTypes.MasterAccount]; if (!typeDict) { return this.getBinding(OrgResourceTypes.Account, logicalId); } const result = typeDict[logicalId]; if (result === undefined) { return this.getBinding(OrgResourceTypes.Account, logicalId); } return result; } public getBinding(type: string, logicalId: string): IBinding | undefined { if (this.organizationLevelState === false) { return this.organizationState.getBinding(type, logicalId); } const typeDict = this.state.bindings?.[type]; if (!typeDict) { return undefined; } const result = typeDict[logicalId]; if (result === undefined) { ConsoleUtil.LogDebug(`unable to find binding for ${type}/${logicalId}`); } return result; } public enumBindings(type: string): IBinding[] { if (this.organizationLevelState === false) { return this.organizationState.enumBindings(type); } if (this.state.bindings === undefined) { return []; } const typeDict = this.state.bindings[type]; if (!typeDict) { return []; } const result: IBinding[] = []; for (const key in typeDict) { result.push(typeDict[key]); } return result; } getLogicalIdForPhysicalId(physicalId: string): string | undefined { if (this.organizationLevelState === false) { return this.organizationState.getLogicalIdForPhysicalId(physicalId); } if (this.masterAccount === physicalId) { const binding = this.enumBindings(OrgResourceTypes.MasterAccount); if (binding && binding.length > 0) { return binding[0].logicalId; } return 'master account'; } const bindings = this.enumBindings(OrgResourceTypes.Account); for (const binding of bindings) { if (binding.physicalId === physicalId) { return binding.logicalId; } } return undefined; } public enumGenericTargets<ITaskDefinition>(type: string, organizationName: string, namespace = 'default', name: string): IGenericTarget<ITaskDefinition>[] { if (this.organizationLevelState === false) { return this.organizationState.enumGenericTargets(type, organizationName, namespace, name); } if (this.state.targets === undefined) { return []; } const organizationDict = this.state.targets[type]; if (!organizationDict) { return []; } const namespaceDict = organizationDict[organizationName]; if (namespaceDict === undefined) { return []; } const nameDict = namespaceDict[namespace]; if (nameDict === undefined) { return []; } const accountDict = nameDict[name]; if (accountDict === undefined) { return []; } const result: IGenericTarget<ITaskDefinition>[] = []; for (const regionDict of Object.values(accountDict)) { for (const target of Object.values(regionDict)) { result.push(target as IGenericTarget<ITaskDefinition>); } } return result; } public setUniqueBindingForType(binding: IBinding): void { if (this.organizationLevelState === false) { this.organizationState.setUniqueBindingForType(binding); return; } if (this.readonly) { throw new OrgFormationError('attempt to modify to read-only organization level state'); } if (this.state.bindings === undefined) { this.state.bindings = {}; } let typeDict: Record<string, IBinding> = this.state.bindings[binding.type]; typeDict = this.state.bindings[binding.type] = {}; typeDict[binding.logicalId] = binding; this.dirty = true; } public setBinding(binding: IBinding): void { if (this.organizationLevelState === false) { this.organizationState.setBinding(binding); return; } if (this.readonly) { throw new OrgFormationError('attempt to modify to read-only organization level state'); } if (this.state.bindings === undefined) { this.state.bindings = {}; } let typeDict: Record<string, IBinding> = this.state.bindings[binding.type]; if (!typeDict) { typeDict = this.state.bindings[binding.type] = {}; } typeDict[binding.logicalId] = binding; this.dirty = true; } public setBindingHash(type: string, logicalId: string, lastCommittedHash: string): void { if (this.organizationLevelState === false) { this.organizationState.setBindingHash(type, logicalId, lastCommittedHash); return; } if (this.readonly) { throw new OrgFormationError('attempt to modify to read-only organization level state'); } if (this.state.bindings === undefined) { this.state.bindings = {}; } let typeDict: Record<string, IBinding> = this.state.bindings[type]; if (!typeDict) { typeDict = this.state.bindings[type] = {}; } const current = typeDict[logicalId]; if (current === undefined) { typeDict[logicalId] = { lastCommittedHash, logicalId, type } as IBinding; } else { current.lastCommittedHash = lastCommittedHash; } this.dirty = true; } public setBindingPhysicalId(type: string, logicalId: string, physicalId: string): void { if (this.organizationLevelState === false) { this.organizationState.setBindingHash(type, logicalId, physicalId); return; } if (this.readonly) { throw new OrgFormationError('attempt to modify to read-only organization level state'); } let typeDict: Record<string, IBinding> = this.state.bindings[type]; if (!typeDict) { typeDict = this.state.bindings[type] = {}; } const current = typeDict[logicalId]; if (current === undefined) { typeDict[logicalId] = { physicalId, logicalId, type } as IBinding; } else { current.physicalId = physicalId; } this.dirty = true; } public removeBinding(binding: IBinding): void { if (this.organizationLevelState === false) { this.organizationState.removeBinding(binding); return; } if (this.readonly) { throw new OrgFormationError('attempt to modify to read-only organization level state'); } let typeDict: Record<string, IBinding> = this.state.bindings[binding.type]; if (!typeDict) { typeDict = this.state.bindings[binding.type] = {}; } delete typeDict[binding.logicalId]; this.dirty = true; } public setPreviousTemplate(template: string): void { if (this.organizationLevelState === false) { this.organizationState.setPreviousTemplate(template); return; } if (this.readonly) { throw new OrgFormationError('attempt to modify to read-only organization level state'); } this.state.previousTemplate = template; this.dirty = true; } public getPreviousTemplate(): string { if (this.organizationLevelState === false) { return this.organizationState.getPreviousTemplate(); } return this.state.previousTemplate; } public async save(storageProvider: IStorageProvider | undefined = this.provider, isPartition: boolean | undefined = false): Promise<void> { if (!storageProvider) { return; } if (!this.dirty && !isPartition) { return; } const json = this.toJson(); await storageProvider.put(json); this.dirty = false; } performUpdateToVersion2IfNeeded(): void { if (this.organizationLevelState === false) { return; } const storedVersion = this.getValue('state-version'); if (storedVersion === undefined) { this.state.trackedTasks = {}; if (this.state.targets) { for (const root of Object.entries(this.state.targets)) { for (const logicalName of Object.entries(root[1])) { for (const account of Object.entries(logicalName[1])) { for (const region of Object.entries(account[1])) { if ((region[1] as any).lastCommittedHash) { delete root[1][logicalName[0]]; break; } break; } break; } } } } this.putValue('state-version', '2'); } } public toJson(): string { return JSON.stringify(this.state, null, 2); } } export interface IState { targets?: Record<string, Record<string, Record<string, Record<string, Record<string, Record<string, IGenericTarget<unknown>>>>>>>; masterAccountId: string; bindings: Record<string, Record<string, IBinding>>; stacks: Record<string, Record<string, Record<string, ICfnTarget>>>; values: Record<string, string>; trackedTasks: Record<string, ITrackedTask[]>; previousTemplate: string; } export interface IBinding { logicalId: string; type: string; physicalId: string; lastCommittedHash: string; partitionAccountId?: string; } export interface ICfnTarget { logicalAccountId: string; region: string; accountId: string; stackName: string; customRoleName?: string; customViaRoleArn?: string; cloudFormationRoleName?: string; terminationProtection?: boolean; lastCommittedHash: string; } export interface IGenericTarget<TTaskDefinition> { targetType: string; logicalAccountId: string; region: string; accountId: string; logicalName: string; organizationLogicalName: string; logicalNamePrefix?: string; lastCommittedHash: string; lastCommittedLocalHash?: string; definition: TTaskDefinition; } export interface ITrackedTask { logicalName: string; physicalIdForCleanup: string; concurrencyForCleanup?: number; type: string; }
the_stack
import React, { useCallback, useEffect, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import { CaretDownOutlined, FileOutlined, FileTextOutlined, FolderOpenOutlined, FolderOutlined, } from '@ant-design/icons'; import { Popover, Tag } from 'antd'; import styled from 'styled-components'; import { FileTypeEnum } from '@/constants/index'; import { BasicTemRing, Ring, VLine } from '@/pages/components'; import { PageContentType } from '@/types/builder'; import { PageParam } from '@/types/builder/page'; import formatter from '@/utils/version-formatter'; import { catalogIconStyle } from '../common/CommonStyles'; const MenuTitle = styled.a` display: flex; align-items: center; padding: 0 12px; color: #5b6b73; &:hover { color: #5b6b73; background: #f7f7f7; } `; const MenuTitleText = styled.span` display: inline-block; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; `; const Menu = styled.ul` width: 250px; max-height: 450px; overflow: auto; margin: 0; padding: 8px; list-style: none; background: #ffffff; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); `; const MenuItem = styled.li` position: relative; display: flex; justify-content: flex-start; align-items: center; padding: 8px 16px; cursor: pointer; border-bottom: 1px dashed #e8e8e8; user-select: none; color: #000000d8; &:last-of-type { border-bottom: none; } &:hover { background: #f7f7f7; } &.active { background: #f2f8ff; } &.disabled { color: #00000040 !important; background: 0 0; cursor: not-allowed; } &.no-select { &:hover { color: inherit; background: inherit; } } a { color: #000000d8; } `; const MenuItemSlot = styled.div` display: flex; justify-content: space-between; align-items: center; width: 100%; `; const ContentName = styled.div` display: inline-block; margin-right: 12px; padding-left: 18px; width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left; `; interface Type { root: string; contentList: PageContentType[]; locale: string; fileId: string; contentId: string; selectContent: (param: PageParam) => void; selectFoldStatus: (id: string, fold: boolean) => void; setLocale: (locale: string) => void; } const Catalog: React.FC<Type> = (props) => { const { root, contentList = [], locale, fileId: propsFileId, contentId, selectContent, selectFoldStatus, setLocale, } = props; const [folderOpen, setFolderOpen] = useState<boolean>(true); const [fileId, setFileId] = useState(''); const { applicationId, folderId, fileId: _fileId } = useParams<{ applicationId: string; folderId: string; fileId: string; }>(); useEffect(() => { const newFileId = propsFileId || _fileId; if (newFileId) setFileId(newFileId); }, [propsFileId]); // expand current file by default useEffect(() => { if (fileId) { selectFoldStatus(fileId, false); } else { // use first file when there is no file id in url search params const defaultFile = contentList.find((item) => item.contents && item.contents.length > 0); if (defaultFile) selectFoldStatus(defaultFile.id, false); } }, [fileId, selectFoldStatus]); const reSortList = useCallback((originList) => { const contentRecord: Record<string, PageContentType[]> = {}; const extendRecord: Record<string, string[]> = {}; const list: PageContentType[] = []; originList.forEach((item) => { if (item.isBase || !item.extendId) { list.push(item); } else { if (!contentRecord[item.extendId]) { contentRecord[item.extendId] = []; } contentRecord[item.extendId].push(item); if (!extendRecord[item.extendId]) { extendRecord[item.extendId] = []; } extendRecord[item.extendId].push(item.id); } }); Object.keys(contentRecord).forEach((key) => { const children = contentRecord[key]; if (children && children.length > 0) { const idx = list.findIndex((item) => item.id === key); list.splice(idx + 1, 0, ...children); } }); return list; }, []); // get current content detail const currentFile = (contentList && contentList.find((file) => file.id === fileId)) || contentList.find((item) => item.contents && item.contents.length > 0); const currentFileContents = currentFile && currentFile.contents; const currentContent = currentFileContents && currentFileContents.find((content) => content.id === contentId); const title = currentContent?.title || ''; const handleSecondFolderClick = (menu) => { const { id, contents, fold } = menu; if (id && contents && contents.length > 0) selectFoldStatus(id, !fold); }; const menu = ( <Menu> <MenuItem style={{ paddingLeft: 2 }} onClick={() => { setFolderOpen(!folderOpen); }}> <CaretDownOutlined rotate={folderOpen ? 0 : 270} style={catalogIconStyle} /> {folderOpen ? ( <FolderOpenOutlined style={catalogIconStyle} /> ) : ( <FolderOutlined style={catalogIconStyle} /> )} {root} </MenuItem> {folderOpen && contentList.map((item) => ( <React.Fragment key={item.id}> <MenuItem className={item.contents && item.contents.length > 0 ? '' : 'disabled'} onClick={() => handleSecondFolderClick(item)}> <CaretDownOutlined rotate={!item.fold ? 0 : 270} style={catalogIconStyle} /> {item.type === FileTypeEnum.page ? ( <FileTextOutlined style={catalogIconStyle} /> ) : ( <FileOutlined style={catalogIconStyle} /> )} {item.name} </MenuItem> {!item.fold && item.contents && item.contents.length > 0 && ( <> {reSortList(item.contents).map((subItem) => { const isSelected = contentId === subItem.id; const isBase = subItem.isBase && !!item.contents && item.contents.find((content) => content.extendId === subItem.id); const isInherited = !subItem.isBase && !!subItem.extendId; return ( <React.Fragment key={subItem.id}> <MenuItem className={isSelected ? 'active' : ''} style={{ paddingLeft: 34, paddingRight: 4 }} onClick={() => { if (!isSelected) { const localeTags = subItem.tags ? subItem.tags.filter((item) => item.locale) : []; selectContent({ applicationId, folderId, fileId: item.id, contentId: subItem.id, locale: localeTags.length > 0 ? localeTags[0].locale : '', fileType: item.type, }); } }}> <Link to={{ pathname: `/application/${applicationId}/folder/${folderId}/file/${item.id}/content/${subItem.id}/builder`, }}> <MenuItemSlot> {isBase && <BasicTemRing style={{ left: 34 }} />} {isInherited && ( <> <VLine style={{ left: 38 }} /> <Ring style={{ left: 36 }} /> </> )} <ContentName className={isSelected ? 'selected' : ''}> {subItem.title} </ContentName> {subItem.liveVersionNumber > 0 && ( <Tag color="orange" style={{ marginRight: 0 }}> {formatter(subItem.liveVersionNumber)} </Tag> )} </MenuItemSlot> </Link> </MenuItem> </React.Fragment> ); })} </> )} </React.Fragment> ))} </Menu> ); const localeMenu = ( <Menu style={{ width: 76, padding: 0 }}> {currentContent && currentContent.tags .filter((localeItem) => localeItem.locale) .map((item) => ( <MenuItem key={item.locale} onClick={() => setLocale(item.locale)}> {item.locale} </MenuItem> ))} </Menu> ); return ( <> <Popover zIndex={99} placement="bottomLeft" overlayClassName="foxpage-builder-header_popover" trigger={['hover']} content={menu} getPopupContainer={(triggerNode) => triggerNode.parentNode as HTMLElement}> <MenuTitle> <MenuTitleText>{title}</MenuTitleText> <CaretDownOutlined style={{ fontSize: 8, marginLeft: 4 }} /> </MenuTitle> </Popover> {locale && ( <Popover zIndex={99} placement="bottomLeft" overlayClassName="foxpage-builder-header_popover" trigger={['hover']} content={localeMenu} getPopupContainer={(triggerNode) => triggerNode.parentNode as HTMLElement}> <MenuTitle style={{ width: 76, display: 'flex', justifyContent: 'space-between' }}> <MenuTitleText>{locale}</MenuTitleText> <CaretDownOutlined style={{ fontSize: 8, marginLeft: 4 }} /> </MenuTitle> </Popover> )} </> ); }; export default Catalog;
the_stack
import React, { useEffect, useState, useRef, useLayoutEffect } from "react"; import "xterm/css/xterm.css"; import { Terminal as Xterm, IDisposable } from "xterm"; import { getBootstrapAESKey } from "./encryption"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { newBrowserConnected, requestTerminalDimensions } from "./events"; import { LandingPageContent } from "./LandingPageContent"; import { AesKeysRef, Status, TerminalServerData, TerminalSize } from "./types"; import { TopBar } from "./TopBar"; import { ErrorBoundary } from "./ErrorBoundary"; import { BottomBar } from "./BottomBar"; import { defaultTerminalId, defaultTermpairServer, secureContextHelp, xterm, } from "./constants"; import { toastStatus, websocketUrlFromHttpUrl } from "./utils"; import { getCustomKeyEventHandler, getOnDataHandler, redXtermText, } from "./xtermUtils"; import { handlers, TermPairEvent } from "./websocketMessageHandler"; function handleStatusChange( status: Status, prevStatus: Status, setPrevStatus: (prevStatus: Status) => void ): void { setPrevStatus(status); switch (status) { case null: break; case "Connection Established": toastStatus(status); xterm.writeln("Connection established with end-to-end encryption 🔒."); xterm.writeln( "The termpair server and third parties can't read transmitted data." ); xterm.writeln(""); xterm.writeln( "You can copy text with ctrl+shift+c or ctrl+shift+x, and paste with ctrl+shift+v." ); xterm.writeln(""); break; case "Disconnected": toastStatus(status); if (prevStatus === "Connection Established") { xterm.writeln(redXtermText("Terminal session has ended")); xterm.writeln(""); } break; case "Terminal ID is invalid": toast.dark( `An invalid Terminal ID was provided. ` + `Check that the session is still being broadcast and that the ID is entered correctly.` ); break; case "Failed to obtain encryption keys": toast.dark( `Failed to obtain secret encryption keys from the broadcasting terminal. ` + `Is your encryption key valid?` ); break; case "Browser is not running in a secure context": toast.dark(secureContextHelp); break; case "Connecting...": break; case "Connection Error": break; case "Failed to fetch terminal data": break; default: ((_: "Unhandled switch case"): never => { throw Error; })(status); } return status as never; } function ensureXtermIsOpen( xtermWasOpened: React.MutableRefObject<boolean>, xterm: Xterm ) { if (xtermWasOpened.current) { return; } const el = document.getElementById("terminal"); if (!el) { return; } xterm.open(el); xtermWasOpened.current = true; xterm.writeln(`Welcome to TermPair! https://github.com/cs01/termpair`); xterm.writeln(""); } function App() { const [isStaticallyHosted, setIsStaticallyHosted] = useState<Nullable<boolean>>(null); const [terminalServerData, setTerminalServerData] = useState<Nullable<TerminalServerData>>(null); const [numClients, setNumClients] = useState(0); const aesKeys = useRef<AesKeysRef>({ browser: null, unix: null, ivCount: null, maxIvCount: null, }); const xtermWasOpened = useRef(false); const [webSocket, setWebsocket] = useState<Nullable<WebSocket>>(null); const showTerminal = webSocket !== null; const [terminalSize, setTerminalSize] = useState<TerminalSize>({ rows: 20, cols: 81, }); const [status, setStatus] = useState<Status>(null); const [prevStatus, setPrevStatus] = useState<Status>(null); const [terminalId, setTerminalId] = useState(defaultTerminalId); useEffect(() => { if (!window.isSecureContext) { changeStatus("Browser is not running in a secure context"); return; } // run once when initially opened const initialize = async () => { let staticallyHosted; try { const ret = await fetch(defaultTermpairServer.toString() + "ping", { mode: "same-origin", }); const text = await ret.json(); const pong = text === "pong"; const isTermpairServer = ret.status === 200 && pong; staticallyHosted = !isTermpairServer; setIsStaticallyHosted(staticallyHosted); } catch (e) { staticallyHosted = true; setIsStaticallyHosted(staticallyHosted); } const bootstrapKey = await getBootstrapAESKey(); const termpairServerUrlParam = new URLSearchParams( window.location.search ).get("termpair_server_url"); const customTermpairServer = termpairServerUrlParam ? new URL(termpairServerUrlParam) : null; const termpairHttpServer = staticallyHosted ? customTermpairServer : defaultTermpairServer; if (terminalId && termpairHttpServer && bootstrapKey) { const termpairWebsocketServer = websocketUrlFromHttpUrl(termpairHttpServer); await connectToTerminalAndWebsocket( terminalId, termpairWebsocketServer, termpairHttpServer, bootstrapKey ); } }; initialize(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useLayoutEffect(() => { ensureXtermIsOpen(xtermWasOpened, xterm); }, [showTerminal]); const changeStatus = (newStatus: Status) => { setStatus(newStatus); handleStatusChange(newStatus, prevStatus, setPrevStatus); }; async function connectToTerminalAndWebsocket( terminalId: string, termpairWebsocketServer: URL, termpairHttpServer: URL, bootstrapAesKey: CryptoKey ) { setTerminalId(terminalId); setTerminalServerData(null); try { const response = await fetch( new URL(`terminal/${terminalId}`, termpairHttpServer).toString() ); if (response.status === 200) { const data: TerminalServerData = await response.json(); setTerminalServerData(data); setupWebsocket( terminalId, data, termpairWebsocketServer, bootstrapAesKey ); } else { changeStatus("Terminal ID is invalid"); } } catch (e) { changeStatus(`Failed to fetch terminal data`); toast.dark( `Error fetching terminal data from ${termpairHttpServer.toString()}. Is the URL correct? Error message: ${String( e.message )}`, { autoClose: false } ); } } function setupWebsocket( terminalId: string, terminalServerData: TerminalServerData, termpairWebsocketServer: URL, bootstrapAesKey: CryptoKey ) { if (webSocket) { toast.dark("Closing existing connection"); webSocket.close(); } changeStatus("Connecting..."); const connectWebsocketUrl = new URL( `connect_browser_to_terminal?terminal_id=${terminalId}`, termpairWebsocketServer ); const ws = new WebSocket(connectWebsocketUrl.toString()); setWebsocket(ws); const handleNewInput = getOnDataHandler(ws, terminalServerData, aesKeys); xterm.attachCustomKeyEventHandler( getCustomKeyEventHandler( xterm, terminalServerData?.allow_browser_control, handleNewInput ) ); let onDataDispose: Nullable<IDisposable>; ws.addEventListener("open", async (event) => { changeStatus("Connection Established"); ws.send(requestTerminalDimensions()); const newBrowserMessage = await newBrowserConnected(); ws.send(newBrowserMessage); onDataDispose = xterm.onData(handleNewInput); }); ws.addEventListener("close", (event) => { if (onDataDispose) { // stop trying to send data since the connection is closed onDataDispose.dispose(); } changeStatus("Disconnected"); setNumClients(0); }); ws.addEventListener("error", (event) => { if (onDataDispose) { // stop trying to send data since the connection is closed onDataDispose.dispose(); } console.error(event); toast.dark(`Websocket Connection Error: ${JSON.stringify(event)}`); changeStatus("Connection Error"); setNumClients(0); }); ws.addEventListener("message", async (message: { data: any }) => { let data: { event: TermPairEvent; [key: string]: any }; try { data = JSON.parse(message.data); } catch (e) { toast.dark("Failed to parse websocket message"); return; } switch (data.event) { case "new_output": return handlers.new_output(aesKeys, data); case "resize": return handlers.resize(data, setTerminalSize); case "num_clients": return handlers.num_clients(setNumClients, data); case "aes_keys": return handlers.aes_keys( aesKeys, bootstrapAesKey, data, changeStatus ); case "aes_key_rotation": return handlers.aes_key_rotation(aesKeys, data); case "error": return handlers.error(data); default: ((_: "Unhandled switch case"): never => { throw Error; })(data.event); return handlers.default(data); } }); } const content = ( <div className="p-5 text-white flex-grow w-auto m-auto"> {showTerminal ? ( <div id="terminal" className={`p-1 bg-gray-900 flex-grow text-gray-400 m-auto`} ></div> ) : ( <LandingPageContent isSecureContext={window.isSecureContext} isStaticallyHosted={isStaticallyHosted} connectToTerminalAndWebsocket={connectToTerminalAndWebsocket} /> )} </div> ); return ( <ErrorBoundary> <div className="flex flex-col h-screen align-middle max-w-full m-auto"> <ToastContainer position="bottom-right" limit={3} autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss={false} draggable pauseOnHover /> <TopBar /> {content} <BottomBar terminalData={terminalServerData} status={status} terminalId={terminalId} terminalSize={terminalSize} numClients={numClients} /> </div> </ErrorBoundary> ); } export default App;
the_stack
import { Schema, screenTrack, Track, track as _track } from "lib/utils/track" import React from "react" import { Alert } from "react-native" import { AsyncStorage, Dimensions, Route, ScrollView, View, ViewProperties } from "react-native" import NavigatorIOS from "react-native-navigator-ios" import { Box, Button, color, Flex, Serif, Spacer, Theme } from "@artsy/palette" import { ArtistResult, ConsignmentMetadata, ConsignmentSetup } from "../" import SwitchBoard from "../../../NativeModules/SwitchBoard" import TODO from "../Components/ArtworkConsignmentTodo" import { createConsignmentSubmission } from "../Submission/createConsignmentSubmission" import { updateConsignmentSubmission } from "../Submission/updateConsignmentSubmission" import { uploadImageAndPassToGemini } from "../Submission/uploadPhotoToGemini" import Confirmation from "./Confirmation" import Artist from "./ConsignmentsArtist" import Edition from "./Edition" import Location from "./Location" import Metadata from "./Metadata" import Provenance from "./Provenance" import SelectFromPhotoLibrary from "./SelectFromPhotoLibrary" const consignmentsStateKey = "ConsignmentsStoredState" interface Props extends ViewProperties { navigator: NavigatorIOS route: Route // this gets set by NavigatorIOS setup: ConsignmentSetup } interface State extends ConsignmentSetup { hasLoaded?: boolean /** Used at the end to keep track of the final submission to convection for the Confirmation page to see */ hasSubmittedSuccessfully?: boolean } const track: Track<Props, State> = _track @screenTrack({ context_screen: Schema.PageNames.ConsignmentsOverView, context_screen_owner_type: Schema.OwnerEntityTypes.Consignment, }) export default class Overview extends React.Component<Props, State> { constructor(props) { super(props) this.state = props.setup || {} // Grab stored details from the local storage if no // props have been passed in if (!props.setup) { this.restoreFromLocalStorage() } } saveStateToLocalStorage = () => AsyncStorage.setItem(consignmentsStateKey, JSON.stringify(this.state)) restoreFromLocalStorage = () => AsyncStorage.getItem(consignmentsStateKey, (_err, result) => { const results = (result && JSON.parse(result)) || {} this.setState({ ...results, hasLoaded: true }) }) goToArtistTapped = () => this.props.navigator.push({ component: Artist, passProps: { ...this.state, updateWithArtist: this.updateArtist }, }) goToProvenanceTapped = () => this.props.navigator.push({ component: Provenance, passProps: { ...this.state, updateWithProvenance: this.updateProvenance }, }) goToPhotosTapped = () => this.props.navigator.push({ component: SelectFromPhotoLibrary, passProps: { setup: this.state, updateWithPhotos: this.updatePhotos }, }) goToMetadataTapped = () => this.props.navigator.push({ component: Metadata, passProps: { metadata: this.state.metadata, updateWithMetadata: this.updateMetadata }, }) goToEditionTapped = () => this.props.navigator.push({ component: Edition, passProps: { setup: this.state, updateWithEdition: this.updateEdition }, }) goToLocationTapped = () => this.props.navigator.push({ component: Location, passProps: { updateWithResult: this.updateLocation } }) updateArtist = (result: ArtistResult) => this.updateStateAndMetaphysics({ artist: result }) updateMetadata = (result: ConsignmentMetadata) => this.updateStateAndMetaphysics({ metadata: result }) updateProvenance = (result: string) => this.updateStateAndMetaphysics({ provenance: result }) updateEdition = (result: ConsignmentSetup) => this.updateStateAndMetaphysics(result) updateLocation = (city: string, state: string, country: string) => this.updateStateAndMetaphysics({ location: { city, state, country } }) updatePhotos = (photos: string[]) => photos.length && this.updateStateAndMetaphysics({ photos: photos.map(f => ({ file: f, uploaded: false })) }) updateStateAndMetaphysics = (state: Partial<ConsignmentSetup>) => this.setState(state, this.updateLocalStateAndMetaphysics) updateLocalStateAndMetaphysics = async () => { this.saveStateToLocalStorage() if (this.state.submissionID) { try { await this.uploadPhotosIfNeeded() updateConsignmentSubmission(this.state) } catch (error) { this.showUploadFailureAlert(error) } } else if (this.state.artist) { const submissionID = await createConsignmentSubmission(this.state) this.setState({ submissionID }, () => { this.submissionDraftCreated() }) } } showUploadFailureAlert(error: Error) { Alert.alert("Sorry, we couldn't upload your images.", "Please try again or contact consign@artsy.net for help.", [ { text: "Cancel", style: "cancel", }, { text: "Retry", onPress: () => { this.updateLocalStateAndMetaphysics() }, }, ]) console.log("src/lib/Components/Consignments/Screens/Overview.tsx", error) } @track((_props, state) => ({ action_type: Schema.ActionTypes.Success, action_name: Schema.ActionNames.ConsignmentDraftCreated, owner_id: state.submissionID, owner_type: Schema.OwnerEntityTypes.Consignment, owner_slug: state.submissionID, })) submissionDraftCreated() { return null } submitFinalSubmission = async () => { this.showConfirmationScreen() const submission = this.state as ConsignmentSetup let hasSubmittedSuccessfully = true try { await updateConsignmentSubmission({ ...submission, state: "SUBMITTED" }) await AsyncStorage.removeItem(consignmentsStateKey) this.submissionDraftSubmitted() } catch (error) { console.error("Overview final submission: " + error) hasSubmittedSuccessfully = false } this.setState({ hasSubmittedSuccessfully }) } @track((_props, state) => ({ action_type: Schema.ActionTypes.Success, action_name: Schema.ActionNames.ConsignmentSubmitted, owner_id: state.submissionID, owner_type: Schema.OwnerEntityTypes.Consignment, owner_slug: state.submissionID, })) submissionDraftSubmitted() { return null } showConfirmationScreen() { // Confirmation will ask to see how the submission process has worked in 1 second const submissionRequestValidationCheck = () => this.state.hasSubmittedSuccessfully // Show confirmation screen this.props.navigator.push({ component: Confirmation, passProps: { submissionRequestValidationCheck } }) } exitModal = () => SwitchBoard.dismissModalViewController(this) uploadPhotosIfNeeded = async () => { const uploading = this.state.photos && this.state.photos.some(f => f.uploading) const toUpload = this.state.photos && this.state.photos.filter(f => !f.uploaded && f.file) if (!uploading && toUpload && toUpload.length) { // Pull out the first in the queue and upload it const photo = toUpload[0] try { // Set this one photo to upload, so that if you go in and out // quickly it doesn't upload duplicates photo.uploading = true this.setState({ photos: this.state.photos }) await uploadImageAndPassToGemini(photo.file, "private", this.state.submissionID) // Mutate state 'unexpectedly', then send it back through "setState" to trigger the next // in the queue photo.uploaded = true photo.uploading = false this.setState({ photos: this.state.photos }, this.uploadPhotosIfNeeded) } catch (e) { // Reset photos to enable upload retry, propogate exception upward photo.uploaded = false photo.uploading = false throw e } } } canSubmit = () => !!( this.state.artist && this.state.location && this.state.metadata && this.state.metadata.category && this.state.metadata.title && this.state.metadata.year && this.state.metadata.medium && this.state.metadata.height && this.state.metadata.width && this.state.editionScreenViewed ) render() { const title = "Complete work details to submit" const subtitle = "Provide as much detail as possible so that our partners can best assess your work." // See https://github.com/artsy/convection/blob/master/app/models/submission.rb for list const canSubmit = this.canSubmit() const isPad = Dimensions.get("window").width > 700 return ( <Theme> <ScrollView style={{ flex: 1 }} alwaysBounceVertical={false} centerContent> <View style={{ paddingTop: 10, alignSelf: "center", width: "100%", maxWidth: 540, flex: 1, }} > <Box px={2}> <Serif size="6" style={{ textAlign: isPad ? "center" : "left" }}> {title} </Serif> <Spacer mb={2} /> <Serif size="4" color={color("black60")} style={{ textAlign: isPad ? "center" : "left", marginBottom: isPad ? 80 : 0, marginTop: -15 }} > {subtitle} </Serif> </Box> <TODO goToArtist={this.goToArtistTapped} goToPhotos={this.goToPhotosTapped} goToEdition={this.goToEditionTapped} goToMetadata={this.goToMetadataTapped} goToLocation={this.goToLocationTapped} goToProvenance={this.goToProvenanceTapped} {...this.state} /> <Spacer mb={isPad ? 80 : 2} /> <Flex justifyContent="center" alignItems="center" flexDirection="column"> {this.state.hasLoaded && ( <Button onPress={canSubmit ? this.submitFinalSubmission : undefined} disabled={!canSubmit}> Submit </Button> )} <Spacer mb={1} /> <Button variant="noOutline" onPress={() => SwitchBoard.dismissModalViewController(this)}> Close </Button> </Flex> </View> </ScrollView> </Theme> ) } }
the_stack
import { ConditionalTransferTypes, CreatedHashLockTransferMeta, CreatedLinkedTransferMeta, CreatedSignedTransferMeta, DefaultApp, EventNames, HashLockTransferAppName, HashLockTransferAppState, IChannelProvider, ILoggerService, SimpleLinkedTransferAppName, SimpleLinkedTransferAppState, SimpleSignedTransferAppName, SimpleSignedTransferAppState, WithdrawAppName, WithdrawAppState, AppAction, AppState, SimpleSignedTransferAppAction, SimpleLinkedTransferAppAction, HashLockTransferAppAction, UnlockedLinkedTransferMeta, UnlockedHashLockTransferMeta, UnlockedSignedTransferMeta, EventPayload, EventPayloads, EventName, IBasicEventEmitter, ProtocolEventMessage, ProtocolParams, AppInstanceJson, GraphSignedTransferAppName, CreatedGraphBatchedTransferMeta, GraphSignedTransferAppState, GraphSignedTransferAppAction, UnlockedGraphBatchedTransferMeta, ConditionalTransferAppNames, GraphBatchedTransferAppName, CreatedGraphSignedTransferMeta, UnlockedGraphSignedTransferMeta, GraphBatchedTransferAppState, GraphBatchedTransferAppAction, WatcherEvents, WatcherEventData, WatcherEvent, } from "@connext/types"; import { bigNumberifyJson, stringify, TypedEmitter, toBN } from "@connext/utils"; import { constants } from "ethers"; import { ConnextClient } from "./connext"; const { HashZero } = constants; const { CONDITIONAL_TRANSFER_CREATED_EVENT, CONDITIONAL_TRANSFER_UNLOCKED_EVENT, CONDITIONAL_TRANSFER_FAILED_EVENT, WITHDRAWAL_CONFIRMED_EVENT, WITHDRAWAL_FAILED_EVENT, WITHDRAWAL_STARTED_EVENT, CREATE_CHANNEL_EVENT, SETUP_FAILED_EVENT, DEPOSIT_CONFIRMED_EVENT, DEPOSIT_FAILED_EVENT, DEPOSIT_STARTED_EVENT, INSTALL_EVENT, INSTALL_FAILED_EVENT, PROPOSE_INSTALL_EVENT, PROPOSE_INSTALL_FAILED_EVENT, PROTOCOL_MESSAGE_EVENT, REJECT_INSTALL_EVENT, SYNC, SYNC_FAILED_EVENT, UNINSTALL_EVENT, UNINSTALL_FAILED_EVENT, UPDATE_STATE_EVENT, UPDATE_STATE_FAILED_EVENT, } = EventNames; type ProtocolCallback = { [index in keyof typeof EventNames]: (data: ProtocolEventMessage<index>) => Promise<any> | void; }; type WatcherCallback = { [index in keyof typeof WatcherEvents]: (data: WatcherEventData[index]) => Promise<any> | void; }; type CallbackStruct = WatcherCallback | ProtocolCallback; export class ConnextListener { private log: ILoggerService; private typedEmitter: IBasicEventEmitter; private channelProvider: IChannelProvider; private connext: ConnextClient; // TODO: add custom parsing functions here to convert event data // to something more usable? -- OR JUST FIX THE EVENT DATA! :p private protocolCallbacks: CallbackStruct = { CREATE_CHANNEL_EVENT: (msg): void => { this.emitAndLog(CREATE_CHANNEL_EVENT, msg.data); }, SETUP_FAILED_EVENT: (msg): void => { this.emitAndLog(SETUP_FAILED_EVENT, msg.data); }, CONDITIONAL_TRANSFER_CREATED_EVENT: (msg): void => { this.emitAndLog(CONDITIONAL_TRANSFER_CREATED_EVENT, msg.data); }, CONDITIONAL_TRANSFER_UNLOCKED_EVENT: (msg): void => { this.emitAndLog(CONDITIONAL_TRANSFER_UNLOCKED_EVENT, msg.data); }, CONDITIONAL_TRANSFER_FAILED_EVENT: (msg: any): void => { this.emitAndLog(CONDITIONAL_TRANSFER_FAILED_EVENT, msg.data); }, DEPOSIT_CONFIRMED_EVENT: (msg): void => { this.emitAndLog(DEPOSIT_CONFIRMED_EVENT, msg.data); }, DEPOSIT_FAILED_EVENT: (msg): void => { this.emitAndLog(DEPOSIT_FAILED_EVENT, msg.data); }, DEPOSIT_STARTED_EVENT: (msg): void => { this.log.info(`Deposit started: ${msg.data.hash}`); this.emitAndLog(DEPOSIT_STARTED_EVENT, msg.data); }, INSTALL_EVENT: async (msg): Promise<void> => { this.emitAndLog(INSTALL_EVENT, msg.data); const { appIdentityHash, appInstance } = msg.data; const registryAppInfo = this.connext.appRegistry.find( (app: DefaultApp): boolean => app.appDefinitionAddress === appInstance.appDefinition, ); // install and run post-install tasks await this.runPostInstallTasks(appIdentityHash, registryAppInfo, appInstance, msg.from); this.log.info( `handleAppProposal for app ${registryAppInfo.name} ${appIdentityHash} completed`, ); await this.connext.node.messaging.publish( `${this.connext.publicIdentifier}.channel.${this.connext.multisigAddress}.app-instance.${appIdentityHash}.install`, stringify(appInstance), ); }, INSTALL_FAILED_EVENT: (msg): void => { this.emitAndLog(INSTALL_FAILED_EVENT, msg.data); }, PROPOSE_INSTALL_EVENT: async (msg): Promise<void> => { const { data: { params, appInstanceId }, from, } = msg; // return if its from us const start = Date.now(); const time = () => `in ${Date.now() - start} ms`; if (from === this.connext.publicIdentifier) { this.log.debug(`Received proposal from our own node, doing nothing ${time()}`); return; } this.log.info(`Processing proposal for ${appInstanceId}`); await this.handleAppProposal(params, appInstanceId); this.log.info(`Done processing propose install event ${time()}`); // validate and automatically install for the known and supported // applications this.emitAndLog(PROPOSE_INSTALL_EVENT, msg.data); }, PROPOSE_INSTALL_FAILED_EVENT: (msg): void => { this.emitAndLog(PROPOSE_INSTALL_FAILED_EVENT, msg.data); }, PROTOCOL_MESSAGE_EVENT: (msg): void => { this.emitAndLog(PROTOCOL_MESSAGE_EVENT, msg.data); }, REJECT_INSTALL_EVENT: (msg): void => { this.emitAndLog(REJECT_INSTALL_EVENT, msg.data); }, SYNC: (msg): void => { this.emitAndLog(SYNC, msg.data); }, SYNC_FAILED_EVENT: (msg): void => { this.emitAndLog(SYNC_FAILED_EVENT, msg.data); }, UNINSTALL_EVENT: async (msg): Promise<void> => { const { latestState } = msg.data.uninstalledApp; await this.handleAppUninstall( msg.data.appIdentityHash, latestState as AppState, msg.from, msg.data.action as AppAction, msg.data.uninstalledApp, msg.data.protocolMeta, ); this.emitAndLog(UNINSTALL_EVENT, msg.data); }, UNINSTALL_FAILED_EVENT: (msg): void => { this.emitAndLog(UNINSTALL_FAILED_EVENT, msg.data); }, UPDATE_STATE_EVENT: async (msg): Promise<void> => { await this.handleAppUpdate( msg.data.appIdentityHash, msg.data.newState as AppState, msg.data.action as AppAction, ); this.emitAndLog(UPDATE_STATE_EVENT, msg.data); }, UPDATE_STATE_FAILED_EVENT: (msg): void => { this.emitAndLog(UPDATE_STATE_FAILED_EVENT, msg.data); }, WITHDRAWAL_FAILED_EVENT: (msg): void => { this.emitAndLog(WITHDRAWAL_FAILED_EVENT, msg.data); }, WITHDRAWAL_CONFIRMED_EVENT: (msg): void => { this.emitAndLog(WITHDRAWAL_CONFIRMED_EVENT, msg.data); }, WITHDRAWAL_STARTED_EVENT: (msg): void => { this.emitAndLog(WITHDRAWAL_STARTED_EVENT, msg.data); }, // Watcher events CHALLENGE_UPDATED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_UPDATED_EVENT, msg); }, STATE_PROGRESSED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.STATE_PROGRESSED_EVENT, msg); }, CHALLENGE_PROGRESSED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_PROGRESSED_EVENT, msg); }, CHALLENGE_PROGRESSION_FAILED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_PROGRESSION_FAILED_EVENT, msg); }, CHALLENGE_OUTCOME_FAILED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_OUTCOME_FAILED_EVENT, msg); }, CHALLENGE_OUTCOME_SET_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_OUTCOME_SET_EVENT, msg); }, CHALLENGE_COMPLETED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_COMPLETED_EVENT, msg); }, CHALLENGE_COMPLETION_FAILED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_COMPLETION_FAILED_EVENT, msg); }, CHALLENGE_CANCELLED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_CANCELLED_EVENT, msg); }, CHALLENGE_CANCELLATION_FAILED_EVENT: (msg) => { this.emitAndLog(WatcherEvents.CHALLENGE_CANCELLATION_FAILED_EVENT, msg); }, }; constructor(connext: ConnextClient) { this.typedEmitter = new TypedEmitter(); this.channelProvider = connext.channelProvider; this.connext = connext; this.log = connext.log.newContext("ConnextListener"); } //////////////////////////////////////////////// ////// Emitter events public post<T extends EventName>(event: T, payload: EventPayload[T]): void { this.typedEmitter.post(event, payload); } public attachOnce<T extends EventName>( event: T, callback: (payload: EventPayload[T]) => void | Promise<void>, filter?: (payload: EventPayload[T]) => boolean, ): void { this.typedEmitter.attachOnce(event, callback, filter); } public attach<T extends EventName>( event: T, callback: (payload: EventPayload[T]) => void | Promise<void>, filter?: (payload: EventPayload[T]) => boolean, ): void { this.typedEmitter.attach(event, callback, filter); } public waitFor<T extends EventName>( event: T, timeout: number, filter?: (payload: EventPayload[T]) => boolean, ): Promise<EventPayload[T]> { return this.typedEmitter.waitFor(event, timeout, filter); } public detach(): void { this.typedEmitter.detach(); } public register = async (): Promise<void> => { this.detach(); this.log.debug(`Registering default listeners`); this.registerProtocolCallbacks(); this.registerLinkedTranferSubscription(); this.log.debug(`Registered default listeners`); return; }; private registerProtocolCallbacks = (): void => { Object.entries(this.protocolCallbacks).forEach(([event, callback]: any): any => { if (Object.keys(WatcherEvents).includes(event)) { this.connext.watcher.on(event, callback); } else { this.channelProvider.off(event); this.channelProvider.on(event, callback); } }); }; private emitAndLog<T extends EventName>(event: T, data: EventPayload[T]): void { const protocol = event === PROTOCOL_MESSAGE_EVENT ? (data as EventPayload[typeof PROTOCOL_MESSAGE_EVENT]).protocol : ""; this.log.debug(`Received ${event}${protocol ? ` for ${protocol} protocol` : ""}`); this.post(event, bigNumberifyJson(data)); } private emitAndLogWatcher<T extends WatcherEvent>(event: T, data: WatcherEventData[T]): void { this.post(event, bigNumberifyJson(data)); } private registerLinkedTranferSubscription = async (): Promise<void> => { this.attach(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, async (payload) => { this.log.info( `Received event CONDITIONAL_TRANSFER_CREATED_EVENT: ${stringify(payload, true, 0)}`, ); const start = Date.now(); const time = () => `in ${Date.now() - start} ms`; if (payload.type === ConditionalTransferTypes.LinkedTransfer) { if ( (payload as EventPayloads.LinkedTransferCreated).recipient !== this.connext.publicIdentifier ) { return; } try { const { paymentId, transferMeta: { encryptedPreImage }, amount, assetId, } = payload as EventPayloads.LinkedTransferCreated; if (!paymentId || !encryptedPreImage || !amount || !assetId) { throw new Error(`Unable to parse transfer details from message ${stringify(payload)}`); } this.log.info(`Unlocking transfer with paymentId: ${paymentId}`); await this.connext.reclaimPendingAsyncTransfer(paymentId, encryptedPreImage); this.log.info(`Successfully unlocked transfer with paymentId: ${paymentId}`); } catch (e) { this.log.error( `Error in event handler for CONDITIONAL_TRANSFER_CREATED_EVENT: ${e.message}`, ); } } this.log.info(`Finished processing CONDITIONAL_TRANSFER_CREATED_EVENT ${time()}`); }); }; private handleAppProposal = async ( params: ProtocolParams.Propose, appIdentityHash: string, ): Promise<void> => { // get supported apps const registryAppInfo = this.connext.appRegistry.find((app: DefaultApp): boolean => { return app.appDefinitionAddress === params.appDefinition; }); this.log.info( `handleAppProposal for app ${registryAppInfo.name} ${appIdentityHash} started: ${stringify( params, true, 0, )}`, ); if (!registryAppInfo) { throw new Error(`Could not find registry info for app ${params.appDefinition}`); } // install or reject app if (Object.values(ConditionalTransferAppNames).includes(registryAppInfo.name as any)) { return; } try { // NOTE: by trying to install here, if the installation fails, // the proposal is automatically removed from the store this.log.info(`Installing ${registryAppInfo.name} with id: ${appIdentityHash}`); await this.connext.installApp(appIdentityHash); this.log.info(`App ${appIdentityHash} installed`); } catch (e) { // TODO: first proposal after reset is responded to // twice if (e.message.includes("No proposed AppInstance exists")) { return; } else { this.log.error(`Caught error, rejecting install of ${appIdentityHash}: ${e.message}`); await this.connext.rejectInstallApp(appIdentityHash, e.message); return; } } }; private runPostInstallTasks = async ( appIdentityHash: string, registryAppInfo: DefaultApp, appInstance: AppInstanceJson, from: string, ): Promise<void> => { this.log.info(`runPostInstallTasks for app ${registryAppInfo.name} ${appIdentityHash} started`); switch (registryAppInfo.name) { case WithdrawAppName: { // withdraw actions only needed if we initiated the install on withdraw if (from !== this.connext.publicIdentifier) { break; } await this.connext.respondToNodeWithdraw(appInstance); break; } case GraphSignedTransferAppName: { const initialState = appInstance && bigNumberifyJson(appInstance.latestState as GraphSignedTransferAppState); const { initiatorDepositAssetId: assetId, meta } = appInstance || {}; const amount = initialState?.coinTransfers[0].amount; this.connext.emit(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, { amount, appIdentityHash, assetId, meta, sender: meta?.sender, transferMeta: { signerAddress: initialState?.signerAddress, chainId: initialState?.chainId, verifyingContract: initialState?.verifyingContract, requestCID: initialState?.requestCID, subgraphDeploymentID: initialState?.subgraphDeploymentID, } as CreatedGraphSignedTransferMeta, type: ConditionalTransferTypes.GraphTransfer, paymentId: initialState?.paymentId, recipient: meta?.recipient, } as EventPayloads.GraphTransferCreated); break; } case GraphBatchedTransferAppName: { const initialState = appInstance && bigNumberifyJson(appInstance.latestState as GraphSignedTransferAppState); const { initiatorDepositAssetId: assetId, meta } = appInstance || {}; const amount = initialState?.coinTransfers[0].amount; this.connext.emit(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, { amount, appIdentityHash, assetId, meta, sender: meta?.sender, transferMeta: { consumerSigner: initialState?.consumerSigner, attestationSigner: initialState?.attestationSigner, swapRate: initialState?.swapRate, chainId: initialState?.chainId, verifyingContract: initialState?.verifyingContract, requestCID: initialState?.requestCID, subgraphDeploymentID: initialState?.subgraphDeploymentID, } as CreatedGraphBatchedTransferMeta, type: ConditionalTransferTypes.GraphBatchedTransfer, paymentId: initialState?.paymentId, recipient: meta?.recipient, } as EventPayloads.GraphBatchedTransferCreated); break; } case SimpleSignedTransferAppName: { const initialState = appInstance && bigNumberifyJson(appInstance.latestState as SimpleSignedTransferAppState); const { initiatorDepositAssetId: assetId, meta } = appInstance || {}; const amount = initialState?.coinTransfers[0].amount; this.connext.emit(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, { amount, appIdentityHash, assetId, meta, sender: meta?.sender, transferMeta: { signerAddress: initialState?.signerAddress, chainId: initialState?.chainId, verifyingContract: initialState?.verifyingContract, } as CreatedSignedTransferMeta, type: ConditionalTransferTypes.SignedTransfer, paymentId: initialState?.paymentId, recipient: meta?.recipient, } as EventPayloads.SignedTransferCreated); break; } case HashLockTransferAppName: { const initialState = appInstance && bigNumberifyJson(appInstance.latestState as HashLockTransferAppState); const { initiatorDepositAssetId: assetId, meta } = appInstance || {}; const amount = initialState?.coinTransfers[0].amount; this.connext.emit(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, { amount, appIdentityHash, assetId, meta, sender: meta?.sender, transferMeta: { lockHash: initialState?.lockHash, expiry: initialState?.expiry, timelock: meta?.timelock, } as CreatedHashLockTransferMeta, type: ConditionalTransferTypes.HashLockTransfer, paymentId: meta?.paymentId, recipient: meta?.recipient, } as EventPayloads.HashLockTransferCreated); break; } case SimpleLinkedTransferAppName: { const initialState = appInstance && bigNumberifyJson(appInstance.latestState as SimpleLinkedTransferAppState); const { initiatorDepositAssetId: assetId, meta } = appInstance || {}; const amount = initialState?.coinTransfers[0].amount; this.log.info( `Emitting event CONDITIONAL_TRANSFER_CREATED_EVENT for paymentId ${meta?.paymentId}`, ); this.connext.emit(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, { amount, appIdentityHash, assetId, meta, sender: meta?.sender, transferMeta: { encryptedPreImage: meta?.encryptedPreImage, } as CreatedLinkedTransferMeta, type: ConditionalTransferTypes.LinkedTransfer, paymentId: meta?.paymentId, recipient: meta?.recipient, } as EventPayloads.LinkedTransferCreated); break; } } this.log.info( `runPostInstallTasks for app ${registryAppInfo.name} ${appIdentityHash} complete`, ); }; private handleAppUninstall = async ( appIdentityHash: string, state: AppState, from: string, action?: AppAction, appContext?: AppInstanceJson, protocolMeta?: any, ): Promise<void> => { const appInstance = appContext || ((await this.connext.getAppInstance(appIdentityHash)) || {}).appInstance; if (!appInstance) { this.log.info( `Could not find app instance, this likely means the app has been uninstalled, doing nothing`, ); return; } const registryAppInfo = this.connext.appRegistry.find((app: DefaultApp): boolean => { return app.appDefinitionAddress === appInstance.appDefinition; }); switch (registryAppInfo.name) { case WithdrawAppName: { if (from !== this.connext.publicIdentifier) { const withdrawState = state as WithdrawAppState; const params = { amount: withdrawState.transfers[0].amount, recipient: withdrawState.transfers[0].to, assetId: appInstance.outcomeInterpreterParameters["tokenAddress"], nonce: withdrawState.nonce, }; await this.connext.saveWithdrawCommitmentToStore( params, withdrawState.signatures, protocolMeta?.withdrawTx, ); } break; } case SimpleLinkedTransferAppName: { const transferState = state as SimpleLinkedTransferAppState; const transferAction = action as SimpleLinkedTransferAppAction; const transferAmount = toBN(transferState.coinTransfers[0].amount).isZero() ? toBN(transferState.coinTransfers[1].amount) : toBN(transferState.coinTransfers[0].amount); this.connext.emit(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, { type: ConditionalTransferTypes.LinkedTransfer, amount: transferAmount, assetId: appInstance.outcomeInterpreterParameters["tokenAddress"], paymentId: appInstance.meta.paymentId, sender: appInstance.meta.sender, recipient: appInstance.meta.recipient, meta: appInstance.meta, transferMeta: { preImage: transferAction?.preImage, } as UnlockedLinkedTransferMeta, } as EventPayloads.LinkedTransferUnlocked); break; } case HashLockTransferAppName: { const transferState = state as HashLockTransferAppState; const transferAction = action as HashLockTransferAppAction; const transferAmount = toBN(transferState.coinTransfers[0].amount).isZero() ? toBN(transferState.coinTransfers[1].amount) : toBN(transferState.coinTransfers[0].amount); this.connext.emit(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, { type: ConditionalTransferTypes.HashLockTransfer, amount: transferAmount, assetId: appInstance.outcomeInterpreterParameters["tokenAddress"], paymentId: HashZero, sender: appInstance.meta.sender, recipient: appInstance.meta.recipient, meta: appInstance.meta, transferMeta: { preImage: transferAction?.preImage, lockHash: transferState.lockHash, } as UnlockedHashLockTransferMeta, } as EventPayloads.HashLockTransferUnlocked); break; } case GraphBatchedTransferAppName: { const transferState = state as GraphBatchedTransferAppState; const transferAction = action as GraphBatchedTransferAppAction; // use total amount for transfer amount const transferAmount = toBN(transferState.coinTransfers[0].amount).add( toBN(transferState.coinTransfers[1].amount), ); this.connext.emit(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, { type: ConditionalTransferTypes.GraphBatchedTransfer, amount: transferAmount, assetId: appInstance.outcomeInterpreterParameters["tokenAddress"], paymentId: transferState.paymentId, sender: appInstance.meta.sender, recipient: appInstance.meta.recipient, meta: appInstance.meta, transferMeta: { consumerSignature: transferAction?.consumerSignature, attestationSignature: transferAction?.attestationSignature, responseCID: transferAction?.responseCID, requestCID: transferAction?.requestCID, totalPaid: transferAction?.totalPaid, } as UnlockedGraphBatchedTransferMeta, } as EventPayloads.GraphBatchedTransferUnlocked); break; } case GraphSignedTransferAppName: { const transferState = state as GraphSignedTransferAppState; const transferAction = action as GraphSignedTransferAppAction; const transferAmount = toBN(transferState.coinTransfers[0].amount).isZero() ? toBN(transferState.coinTransfers[1].amount) : toBN(transferState.coinTransfers[0].amount); this.connext.emit(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, { type: ConditionalTransferTypes.GraphTransfer, amount: transferAmount, assetId: appInstance.outcomeInterpreterParameters["tokenAddress"], paymentId: transferState.paymentId, sender: appInstance.meta.sender, recipient: appInstance.meta.recipient, meta: appInstance.meta, transferMeta: { signature: transferAction?.signature, responseCID: transferAction?.responseCID, } as UnlockedGraphSignedTransferMeta, } as EventPayloads.GraphTransferUnlocked); break; } case SimpleSignedTransferAppName: { const transferState = state as SimpleSignedTransferAppState; const transferAction = action as SimpleSignedTransferAppAction; const transferAmount = toBN(transferState.coinTransfers[0].amount).isZero() ? toBN(transferState.coinTransfers[1].amount) : toBN(transferState.coinTransfers[0].amount); this.connext.emit(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, { type: ConditionalTransferTypes.SignedTransfer, amount: transferAmount, assetId: appInstance.outcomeInterpreterParameters["tokenAddress"], paymentId: transferState.paymentId, sender: appInstance.meta.sender, recipient: appInstance.meta.recipient, meta: appInstance.meta, transferMeta: { signature: transferAction?.signature, data: transferAction?.data, } as UnlockedSignedTransferMeta, } as EventPayloads.SignedTransferUnlocked); break; } default: { this.log.info( `Received update state event for ${registryAppInfo.name}, not doing anything`, ); } } }; private handleAppUpdate = async ( appIdentityHash: string, state: AppState, action: AppAction, ): Promise<void> => { const { appInstance } = (await this.connext.getAppInstance(appIdentityHash)) || {}; if (!appInstance) { this.log.info( `Could not find app instance, this likely means the app has been uninstalled, doing nothing`, ); return; } const registryAppInfo = this.connext.appRegistry.find((app: DefaultApp): boolean => { return app.appDefinitionAddress === appInstance.appDefinition; }); switch (registryAppInfo.name) { case WithdrawAppName: { const withdrawState = state as WithdrawAppState; const params = { amount: withdrawState.transfers[0].amount, recipient: withdrawState.transfers[0].to, assetId: appInstance.outcomeInterpreterParameters["tokenAddress"], nonce: withdrawState.nonce, }; await this.connext.saveWithdrawCommitmentToStore(params, withdrawState.signatures); break; } default: { this.log.info( `Received update state event for ${registryAppInfo.name}, not doing anything`, ); } } }; }
the_stack
import { Camera2D, CompositeOperation, E, PlainMatrix, PointDownEvent, PointSource, Scene, MessageEvent, PlatformPointType, PointUpEvent, PointMoveEvent } from ".."; import { customMatchers, EntityStateFlags, Game, Renderer, Runtime, skeletonRuntime } from "./helpers"; expect.extend(customMatchers); describe("test E", () => { let runtime: Runtime, e: E; function resetUpdated(runtime: Runtime): void { runtime.game._modified = false; e.state &= ~EntityStateFlags.Modified; } beforeEach(() => { runtime = skeletonRuntime(); e = new E({ scene: runtime.scene }); runtime.scene.append(e); }); it("初期化", () => { let e = new E({ scene: runtime.scene }); expect(e.children).toBeUndefined(); expect(e.parent).toBeUndefined(); expect(e.touchable).toEqual(false); expect(e.local).toBe(false); expect(e.scene).toBe(runtime.scene); expect(e.state).toBe(EntityStateFlags.None); expect(e._hasTouchableChildren).toBe(false); expect(e.x).toBe(0); expect(e.y).toBe(0); expect(e.width).toBe(0); expect(e.height).toBe(0); expect(e.opacity).toBe(1); expect(e.scaleX).toBe(1); expect(e.scaleY).toBe(1); let c1 = new E({ scene: runtime.scene, x: 10, y: 10, local: true }); let c2 = new E({ scene: runtime.scene, x: 0, y: 0, local: true }); e = new E({ scene: runtime.scene, local: true, children: [c1, c2], touchable: true, hidden: true, x: 10, y: 20, width: 5, height: 4, opacity: 0.5, scaleX: 2, scaleY: 3 }); expect(e.parent).toBeUndefined(); expect(e.children!.length).toBe(2); expect(e.children![0]).toBe(c1); expect(e.children![1]).toBe(c2); expect(e.touchable).toBe(true); expect(e.local).toBe(true); expect(e.scene).toBe(runtime.scene); expect(e.state).toBe(EntityStateFlags.Modified | EntityStateFlags.Hidden); expect(e._hasTouchableChildren).toBe(false); expect(e.id in runtime.game.db).toBe(false); expect(e.id in runtime.game._localDb).toBe(true); expect(e.x).toBe(10); expect(e.y).toBe(20); expect(e.width).toBe(5); expect(e.height).toBe(4); expect(e.opacity).toBe(0.5); expect(e.scaleX).toBe(2); expect(e.scaleY).toBe(3); // parameter object で初期化してもコンストラクタ内で modified() していないが、問題なく動作することを確認しておく const mat = new PlainMatrix(); mat.update(5, 4, 2, 3, 0, 10, 20, 0, 0); expect(e.getMatrix()._matrix).toEqual(mat._matrix); e = new E({ id: 400, scene: runtime.scene, touchable: true, x: 100, y: 10 }); expect(e.id).toBe(400); expect(runtime.game.db[e.id]).toBe(e); expect(e.scene).toBe(runtime.scene); expect(e.x).toBe(100); expect(e.y).toBe(10); expect(e.touchable).toBe(true); // 重複IDはエラー expect(() => { return new E({ id: 400, scene: runtime.scene }); }).toThrowError("AssertionError"); // localは負のID expect(() => { return new E({ id: 500, scene: runtime.scene, local: true }); }).toThrowError("AssertionError"); expect(runtime.game._idx).toBe(400); // コンストラクタでのparent, tag指定チェック const p = new E({ scene: runtime.scene }); c1 = new E({ scene: runtime.scene, parent: p }); c2 = new E({ scene: runtime.scene, parent: p, tag: "tagged" }); expect(c1.parent).toBe(p); expect(c2.parent).toBe(p); expect(p.children![0]).toBe(c1); expect(p.children![1]).toBe(c2); expect(c2.tag).toBe("tagged"); }); it("findPointSourceByPoint", () => { const e2 = new E({ scene: runtime.scene }); e2.width = 100; e2.height = 100; runtime.scene.append(e2); e2.modified(); const point = { x: e2.width / 2, y: e2.height / 2 }; expect(runtime.scene.findPointSourceByPoint(point)).toEqual({ target: undefined, point: undefined, local: false }); expect(runtime.scene.findPointSourceByPoint(point, true)).toEqual({ target: e2, point: point, local: false }); const e3 = new E({ scene: runtime.scene }); e3.x = e3.y = 10; e3.width = 100; e3.height = 100; e2.append(e3); e3.modified(); const pointForE3 = { x: point.x - e3.x, y: point.y - e3.y }; expect(runtime.scene.findPointSourceByPoint(point)).toEqual({ target: undefined, point: undefined, local: false }); expect(runtime.scene.findPointSourceByPoint(point, true)).toEqual({ target: e3, point: pointForE3, local: false }); e2.touchable = true; e2.local = true; expect(runtime.scene.findPointSourceByPoint(point)).toEqual({ target: e2, point: point, local: true }); expect(runtime.scene.findPointSourceByPoint(point, true)).toEqual({ target: e3, point: pointForE3, local: false }); point.x = e2.width + 1; point.y = e2.height + 1; expect(runtime.scene.findPointSourceByPoint(point)).toEqual({ target: undefined, point: undefined, local: false }); }); it("show", () => { const e2 = new E({ scene: runtime.scene }); e2.show(); expect(e2.state).toEqual(0); // modified変更なし }); it("hide", () => { const e2 = new E({ scene: runtime.scene }); e2.hide(); expect(e2.state).toEqual(EntityStateFlags.Hidden); }); it("テスト内の便利関数テスト", () => { expect(runtime.game).not.toBeFalsy(); expect(runtime.scene).not.toBeFalsy(); expect(runtime.scene.children).not.toBeFalsy(); expect(runtime.scene.children.length).toBe(1); expect(runtime.scene.children[0]).toEqual(e); const runtime2 = skeletonRuntime(); expect(runtime2.game).not.toBeFalsy(); expect(runtime2.scene).not.toBeFalsy(); expect(runtime2.scene.children).not.toBeFalsy(); expect(runtime2.scene.children.length).toBe(0); }); it("scene", () => { const game = new Game({ width: 320, height: 320, main: "", assets: {} }); const scene = new Scene({ game: game }); const e2 = new E({ scene: scene }); expect(e.game() === runtime.game).toBe(true); expect(e2.game() === game).toBe(true); }); it("game", () => { expect(e.game()).toEqual(runtime.game); }); it("append", () => { const e2 = new E({ scene: runtime.scene }); e.append(e2); expect(e.parent).toEqual(runtime.scene); expect(e2.parent).toEqual(e); }); it("insertBefore", () => { const e2 = new E({ scene: runtime.scene }); const e3 = new E({ scene: runtime.scene }); const e4 = new E({ scene: runtime.scene }); const e5 = new E({ scene: runtime.scene }); e.append(e2); e.insertBefore(e3, e2); expect(e.children![0]).toBe(e3); expect(e.children![1]).toBe(e2); e.insertBefore(e4, e5); expect(e.children![2]).toBe(e4); const e6 = new E({ scene: runtime.scene }); const e7 = new E({ scene: runtime.scene }); e6.insertBefore(e7, undefined); expect(e6.children![0]).toBe(e7); }); it("remove", () => { const e2 = new E({ scene: runtime.scene }); const e3 = new E({ scene: runtime.scene }); expect(e2.scene).toBe(runtime.scene); expect(e3.scene).toBe(runtime.scene); expect(runtime.game.db[e.id]).toBe(e); expect(runtime.game.db[e2.id]).toBe(e2); expect(runtime.game.db[e3.id]).toBe(e3); e.append(e2); expect(e.parent).toBe(runtime.scene); expect(e2.parent).toBe(e); e2.remove(); expect(e.parent).toBe(runtime.scene); expect(e2.parent).toBeUndefined(); expect(runtime.game.db[e.id]).toBe(e); expect(runtime.game.db[e2.id]).toBe(e2); e2.destroy(); expect(runtime.game.db[e2.id]).toBeUndefined(); expect(e2.destroyed()).toBe(true); runtime.scene.append(e3); expect(e3.parent).toBe(runtime.scene); runtime.scene.remove(e3); expect(e3.parent).toBeUndefined(); expect(runtime.game.db[e3.id]).toBe(e3); e3.destroy(); expect(runtime.game.db[e3.id]).toBeUndefined(); }); it("remove - AssertionError", () => { const e2 = new E({ scene: runtime.scene }); e.append(e2); e2.remove(); e2.destroy(); expect(() => { e2.remove(e2); }).toThrowError("AssertionError"); }); it("destroy - has no handle", () => { const e2 = new E({ scene: runtime.scene }); e.append(e2); expect(e.children!.length).toBe(1); expect(e.children![0]).toBe(e2); e2.destroy(); expect(e.children!.length).toBe(0); const e3 = new E({ scene: runtime.scene }); const e4 = new E({ scene: runtime.scene }); e.append(e3); e.append(e4); expect(e.children!.length).toBe(2); expect(e.children![0]).toBe(e3); expect(e.children![1]).toBe(e4); e3.destroy(); expect(e.children!.length).toBe(1); expect(e.children![0]).toBe(e4); expect(e3.parent).toBe(undefined); expect(e3.destroyed()).toBe(true); const e5 = new E({ scene: runtime.scene }); e.append(e5); expect(e.children!.length).toBe(2); expect(e.children![0]).toBe(e4); expect(e.children![1]).toBe(e5); e.destroy(); expect(e.parent).toBe(undefined); expect(e.destroyed()).toBe(true); expect(e.children).toBe(undefined); expect(e4.parent).toBe(undefined); expect(e4.destroyed()).toBe(true); expect(e4.children).toBe(undefined); expect(e5.parent).toBe(undefined); expect(e5.destroyed()).toBe(true); expect(e5.children).toBe(undefined); }); it("destroy - has handles", () => { e.onMessage.add(() => { /* do nothing */ }); e.onPointDown.add(() => { /* do nothing */ }); e.onPointMove.add(() => { /* do nothing */ }); e.onPointUp.add(() => { /* do nothing */ }); expect((e as any)._onMessage).toBeDefined(); expect((e as any)._onPointDown).toBeDefined(); expect((e as any)._onPointMove).toBeDefined(); expect((e as any)._onPointUp).toBeDefined(); e.destroy(); expect(e.parent).toBe(undefined); expect(e.destroyed()).toBe(true); expect(e.children).toBe(undefined); expect((e as any)._onMessage).toBeUndefined(); expect((e as any)._onPointDown).toBeUndefined(); expect((e as any)._onPointMove).toBeUndefined(); expect((e as any)._onPointUp).toBeUndefined(); }); it("modified", () => { resetUpdated(runtime); expect(runtime.game._modified).toBe(false); e.modified(); expect(runtime.game._modified).toBe(true); resetUpdated(runtime); const e2 = new E({ scene: runtime.scene }); e.append(e2); expect(runtime.game._modified).toBe(true); resetUpdated(runtime); const e3 = new E({ scene: runtime.scene }); e.append(e3); expect(runtime.game._modified).toBe(true); }); it("modified with hide/show", () => { resetUpdated(runtime); expect(runtime.game._modified).toBe(false); e.hide(); expect(runtime.game._modified).toBe(true); runtime.game.render(); expect(runtime.game._modified).toBe(false); e.show(); expect(runtime.game._modified).toBe(true); }); it("update", () => { expect((e as any)._onUpdate).toBeUndefined(); expect(runtime.scene.onUpdate.length > 0).toBe(false); runtime.game.tick(true); // auto chain expect(e.onUpdate).not.toBeUndefined(); expect((e as any)._onUpdate).not.toBeUndefined(); expect((e as any)._onUpdate.chain).not.toBeUndefined(); expect(runtime.scene.onUpdate.length > 0).toBe(false); runtime.game.tick(true); let estate = false; let esuccess = false; e.onUpdate.add(() => { if (!estate) fail("efail"); esuccess = true; }); expect(runtime.scene.onUpdate.length > 0).toBe(true); estate = true; runtime.game.tick(true); expect(esuccess).toBe(true); const scene2 = new Scene({ game: runtime.game }); runtime.game.pushScene(scene2); runtime.game._flushPostTickTasks(); estate = false; runtime.game.tick(true); runtime.game.tick(true); runtime.game.tick(true); runtime.game.popScene(); runtime.game._flushPostTickTasks(); estate = true; esuccess = false; runtime.game.tick(true); expect(esuccess).toBe(true); const scene3 = new Scene({ game: runtime.game }); runtime.game.replaceScene(scene3); runtime.game._flushPostTickTasks(); estate = false; expect(scene3.onUpdate.length > 0).toBe(false); expect(runtime.scene.onUpdate.destroyed()).toBe(true); runtime.game.tick(true); }); it("operate", () => { expect((e as any)._onPointDown).toBeUndefined(); expect(runtime.scene.onPointDownCapture.length > 0).toBe(false); expect(e.onPointDown).not.toBeUndefined(); expect((e as any)._onPointDown).not.toBeUndefined(); expect((e as any)._onPointDown.chain).not.toBeUndefined(); expect(runtime.scene.onPointDownCapture.length > 0).toBe(false); const operationTick = (): void => { const event = runtime.game._pointEventResolver.pointDown({ type: PlatformPointType.Down, identifier: 1, offset: { x: 0, y: 0 } }); runtime.game.tick(true, 0, [event]); }; let estate = false; let esuccess = false; e.onPointDown.add(() => { if (!estate) fail("efail"); esuccess = true; }); operationTick(); e.touchable = true; e.width = 1; e.height = 1; estate = true; operationTick(); expect(esuccess).toBe(true); const scene2 = new Scene({ game: runtime.game }); runtime.game.pushScene(scene2); runtime.game._flushPostTickTasks(); estate = false; operationTick(); operationTick(); operationTick(); runtime.game.popScene(); runtime.game._flushPostTickTasks(); estate = true; esuccess = false; operationTick(); expect(esuccess).toBe(true); runtime.game.replaceScene(new Scene({ game: runtime.game })); runtime.game._flushPostTickTasks(); estate = false; expect(runtime.scene.onPointDownCapture.destroyed()).toBe(true); operationTick(); }); it("findPointSource", () => { e.touchable = true; e.x = e.y = 100; e.width = e.height = 100; const face1 = new E({ scene: runtime.scene }); face1.touchable = true; face1.x = face1.y = 10; face1.width = face1.height = 10; e.append(face1); face1.modified(); let found: PointSource; found = runtime.game.findPointSource({ x: 150, y: 150 })!; expect(found && found.target).toBe(e); found = runtime.game.findPointSource({ x: 115, y: 115 })!; expect(found && found.target).toBe(face1); const cam1 = new Camera2D({}); cam1.x = cam1.y = 10; found = runtime.game.findPointSource({ x: 115, y: 115 }, cam1)!; expect(found && found.target).toBe(e); const face2 = new E({ scene: runtime.scene }); face2.x = face2.y = 10; face2.width = face2.height = 10; e.append(face2); face2.modified(); face2.touchable = true; found = runtime.game.findPointSource({ x: 115, y: 115 })!; expect(found && found.target).toBe(face2); face2.touchable = false; found = runtime.game.findPointSource({ x: 115, y: 115 })!; expect(found && found.target).toBe(face1); face1.touchable = false; found = runtime.game.findPointSource({ x: 115, y: 115 })!; expect(found && found.target).toBe(e); }); it("findPointSource - deep", () => { const e2 = new E({ scene: runtime.scene }); const e3 = new E({ scene: runtime.scene }); const e4 = new E({ scene: runtime.scene }); e.append(e2); e2.append(e3); e3.append(e4); e.x = e.y = e2.x = e2.y = e3.x = e3.y = 0; e4.x = e4.y = 0; e4.width = e4.height = 100; e4.modified(); let found; found = runtime.scene.findPointSourceByPoint({ x: 50, y: 50 }); expect(found && found.target).toBeUndefined(); e4.touchable = true; found = runtime.scene.findPointSourceByPoint({ x: 50, y: 50 }); expect(found && found.target).toBe(e4); e4.remove(); found = runtime.scene.findPointSourceByPoint({ x: 50, y: 50 }); expect(found && found.target).toBeUndefined(); }); it("findPointSource - rotated/scaled", () => { e.touchable = true; e.width = e.height = 100; e.x = e.y = 100 + e.width / 2; e.anchorX = e.anchorY = 0.5; let found; found = runtime.game.findPointSource({ x: 150, y: 150 }); expect(found && found.target).toBe(e); found = runtime.game.findPointSource({ x: 105, y: 105 }); expect(found && found.target).toBe(e); e.angle = 45; e.modified(); found = runtime.game.findPointSource({ x: 105, y: 105 }); expect(found).toEqual({ target: undefined, point: undefined, local: false }); found = runtime.game.findPointSource({ x: 150, y: 95 }); expect(found && found.target).toBe(e); e.scaleY = 0.5; e.modified(); found = runtime.game.findPointSource({ x: 150, y: 95 }); expect(found).toEqual({ target: undefined, point: undefined, local: false }); found = runtime.game.findPointSource({ x: 150, y: 105 }); expect(found).toEqual({ target: undefined, point: undefined, local: false }); found = runtime.game.findPointSource({ x: 150, y: 150 }); expect(found && found.target).toBe(e); }); it("findPointSource - dynamic", () => { e.x = e.y = 100; e.width = e.height = 99; const child = new E({ scene: runtime.scene }); child.x = child.y = 90; child.width = child.height = 90; child.touchable = true; e.append(child); const sibling = new E({ scene: runtime.scene }); sibling.x = 200; sibling.y = 0; sibling.width = sibling.height = 10; runtime.scene.append(sibling); sibling.modified(); expect(e._hasTouchableChildren).toBe(true); expect(sibling._hasTouchableChildren).toBe(false); let found = runtime.game.findPointSource({ x: 100 + 90 + 5, y: 100 + 90 + 5 }); expect(found && found.target).toBe(child); found = runtime.game.findPointSource({ x: 100 + 5, y: 100 + 5 }); expect(found).toEqual({ target: undefined, point: undefined, local: false }); // on e (untouchable) sibling.append(child); expect(e._hasTouchableChildren).toBe(false); expect(sibling._hasTouchableChildren).toBe(true); found = runtime.game.findPointSource({ x: 100 + 90 + 5, y: 100 + 90 + 5 }); expect(found).toEqual({ target: undefined, point: undefined, local: false }); found = runtime.game.findPointSource({ x: 200 + 90 + 5, y: 0 + 90 + 5 }); expect(found && found.target).toBe(child); e.append(child); expect(e._hasTouchableChildren).toBe(true); expect(sibling._hasTouchableChildren).toBe(false); found = runtime.game.findPointSource({ x: 100 + 90 + 5, y: 100 + 90 + 5 }); expect(found && found.target).toBe(child); found = runtime.game.findPointSource({ x: 100 + 5, y: 100 + 5 }); expect(found).toEqual({ target: undefined, point: undefined, local: false }); // on e (untouchable) sibling.append(e); expect(e._hasTouchableChildren).toBe(true); expect(sibling._hasTouchableChildren).toBe(true); found = runtime.game.findPointSource({ x: 100 + 200 + 90 + 5, y: 100 + 0 + 90 + 5 }); expect(found && found.target).toBe(child); const e2 = new E({ scene: runtime.scene }); runtime.scene.append(e2); e2.append(sibling); expect(e._hasTouchableChildren).toBe(true); expect(sibling._hasTouchableChildren).toBe(true); expect(e2._hasTouchableChildren).toBe(true); sibling.remove(); expect(e._hasTouchableChildren).toBe(true); expect(sibling._hasTouchableChildren).toBe(true); expect(e2._hasTouchableChildren).toBe(false); }); it("findPointSource - hide", () => { e.touchable = true; e.x = e.y = 0; e.width = 100; e.height = 100; e.modified(); let found; found = runtime.scene.findPointSourceByPoint({ x: 50, y: 50 }); expect(found && found.target).toBe(e); e.hide(); found = runtime.scene.findPointSourceByPoint({ x: 50, y: 50 }); expect(found).toEqual({ target: undefined, point: undefined, local: false }); }); it("findPointSource - clipping", () => { const e2 = new E({ scene: runtime.scene }); e.append(e2); e.x = e.y = e2.x = e2.y = 0; e.width = 100; e.height = 100; e.modified(); e2.touchable = true; e2.width = 200; e2.height = 200; e2.modified(); let found; found = runtime.scene.findPointSourceByPoint({ x: 150, y: 150 }); expect(found && found.target).toBe(e2); e.shouldFindChildrenByPoint = () => { return false; }; found = runtime.scene.findPointSourceByPoint({ x: 150, y: 150 }); expect(found && found.target).toBeUndefined(); }); it("findPointSource - local scene", () => { const game = new Game({ width: 320, height: 320, main: "", assets: {} }); const scene = new Scene({ game: game, local: true }); game.pushScene(scene); game._flushPostTickTasks(); const e = new E({ scene: scene, touchable: true, x: 100, y: 100, width: 100, height: 100 }); scene.append(e); let found; found = game.findPointSource({ x: 150, y: 150 }); expect(found).toEqual({ target: e, point: { x: 50, y: 50 }, local: true }); found = game.findPointSource({ x: 0, y: 0 }); expect(found).toEqual({ target: undefined, point: undefined, local: true }); }); it("findPointSource - local entity", () => { const eparam = { scene: runtime.scene, local: true, touchable: true }; e = new E(eparam); e.x = e.y = 100; e.width = e.height = 100; runtime.scene.append(e); let found; found = runtime.game.findPointSource({ x: 150, y: 150 }); expect(found).toEqual({ target: e, point: { x: 50, y: 50 }, local: true }); }); it("get update", () => { const e = new E({ scene: runtime.scene }); expect((e as any)._onUpdate).toBeUndefined(); const u = e.onUpdate; expect((e as any)._onUpdate).toBe(u); expect(e.onUpdate).toBe(u); let firedFlg = false; u.add(() => { firedFlg = true; }); expect(firedFlg).toBe(false); u.fire(); expect(firedFlg).toBe(true); }); it("get message", () => { const e = new E({ scene: runtime.scene }); expect((e as any)._onMessage).toBeUndefined(); const m = e.onMessage; expect((e as any)._onMessage).toBe(m); expect(e.onMessage).toBe(m); let firedFlg = false; m.add(() => { firedFlg = true; }); expect(firedFlg).toBe(false); m.fire(new MessageEvent("dummy")); expect(firedFlg).toBe(true); }); it("get pointDown", () => { const e = new E({ scene: runtime.scene }); expect((e as any)._onPointDown).toBeUndefined(); const p = e.onPointDown; expect((e as any)._onPointDown).toBe(p); expect(e.onPointDown).toBe(p); let firedFlg = false; p.add(() => { firedFlg = true; }); expect(firedFlg).toBe(false); p.fire(new PointDownEvent(0, undefined, { x: 0, y: 0 })); expect(firedFlg).toBe(true); }); it("get pointUp", () => { const e = new E({ scene: runtime.scene }); expect((e as any)._onPointUp).toBeUndefined(); const p = e.onPointUp; expect((e as any)._onPointUp).toBe(p); expect(e.onPointUp).toBe(p); let firedFlg = false; p.add(() => { firedFlg = true; }); expect(firedFlg).toBe(false); p.fire(new PointUpEvent(0, undefined, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 })); expect(firedFlg).toBe(true); }); it("get pointMove", () => { const e = new E({ scene: runtime.scene }); expect((e as any)._onPointMove).toBeUndefined(); const p = e.onPointMove; expect((e as any)._onPointMove).toBe(p); expect(e.onPointMove).toBe(p); let firedFlg = false; p.add(() => { firedFlg = true; }); expect(firedFlg).toBe(false); p.fire(new PointMoveEvent(0, undefined, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 })); expect(firedFlg).toBe(true); }); it("set/get touchable", () => { const e = new E({ scene: runtime.scene }); expect((e as any)._touchable).toBe(false); expect(e.touchable).toBe(false); e.touchable = true; expect((e as any)._touchable).toBe(true); expect(e.touchable).toBe(true); let enableFlg = false; e._enableTouchPropagation = () => { enableFlg = true; }; e.touchable = false; expect(enableFlg).toBe(false); e.touchable = true; expect(enableFlg).toBe(true); let disableFlg = false; e._disableTouchPropagation = () => { disableFlg = true; }; e.touchable = true; expect(disableFlg).toBe(false); e.touchable = false; expect(disableFlg).toBe(true); }); it("render with camera", () => { const e = new E({ scene: runtime.scene }); const r = new Renderer(); const c = new Camera2D({}); r.clearMethodCallHistory(); e.modified(); e.render(r, c); expect(r.methodCallHistory).toEqual(["translate", "translate"]); r.clearMethodCallHistory(); e.scale(2); e.render(r, c); expect(r.methodCallHistory).toEqual(["translate", "translate"]); r.clearMethodCallHistory(); e.opacity = 0; e.render(r, c); expect(r.methodCallHistory).toEqual(["translate", "translate"]); e.opacity = 1; r.clearMethodCallHistory(); e.hide(); e.render(r, c); expect(r.methodCallHistory).toEqual([]); e.show(); r.clearMethodCallHistory(); const e2 = new E({ scene: runtime.scene }); e.children = [e2]; e.render(r, c); expect(r.methodCallHistory).toEqual(["translate", "save", "translate", "restore", "translate"]); }); it("render without camera", () => { const e = new E({ scene: runtime.scene }); const r = new Renderer(); e.modified(); e.render(r); expect(r.methodCallHistory).toEqual(["translate", "translate"]); r.clearMethodCallHistory(); e.scale(2); e.render(r); expect(r.methodCallHistory).toEqual(["translate", "translate"]); r.clearMethodCallHistory(); e.opacity = 0; e.render(r); expect(r.methodCallHistory).toEqual(["translate", "translate"]); e.opacity = 1; r.clearMethodCallHistory(); e.hide(); e.render(r); expect(r.methodCallHistory).toEqual([]); e.show(); r.clearMethodCallHistory(); const e2 = new E({ scene: runtime.scene }); e.children = [e2]; e.render(r); expect(r.methodCallHistory).toEqual(["translate", "save", "translate", "restore", "translate"]); }); it("renderSelf with camera", () => { const e = new E({ scene: runtime.scene }); const r = new Renderer(); const c = new Camera2D({}); expect(e.renderSelf(r, c)).toBe(true); expect(r.methodCallHistory).toEqual([]); }); it("renderSelf without camera", () => { const e = new E({ scene: runtime.scene }); const r = new Renderer(); expect(e.renderSelf(r)).toBe(true); expect(r.methodCallHistory).toEqual([]); }); it("visible", () => { const e = new E({ scene: runtime.scene }); expect(e.visible()).toBe(true); e.hide(); expect(e.visible()).toBe(false); e.show(); expect(e.visible()).toBe(true); }); it("_enableTouchPropagation", () => { const e = new E({ scene: runtime.scene }); const e2 = new E({ scene: runtime.scene }); e.append(e2); expect(e._hasTouchableChildren).toBe(false); e2._enableTouchPropagation(); expect(e._hasTouchableChildren).toBe(true); }); it("_disableTouchPropagation", () => { const e = new E({ scene: runtime.scene }); const e2 = new E({ scene: runtime.scene }); const e3 = new E({ scene: runtime.scene }); const e4 = new E({ scene: runtime.scene }); e3.append(e4); e2.append(e3); e.append(e2); e2.touchable = true; e4.touchable = true; expect(e._hasTouchableChildren).toBe(true); e2._disableTouchPropagation(); expect(e._hasTouchableChildren).toBe(true); // e4 is touchable e._disableTouchPropagation(); expect(e._hasTouchableChildren).toBe(true); e4._disableTouchPropagation(); expect(e._hasTouchableChildren).toBe(true); // e4 and e2 is touchable const parent = new E({ scene: runtime.scene }); const child1 = new E({ scene: runtime.scene }); const child2 = new E({ scene: runtime.scene }); parent.append(child1); parent.append(child2); child1.touchable = true; child2.touchable = true; expect(child1.touchable).toBe(true); expect(child2.touchable).toBe(true); child2.touchable = false; expect(child1.touchable).toBe(true); expect(child2.touchable).toBe(false); }); it("_isTargetOperation", () => { const e = new E({ scene: runtime.scene }); const p = new PointDownEvent(0, e, { x: 0, y: 0 }); expect(e._isTargetOperation(p)).toBe(false); e.touchable = true; expect(e._isTargetOperation(p)).toBe(true); e.hide(); expect(e._isTargetOperation(p)).toBe(false); e.show(); expect(e._isTargetOperation(p)).toBe(true); expect(e._isTargetOperation(null!)).toBe(false); const e2 = new E({ scene: runtime.scene }); expect(e2._isTargetOperation(p)).toBe(false); e2.touchable = true; expect(e2._isTargetOperation(p)).toBe(false); e2.hide(); expect(e2._isTargetOperation(p)).toBe(false); e2.show(); expect(e2._isTargetOperation(p)).toBe(false); expect(e2._isTargetOperation(null!)).toBe(false); }); it("render - compositeOperationString", () => { const e = new E({ scene: runtime.scene }); const r = new Renderer(); e.render(r); expect(r.methodCallHistory).toEqual(["save", "translate", "restore"]); e.compositeOperation = "xor"; r.clearMethodCallHistory(); e.render(r); expect(r.methodCallHistory).toEqual(["save", "translate", "setCompositeOperation", "restore"]); expect(r.methodCallParamsHistory("setCompositeOperation")[0]).toEqual({ operation: "xor" }); e.compositeOperation = CompositeOperation.SourceAtop; r.clearMethodCallHistory(); e.render(r); expect(r.methodCallHistory).toEqual(["save", "translate", "setCompositeOperation", "restore"]); expect(r.methodCallParamsHistory("setCompositeOperation")[0]).toEqual({ operation: "source-atop" }); e.compositeOperation = undefined; r.clearMethodCallHistory(); e.render(r); expect(r.methodCallHistory).toEqual(["save", "translate", "restore"]); }); it("calculateBoundingRect", () => { const runtime = skeletonRuntime(); const scene = runtime.scene; const e = new E({ scene }); e.width = 100; e.height = 50; e.scale(2); scene.append(e); e.modified(); const result = e.calculateBoundingRect()!; expect(result.left).toBe(0); expect(result.right).toBe(200); expect(result.top).toBe(0); expect(result.bottom).toBe(100); const e2 = new E({ scene }); e2.width = 100; e2.height = 50; e2.anchor(0.5, 0.5); e2.scale(2); e2.moveTo(-50, -10); scene.append(e2); e2.modified(); const result2 = e2.calculateBoundingRect()!; expect(result2.left).toBe(-150); expect(result2.right).toBe(50); expect(result2.top).toBe(-60); expect(result2.bottom).toBe(40); const e3 = new E({ scene }); e3.width = 300; e3.height = 400; e3.scale(0.5); e3.anchor(1, 1); e3.moveTo(10, 20); scene.append(e3); e3.modified(); const result3 = e3.calculateBoundingRect()!; expect(result3.left).toBe(-140); expect(result3.right).toBe(10); expect(result3.top).toBe(-180); expect(result3.bottom).toBe(20); }); it("calculateBoundingRect with children", () => { const runtime = skeletonRuntime(); const scene = runtime.scene; const e = new E({ scene: scene }); e.width = 100; e.height = 50; scene.append(e); const e2 = new E({ scene: scene }); e2.width = 400; e2.height = 200; scene.append(e2); e.append(e2); const e3 = new E({ scene: scene }); e3.width = 200; e3.height = 400; scene.append(e3); e.append(e3); const result = e.calculateBoundingRect()!; expect(result.left).toBe(0); expect(result.right).toBe(400); expect(result.top).toBe(0); expect(result.bottom).toBe(400); }); it("calculateBoundingRect with grandchild", () => { const runtime = skeletonRuntime(); const scene = runtime.scene; const e = new E({ scene: scene }); e.width = 100; e.height = 50; scene.append(e); const e2 = new E({ scene: scene }); e2.width = 200; e2.height = 200; scene.append(e2); e.append(e2); const e3 = new E({ scene: scene }); e3.width = 400; e3.height = 200; scene.append(e3); e2.append(e3); const e4 = new E({ scene: scene }); e4.width = 200; e4.height = 400; scene.append(e4); e3.append(e4); const result = e.calculateBoundingRect()!; expect(result.left).toBe(0); expect(result.right).toBe(400); expect(result.top).toBe(0); expect(result.bottom).toBe(400); }); it("EntityStateFlags", () => { const e = new E({ scene: runtime.scene }); expect(e.state).toBe(EntityStateFlags.None); e.x += 1; e.modified(); expect(e.state).toBe(EntityStateFlags.Modified | EntityStateFlags.ContextLess); const r = new Renderer(); e.render(r, runtime.game.focusingCamera); expect(e.state).toBe(EntityStateFlags.ContextLess); e.angle = 10; e.modified(); expect(e.state).toBe(EntityStateFlags.Modified); e.render(r, runtime.game.focusingCamera); e.angle = 0; e.modified(); expect(e.state).toBe(EntityStateFlags.Modified | EntityStateFlags.ContextLess); }); describe("localToGlobal, globalToLocal", () => { let p: E; let p2: E; let p3: E; let e: E; let anotherRuntime: Runtime; beforeEach(() => { // 各エンティティのマトリクスは以下の値になる // p: [ 0.5, 0, -0, 0.5, 100, 100 ] // p2: [ 0.7071067811865476, 0.7071067811865475, -0.7071067811865475, 0.7071067811865476, 0, 0 ] // p3: [ 2, 0, -0, 3, 20, 20 ] // e: [ 1, 0, 0, 1, 10, 0 ] // p * p2 * p3 * e: [0.707107, 0.707107, -1.06066, 1.06066, 107.071, 121.213] // ( p * p2 * p3 * e)-1: [0.707107, -0.471405, 0.707107, 0.471405, -161.421, -6.6666] p = new E({ scene: runtime.scene, x: 100, y: 100, scaleX: 0.5, scaleY: 0.5, anchorX: 1, anchorY: 1 }); p2 = new E({ scene: runtime.scene, angle: 45, anchorX: 0.5, anchorY: 0.5, parent: p }); p3 = new E({ scene: runtime.scene, x: 20, y: 20, scaleX: 2, scaleY: 3, parent: p2 }); e = new E({ scene: runtime.scene, parent: p3, x: 10, y: 0 }); anotherRuntime = skeletonRuntime(); }); it("can convert local point to global point", () => { // 一番上の親エンティティのparentがundefinedの場合 const targetPoint = { x: 5, y: 30 }; const actual = e.localToGlobal(targetPoint); // (p * p2 * p3 * e) * targetPoint の計算結果 const expected = { x: 78.787, y: 156.568 }; // 小数点第2位まで合っていればパスとする expect(actual.x).toBeApproximation(expected.x, 3); expect(actual.y).toBeApproximation(expected.y, 3); // 一番上の親エンティティのparentがsceneに変わってもlocalToGlobalの結果は変わらない p.parent = anotherRuntime.scene; anotherRuntime.scene.append(p); const actual2 = e.localToGlobal(targetPoint); expect(actual2.x).toBeApproximation(expected.x, 3); expect(actual2.y).toBeApproximation(expected.y, 3); }); it("can convert global point to local point", () => { // 一番上の親エンティティのparentがundefinedの場合 const targetPoint = { x: 500, y: 500 }; const actual = e.globalToLocal(targetPoint); // (p * p2 * p3 * e)-1 * targetPoint の計算結果 const expected = { x: 545.686, y: -6.667 }; // 小数点第2位まで合っていればパスとする expect(actual.x).toBeApproximation(expected.x, 3); expect(actual.y).toBeApproximation(expected.y, 3); // 一番上の親エンティティのparentがsceneに変わってもlocalToGlobalの結果は変わらない p.parent = anotherRuntime.scene; anotherRuntime.scene.append(p); const actual2 = e.globalToLocal(targetPoint); expect(actual2.x).toBeApproximation(expected.x, 3); expect(actual2.y).toBeApproximation(expected.y, 3); }); it("is reversible", () => { const targetPoint = { x: 0, y: 0 }; const actual = e.localToGlobal(e.globalToLocal(targetPoint)); expect(actual.x).toBeApproximation(targetPoint.x, 10); expect(actual.y).toBeApproximation(targetPoint.y, 10); const actual2 = e.globalToLocal(e.localToGlobal(targetPoint)); expect(actual2.x).toBeApproximation(targetPoint.x, 10); expect(actual2.y).toBeApproximation(targetPoint.y, 10); }); it("can convert predictable values", () => { const targetPoint = { x: 0, y: 0 }; // これらのマトリクスはかけると [1, 0, 0, 1, 0, 0] に近似した値となる p = new E({ scene: runtime.scene, x: 100, y: 100, scaleX: 0.5, scaleY: 0.5 }); p2 = new E({ scene: runtime.scene, angle: 45, parent: p }); p3 = new E({ scene: runtime.scene, angle: -45, scaleX: 2, scaleY: 2, parent: p2 }); e = new E({ scene: runtime.scene, parent: p3, x: -100, y: -100 }); // localToGlobalとglobalToLocalのどちらを実行しても元の位置に戻る const actual = e.localToGlobal(targetPoint); expect(actual.x).toBeApproximation(targetPoint.x, 3); expect(actual.y).toBeApproximation(targetPoint.y, 3); const actual2 = e.globalToLocal(targetPoint); expect(actual2.x).toBeApproximation(targetPoint.x, 3); expect(actual2.y).toBeApproximation(targetPoint.y, 3); }); }); });
the_stack
import { Rectangle } from "./rectangle"; import { StackPanel } from "./stackPanel"; import { Control } from "./control"; import { TextBlock } from "./textBlock"; import { Checkbox } from "./checkbox"; import { RadioButton } from "./radioButton"; import { Slider } from "./sliders/slider"; import { Container } from "./container"; /** Class used to create a RadioGroup * which contains groups of radio buttons */ export class SelectorGroup { private _groupPanel = new StackPanel(); private _selectors: StackPanel[] = new Array(); private _groupHeader: TextBlock; /** * Creates a new SelectorGroup * @param name of group, used as a group heading */ constructor( /** name of SelectorGroup */ public name: string) { this._groupPanel.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP; this._groupPanel.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; this._groupHeader = this._addGroupHeader(name); } /** Gets the groupPanel of the SelectorGroup */ public get groupPanel(): StackPanel { return this._groupPanel; } /** Gets the selectors array */ public get selectors(): StackPanel[] { return this._selectors; } /** Gets and sets the group header */ public get header() { return this._groupHeader.text; } public set header(label: string) { if (this._groupHeader.text === "label") { return; } this._groupHeader.text = label; } /** @hidden */ private _addGroupHeader(text: string): TextBlock { var groupHeading = new TextBlock("groupHead", text); groupHeading.width = 0.9; groupHeading.height = "30px"; groupHeading.textWrapping = true; groupHeading.color = "black"; groupHeading.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; groupHeading.textHorizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; groupHeading.left = "2px"; this._groupPanel.addControl(groupHeading); return groupHeading; } /** @hidden*/ public _getSelector(selectorNb: number) { if (selectorNb < 0 || selectorNb >= this._selectors.length) { return; } return this._selectors[selectorNb]; } /** Removes the selector at the given position * @param selectorNb the position of the selector within the group */ public removeSelector(selectorNb: number) { if (selectorNb < 0 || selectorNb >= this._selectors.length) { return; } this._groupPanel.removeControl(this._selectors[selectorNb]); this._selectors.splice(selectorNb, 1); } } /** Class used to create a CheckboxGroup * which contains groups of checkbox buttons */ export class CheckboxGroup extends SelectorGroup { /** Adds a checkbox as a control * @param text is the label for the selector * @param func is the function called when the Selector is checked * @param checked is true when Selector is checked */ public addCheckbox(text: string, func = (s: boolean) => { }, checked: boolean = false): void { var checked = checked || false; var button = new Checkbox(); button.width = "20px"; button.height = "20px"; button.color = "#364249"; button.background = "#CCCCCC"; button.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; button.onIsCheckedChangedObservable.add(function (state) { func(state); }); var _selector = Control.AddHeader(button, text, "200px", { isHorizontal: true, controlFirst: true }); _selector.height = "30px"; _selector.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; _selector.left = "4px"; this.groupPanel.addControl(_selector); this.selectors.push(_selector); button.isChecked = checked; if (this.groupPanel.parent && this.groupPanel.parent.parent) { button.color = (<SelectionPanel>this.groupPanel.parent.parent).buttonColor; button.background = (<SelectionPanel>this.groupPanel.parent.parent).buttonBackground; } } /** @hidden */ public _setSelectorLabel(selectorNb: number, label: string) { (<TextBlock>this.selectors[selectorNb].children[1]).text = label; } /** @hidden */ public _setSelectorLabelColor(selectorNb: number, color: string) { (<TextBlock>this.selectors[selectorNb].children[1]).color = color; } /** @hidden */ public _setSelectorButtonColor(selectorNb: number, color: string) { this.selectors[selectorNb].children[0].color = color; } /** @hidden */ public _setSelectorButtonBackground(selectorNb: number, color: string) { (<Checkbox>this.selectors[selectorNb].children[0]).background = color; } } /** Class used to create a RadioGroup * which contains groups of radio buttons */ export class RadioGroup extends SelectorGroup { private _selectNb = 0; /** Adds a radio button as a control * @param label is the label for the selector * @param func is the function called when the Selector is checked * @param checked is true when Selector is checked */ public addRadio(label: string, func = (n: number) => { }, checked = false): void { var nb = this._selectNb++; var button = new RadioButton(); button.name = label; button.width = "20px"; button.height = "20px"; button.color = "#364249"; button.background = "#CCCCCC"; button.group = this.name; button.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; button.onIsCheckedChangedObservable.add(function (state) { if (state) { func(nb); } }); var _selector = Control.AddHeader(button, label, "200px", { isHorizontal: true, controlFirst: true }); _selector.height = "30px"; _selector.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; _selector.left = "4px"; this.groupPanel.addControl(_selector); this.selectors.push(_selector); button.isChecked = checked; if (this.groupPanel.parent && this.groupPanel.parent.parent) { button.color = (<SelectionPanel>this.groupPanel.parent.parent).buttonColor; button.background = (<SelectionPanel>this.groupPanel.parent.parent).buttonBackground; } } /** @hidden */ public _setSelectorLabel(selectorNb: number, label: string) { (<TextBlock>this.selectors[selectorNb].children[1]).text = label; } /** @hidden */ public _setSelectorLabelColor(selectorNb: number, color: string) { (<TextBlock>this.selectors[selectorNb].children[1]).color = color; } /** @hidden */ public _setSelectorButtonColor(selectorNb: number, color: string) { this.selectors[selectorNb].children[0].color = color; } /** @hidden */ public _setSelectorButtonBackground(selectorNb: number, color: string) { (<RadioButton>this.selectors[selectorNb].children[0]).background = color; } } /** Class used to create a SliderGroup * which contains groups of slider buttons */ export class SliderGroup extends SelectorGroup { /** * Adds a slider to the SelectorGroup * @param label is the label for the SliderBar * @param func is the function called when the Slider moves * @param unit is a string describing the units used, eg degrees or metres * @param min is the minimum value for the Slider * @param max is the maximum value for the Slider * @param value is the start value for the Slider between min and max * @param onValueChange is the function used to format the value displayed, eg radians to degrees */ public addSlider(label: string, func = (v: number) => { }, unit: string = "Units", min: number = 0, max: number = 0, value: number = 0, onValueChange = (v: number) => { return v | 0; }): void { var button = new Slider(); button.name = unit; button.value = value; button.minimum = min; button.maximum = max; button.width = 0.9; button.height = "20px"; button.color = "#364249"; button.background = "#CCCCCC"; button.borderColor = "black"; button.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; button.left = "4px"; button.paddingBottom = "4px"; button.onValueChangedObservable.add(function (value) { (<TextBlock>button.parent!.children[0]).text = button.parent!.children[0].name + ": " + onValueChange(value) + " " + button.name; func(value); }); var _selector = Control.AddHeader(button, label + ": " + onValueChange(value) + " " + unit, "30px", { isHorizontal: false, controlFirst: false }); _selector.height = "60px"; _selector.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; _selector.left = "4px"; _selector.children[0].name = label; this.groupPanel.addControl(_selector); this.selectors.push(_selector); if (this.groupPanel.parent && this.groupPanel.parent.parent) { button.color = (<SelectionPanel>this.groupPanel.parent.parent).buttonColor; button.background = (<SelectionPanel>this.groupPanel.parent.parent).buttonBackground; } } /** @hidden */ public _setSelectorLabel(selectorNb: number, label: string) { this.selectors[selectorNb].children[0].name = label; (<TextBlock>this.selectors[selectorNb].children[0]).text = label + ": " + (<Slider>this.selectors[selectorNb].children[1]).value + " " + this.selectors[selectorNb].children[1].name; } /** @hidden */ public _setSelectorLabelColor(selectorNb: number, color: string) { (<TextBlock>this.selectors[selectorNb].children[0]).color = color; } /** @hidden */ public _setSelectorButtonColor(selectorNb: number, color: string) { this.selectors[selectorNb].children[1].color = color; } /** @hidden */ public _setSelectorButtonBackground(selectorNb: number, color: string) { (<Slider>this.selectors[selectorNb].children[1]).background = color; } } /** Class used to hold the controls for the checkboxes, radio buttons and sliders * @see https://doc.babylonjs.com/how_to/selector */ export class SelectionPanel extends Rectangle { private _panel: StackPanel; private _buttonColor: string = "#364249"; private _buttonBackground: string = "#CCCCCC"; private _headerColor: string = "black"; private _barColor: string = "white"; private _barHeight: string = "2px"; private _spacerHeight: string = "20px"; private _labelColor: string; private _groups: SelectorGroup[]; private _bars: any[] = new Array(); /** * Creates a new SelectionPanel * @param name of SelectionPanel * @param groups is an array of SelectionGroups */ constructor( /** name of SelectionPanel */ public name: string, /** an array of SelectionGroups */ public groups: SelectorGroup[] = []) { super(name); this._groups = groups; this.thickness = 2; this._panel = new StackPanel(); this._panel.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP; this._panel.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; this._panel.top = 5; this._panel.left = 5; this._panel.width = 0.95; if (groups.length > 0) { for (var i = 0; i < groups.length - 1; i++) { this._panel.addControl(groups[i].groupPanel); this._addSpacer(); } this._panel.addControl(groups[groups.length - 1].groupPanel); } this.addControl(this._panel); } protected _getTypeName(): string { return "SelectionPanel"; } /** Gets the (stack) panel of the SelectionPanel */ public get panel(): StackPanel { return this._panel; } /** Gets or sets the headerColor */ public get headerColor(): string { return this._headerColor; } public set headerColor(color: string) { if (this._headerColor === color) { return; } this._headerColor = color; this._setHeaderColor(); } private _setHeaderColor() { for (var i = 0; i < this._groups.length; i++) { this._groups[i].groupPanel.children[0].color = this._headerColor; } } /** Gets or sets the button color */ public get buttonColor(): string { return this._buttonColor; } public set buttonColor(color: string) { if (this._buttonColor === color) { return; } this._buttonColor = color; this._setbuttonColor(); } private _setbuttonColor() { for (var i = 0; i < this._groups.length; i++) { for (var j = 0; j < this._groups[i].selectors.length; j++) { (<CheckboxGroup | RadioGroup | SliderGroup>this._groups[i])._setSelectorButtonColor(j, this._buttonColor); } } } /** Gets or sets the label color */ public get labelColor(): string { return this._labelColor; } public set labelColor(color: string) { if (this._labelColor === color) { return; } this._labelColor = color; this._setLabelColor(); } private _setLabelColor() { for (var i = 0; i < this._groups.length; i++) { for (var j = 0; j < this._groups[i].selectors.length; j++) { (<CheckboxGroup | RadioGroup | SliderGroup>this._groups[i])._setSelectorLabelColor(j, this._labelColor); } } } /** Gets or sets the button background */ public get buttonBackground(): string { return this._buttonBackground; } public set buttonBackground(color: string) { if (this._buttonBackground === color) { return; } this._buttonBackground = color; this._setButtonBackground(); } private _setButtonBackground() { for (var i = 0; i < this._groups.length; i++) { for (var j = 0; j < this._groups[i].selectors.length; j++) { (<CheckboxGroup | RadioGroup | SliderGroup>this._groups[i])._setSelectorButtonBackground(j, this._buttonBackground); } } } /** Gets or sets the color of separator bar */ public get barColor(): string { return this._barColor; } public set barColor(color: string) { if (this._barColor === color) { return; } this._barColor = color; this._setBarColor(); } private _setBarColor() { for (var i = 0; i < this._bars.length; i++) { this._bars[i].children[0].background = this._barColor; } } /** Gets or sets the height of separator bar */ public get barHeight(): string { return this._barHeight; } public set barHeight(value: string) { if (this._barHeight === value) { return; } this._barHeight = value; this._setBarHeight(); } private _setBarHeight() { for (var i = 0; i < this._bars.length; i++) { this._bars[i].children[0].height = this._barHeight; } } /** Gets or sets the height of spacers*/ public get spacerHeight(): string { return this._spacerHeight; } public set spacerHeight(value: string) { if (this._spacerHeight === value) { return; } this._spacerHeight = value; this._setSpacerHeight(); } private _setSpacerHeight() { for (var i = 0; i < this._bars.length; i++) { this._bars[i].height = this._spacerHeight; } } /** Adds a bar between groups */ private _addSpacer(): void { var separator = new Container(); separator.width = 1; separator.height = this._spacerHeight; separator.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; var bar = new Rectangle(); bar.width = 1; bar.height = this._barHeight; bar.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; bar.verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER; bar.background = this._barColor; bar.color = "transparent"; separator.addControl(bar); this._panel.addControl(separator); this._bars.push(separator); } /** Add a group to the selection panel * @param group is the selector group to add */ public addGroup(group: SelectorGroup): void { if (this._groups.length > 0) { this._addSpacer(); } this._panel.addControl(group.groupPanel); this._groups.push(group); group.groupPanel.children[0].color = this._headerColor; for (var j = 0; j < group.selectors.length; j++) { (<CheckboxGroup | RadioGroup | SliderGroup>group)._setSelectorButtonColor(j, this._buttonColor); (<CheckboxGroup | RadioGroup | SliderGroup>group)._setSelectorButtonBackground(j, this._buttonBackground); } } /** Remove the group from the given position * @param groupNb is the position of the group in the list */ public removeGroup(groupNb: number): void { if (groupNb < 0 || groupNb >= this._groups.length) { return; } var group = this._groups[groupNb]; this._panel.removeControl(group.groupPanel); this._groups.splice(groupNb, 1); if (groupNb < this._bars.length) { this._panel.removeControl(this._bars[groupNb]); this._bars.splice(groupNb, 1); } } /** Change a group header label * @param label is the new group header label * @param groupNb is the number of the group to relabel * */ public setHeaderName(label: string, groupNb: number) { if (groupNb < 0 || groupNb >= this._groups.length) { return; } var group = this._groups[groupNb]; (<TextBlock>group.groupPanel.children[0]).text = label; } /** Change selector label to the one given * @param label is the new selector label * @param groupNb is the number of the groupcontaining the selector * @param selectorNb is the number of the selector within a group to relabel * */ public relabel(label: string, groupNb: number, selectorNb: number): void { if (groupNb < 0 || groupNb >= this._groups.length) { return; } var group = this._groups[groupNb]; if (selectorNb < 0 || selectorNb >= group.selectors.length) { return; } (<CheckboxGroup | RadioGroup | SliderGroup>group)._setSelectorLabel(selectorNb, label); } /** For a given group position remove the selector at the given position * @param groupNb is the number of the group to remove the selector from * @param selectorNb is the number of the selector within the group */ public removeFromGroupSelector(groupNb: number, selectorNb: number): void { if (groupNb < 0 || groupNb >= this._groups.length) { return; } var group = this._groups[groupNb]; if (selectorNb < 0 || selectorNb >= group.selectors.length) { return; } group.removeSelector(selectorNb); } /** For a given group position of correct type add a checkbox button * @param groupNb is the number of the group to remove the selector from * @param label is the label for the selector * @param func is the function called when the Selector is checked * @param checked is true when Selector is checked */ public addToGroupCheckbox(groupNb: number, label: string, func = () => { }, checked: boolean = false): void { if (groupNb < 0 || groupNb >= this._groups.length) { return; } var group = this._groups[groupNb]; (<CheckboxGroup>group).addCheckbox(label, func, checked); } /** For a given group position of correct type add a radio button * @param groupNb is the number of the group to remove the selector from * @param label is the label for the selector * @param func is the function called when the Selector is checked * @param checked is true when Selector is checked */ public addToGroupRadio(groupNb: number, label: string, func = () => { }, checked: boolean = false): void { if (groupNb < 0 || groupNb >= this._groups.length) { return; } var group = this._groups[groupNb]; (<RadioGroup>group).addRadio(label, func, checked); } /** * For a given slider group add a slider * @param groupNb is the number of the group to add the slider to * @param label is the label for the Slider * @param func is the function called when the Slider moves * @param unit is a string describing the units used, eg degrees or metres * @param min is the minimum value for the Slider * @param max is the maximum value for the Slider * @param value is the start value for the Slider between min and max * @param onVal is the function used to format the value displayed, eg radians to degrees */ public addToGroupSlider(groupNb: number, label: string, func = () => { }, unit: string = "Units", min: number = 0, max: number = 0, value: number = 0, onVal = (v: number) => { return v | 0; }): void { if (groupNb < 0 || groupNb >= this._groups.length) { return; } var group = this._groups[groupNb]; (<SliderGroup>group).addSlider(label, func, unit, min, max, value, onVal); } }
the_stack
import "./DatasetsSearchPage.scss"; import { connect } from "react-redux"; import { Redirect } from "react-router-dom"; import defined from "helpers/defined"; import Pagination from "Components/Common/Pagination"; import Notification from "Components/Common/Notification"; import MagdaDocumentTitle from "Components/i18n/MagdaDocumentTitle"; import React, { Component } from "react"; import SearchFacets from "Components/Dataset/Search/Facets/SearchFacets"; import SearchResults from "Components/Dataset/Search/Results/SearchResults"; import MatchingStatus from "./Search/Results/MatchingStatus"; import { bindActionCreators } from "redux"; import { fetchSearchResultsIfNeeded, resetDatasetSearch } from "actions/datasetSearchActions"; import queryString from "query-string"; import ProgressBar from "Components/Common/ProgressBar"; import stripFiltersFromQuery from "./Search/stripFiltersFromQuery"; import PropTypes from "prop-types"; import { Location } from "history"; type Props = { location: Location; publishingState: string; }; class Search extends Component<Props & any> { static contextTypes = { router: PropTypes.object }; state: { searchText?: string; }; constructor(props) { super(props); const self: any = this; self.onClickTag = this.onClickTag.bind(this); self.updateQuery = this.updateQuery.bind(this); self.onDismissError = this.onDismissError.bind(this); self.updateSearchText = this.updateSearchText.bind(this); self.onToggleDataset = this.onToggleDataset.bind(this); // it needs to be undefined here, so the default value should be from the url // once this value is set, the value should always be from the user input this.state = { searchText: undefined }; } componentDidMount() { const query = queryString.parse(this.props.location.search); if ( this.props.publishingState && this.props.publishingState.trim() !== "" ) { query["publishingState"] = this.props.publishingState; } this.props.resetDatasetSearch(); this.props.fetchSearchResultsIfNeeded(query); } componentDidUpdate() { const query = queryString.parse(this.props.location.search); if ( this.props.publishingState && this.props.publishingState.trim() !== "" ) { query["publishingState"] = this.props.publishingState; } this.props.fetchSearchResultsIfNeeded(query); } componentWillUnmount() { this.props.resetDatasetSearch(); } onClickTag(tag: string) { this.setState({ searchText: tag }); this.updateSearchText(tag); } /** * update only the search text, remove all facets */ updateSearchText(text: string) { this.updateQuery( stripFiltersFromQuery({ q: text }) ); } /** * query in this case, is one or more of the params * eg: {'q': 'water'} */ updateQuery(query) { this.context.router.history.push({ pathname: this.props.location.pathname, search: queryString.stringify( Object.assign( queryString.parse(this.props.location.search), query ) ) }); } onDismissError() { // remove all current configurations this.updateSearchText(""); this.props.resetDatasetSearch(); } onToggleDataset(datasetIdentifier) { this.updateQuery({ open: datasetIdentifier === queryString.parse(this.props.location.search).open ? "" : datasetIdentifier }); } searchBoxEmpty() { return ( !defined(queryString.parse(this.props.location.search).q) || queryString.parse(this.props.location.search).q.length === 0 ); } /** * counts the number of filters that have active values * this is then appended to the results text on the search page */ filterCount = () => { let count = 0; if (this.props.activePublishers.length > 0) { count++; } if (this.props.activeFormats.length > 0) { count++; } if (this.props.activeRegion.regionId) { count++; } if (this.props.activeDateFrom || this.props.activeDateTo) { count++; } if (count !== 0) { const filterText = count === 1 ? " filter" : " filters"; return " with " + count + filterText; } else { return ""; } }; render() { const searchText = queryString.parse(this.props.location.search).q || ""; const currentPage = +queryString.parse(this.props.location.search).page || 1; const isBlankSearch = searchText === "*" || searchText === ""; const searchResultsPerPage = this.props.configuration .searchResultsPerPage; const publishingState = this.props.publishingState ? this.props.publishingState.trim() : ""; let resultTitle = ""; if (publishingState === "" || publishingState === "*") { resultTitle = "all datasets "; } else if (publishingState !== "published") { resultTitle = `${publishingState} datasets `; } return ( <MagdaDocumentTitle prefixes={[ `Datasets search: ${searchText}`, `Page ${currentPage}` ]} > <div> {this.props.isFetching && <ProgressBar />} <div className="search"> <div className="search__search-body"> <SearchFacets updateQuery={this.updateQuery} location={this.props.location} /> {!this.props.isFetching && !this.props.error && ( <div className="sub-heading"> {" "} {resultTitle} results {this.filterCount()} ( {this.props.hitCount}) </div> )} {!this.props.isFetching && !this.props.error && ( <div> <MatchingStatus datasets={this.props.datasets} strategy={this.props.strategy} /> { // redirect if we came from a 404 error and there is only one result queryString.parse( this.props.location.search ).notfound && this.props.datasets.length === 1 && ( <Redirect to={`/dataset/${encodeURI( this.props.datasets[0] .identifier )}/details`} /> ) } <SearchResults strategy={this.props.strategy} searchResults={this.props.datasets} onClickTag={this.onClickTag} onToggleDataset={this.onToggleDataset} openDataset={ queryString.parse( this.props.location.search ).open } searchText={searchText} isFirstPage={currentPage === 1} suggestionBoxAtEnd={isBlankSearch} /> {this.props.hitCount > searchResultsPerPage && ( <Pagination currentPage={currentPage} maxPage={Math.ceil( this.props.hitCount / searchResultsPerPage )} location={this.props.location} totalItems={this.props.hitCount} /> )} </div> )} {!this.props.isFetching && this.props.error && ( <Notification content={this.props.error} type="error" onDismiss={this.onDismissError} /> )} </div> </div> </div> </MagdaDocumentTitle> ); } } const mapDispatchToProps = (dispatch) => bindActionCreators( { fetchSearchResultsIfNeeded: fetchSearchResultsIfNeeded, resetDatasetSearch: resetDatasetSearch }, dispatch ); function mapStateToProps(state, ownProps) { let { datasetSearch } = state; return { datasets: datasetSearch.datasets, activeFormats: datasetSearch.activeFormats, activePublishers: datasetSearch.activePublishers, activeRegion: datasetSearch.activeRegion, activeDateFrom: datasetSearch.activeDateFrom, activeDateTo: datasetSearch.activeDateTo, hitCount: datasetSearch.hitCount, isFetching: datasetSearch.isFetching, strategy: datasetSearch.strategy, error: datasetSearch.error, freeText: datasetSearch.freeText, strings: state.content.strings, configuration: state.content.configuration }; } export default connect(mapStateToProps, mapDispatchToProps)(Search);
the_stack
import * as util from '../core/util'; import {devicePixelRatio} from '../config'; import { ImagePatternObject } from '../graphic/Pattern'; import CanvasPainter from './Painter'; import { GradientObject, InnerGradientObject } from '../graphic/Gradient'; import { ZRCanvasRenderingContext } from '../core/types'; import Eventful from '../core/Eventful'; import { ElementEventCallback } from '../Element'; import { getCanvasGradient } from './helper'; import { createCanvasPattern } from './graphic'; import Displayable from '../graphic/Displayable'; import BoundingRect from '../core/BoundingRect'; import { REDRAW_BIT } from '../graphic/constants'; function returnFalse() { return false; } function createDom(id: string, painter: CanvasPainter, dpr: number) { const newDom = util.createCanvas(); const width = painter.getWidth(); const height = painter.getHeight(); const newDomStyle = newDom.style; if (newDomStyle) { // In node or some other non-browser environment newDomStyle.position = 'absolute'; newDomStyle.left = '0'; newDomStyle.top = '0'; newDomStyle.width = width + 'px'; newDomStyle.height = height + 'px'; newDom.setAttribute('data-zr-dom-id', id); } newDom.width = width * dpr; newDom.height = height * dpr; return newDom; } export interface LayerConfig { // 每次清空画布的颜色 clearColor?: string | GradientObject | ImagePatternObject // 是否开启动态模糊 motionBlur?: boolean // 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显 lastFrameAlpha?: number }; export default class Layer extends Eventful { id: string dom: HTMLCanvasElement domBack: HTMLCanvasElement ctx: CanvasRenderingContext2D ctxBack: CanvasRenderingContext2D painter: CanvasPainter // Configs /** * 每次清空画布的颜色 */ clearColor: string | GradientObject | ImagePatternObject /** * 是否开启动态模糊 */ motionBlur = false /** * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显 */ lastFrameAlpha = 0.7 /** * Layer dpr */ dpr = 1 /** * Virtual layer will not be inserted into dom. */ virtual = false config = {} incremental = false zlevel = 0 maxRepaintRectCount = 5 private _paintRects: BoundingRect[] __painter: CanvasPainter __dirty = true __firstTimePaint = true __used = false __drawIndex = 0 __startIndex = 0 __endIndex = 0 // indices in the previous frame __prevStartIndex: number = null __prevEndIndex: number = null __builtin__: boolean constructor(id: string | HTMLCanvasElement, painter: CanvasPainter, dpr?: number) { super(); let dom; dpr = dpr || devicePixelRatio; if (typeof id === 'string') { dom = createDom(id, painter, dpr); } // Not using isDom because in node it will return false else if (util.isObject(id)) { dom = id; id = dom.id; } this.id = id as string; this.dom = dom; const domStyle = dom.style; if (domStyle) { // Not in node dom.onselectstart = returnFalse; // 避免页面选中的尴尬 domStyle.webkitUserSelect = 'none'; domStyle.userSelect = 'none'; domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)'; (domStyle as any)['-webkit-touch-callout'] = 'none'; domStyle.padding = '0'; domStyle.margin = '0'; domStyle.borderWidth = '0'; } this.domBack = null; this.ctxBack = null; this.painter = painter; this.config = null; this.dpr = dpr; } getElementCount() { return this.__endIndex - this.__startIndex; } afterBrush() { this.__prevStartIndex = this.__startIndex; this.__prevEndIndex = this.__endIndex; } initContext() { this.ctx = this.dom.getContext('2d'); (this.ctx as ZRCanvasRenderingContext).dpr = this.dpr; } setUnpainted() { this.__firstTimePaint = true; } createBackBuffer() { const dpr = this.dpr; this.domBack = createDom('back-' + this.id, this.painter, dpr); this.ctxBack = this.domBack.getContext('2d'); if (dpr !== 1) { this.ctxBack.scale(dpr, dpr); } } /** * Create repaint list when using dirty rect rendering. * * @param displayList current rendering list * @param prevList last frame rendering list * @return repaint rects. null for the first frame, [] for no element dirty */ createRepaintRects( displayList: Displayable[], prevList: Displayable[], viewWidth: number, viewHeight: number ) { if (this.__firstTimePaint) { this.__firstTimePaint = false; return null; } const mergedRepaintRects: BoundingRect[] = []; const maxRepaintRectCount = this.maxRepaintRectCount; let full = false; const pendingRect = new BoundingRect(0, 0, 0, 0); function addRectToMergePool(rect: BoundingRect) { if (!rect.isFinite() || rect.isZero()) { return; } if (mergedRepaintRects.length === 0) { // First rect, create new merged rect const boundingRect = new BoundingRect(0, 0, 0, 0); boundingRect.copy(rect); mergedRepaintRects.push(boundingRect); } else { let isMerged = false; let minDeltaArea = Infinity; let bestRectToMergeIdx = 0; for (let i = 0; i < mergedRepaintRects.length; ++i) { const mergedRect = mergedRepaintRects[i]; // Merge if has intersection if (mergedRect.intersect(rect)) { const pendingRect = new BoundingRect(0, 0, 0, 0); pendingRect.copy(mergedRect); pendingRect.union(rect); mergedRepaintRects[i] = pendingRect; isMerged = true; break; } else if (full) { // Merged to exists rectangles if full pendingRect.copy(rect); pendingRect.union(mergedRect); const aArea = rect.width * rect.height; const bArea = mergedRect.width * mergedRect.height; const pendingArea = pendingRect.width * pendingRect.height; const deltaArea = pendingArea - aArea - bArea; if (deltaArea < minDeltaArea) { minDeltaArea = deltaArea; bestRectToMergeIdx = i; } } } if (full) { mergedRepaintRects[bestRectToMergeIdx].union(rect); isMerged = true; } if (!isMerged) { // Create new merged rect if cannot merge with current const boundingRect = new BoundingRect(0, 0, 0, 0); boundingRect.copy(rect); mergedRepaintRects.push(boundingRect); } if (!full) { full = mergedRepaintRects.length >= maxRepaintRectCount; } } } /** * Loop the paint list of this frame and get the dirty rects of elements * in this frame. */ for (let i = this.__startIndex; i < this.__endIndex; ++i) { const el = displayList[i]; if (el) { /** * `shouldPaint` is true only when the element is not ignored or * invisible and all its ancestors are not ignored. * `shouldPaint` being true means it will be brushed this frame. * * `__isRendered` being true means the element is currently on * the canvas. * * `__dirty` being true means the element should be brushed this * frame. * * We only need to repaint the element's previous painting rect * if it's currently on the canvas and needs repaint this frame * or not painted this frame. */ const shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true); const prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint) ? el.getPrevPaintRect() : null; if (prevRect) { addRectToMergePool(prevRect); } /** * On the other hand, we only need to paint the current rect * if the element should be brushed this frame and either being * dirty or not rendered before. */ const curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered) ? el.getPaintRect() : null; if (curRect) { addRectToMergePool(curRect); } } } /** * The above loop calculates the dirty rects of elements that are in the * paint list this frame, which does not include those elements removed * in this frame. So we loop the `prevList` to get the removed elements. */ for (let i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) { const el = prevList[i]; /** * Consider the elements whose ancestors are invisible, they should * not be painted and their previous painting rects should be * cleared if they are rendered on the canvas (`__isRendered` being * true). `!shouldPaint` means the element is not brushed in this * frame. * * `!el.__zr` means it's removed from the storage. * * In conclusion, an element needs to repaint the previous painting * rect if and only if it's not painted this frame and was * previously painted on the canvas. */ const shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true); if (el && (!shouldPaint || !el.__zr) && el.__isRendered) { // el was removed const prevRect = el.getPrevPaintRect(); if (prevRect) { addRectToMergePool(prevRect); } } } // Merge intersected rects in the result let hasIntersections; do { hasIntersections = false; for (let i = 0; i < mergedRepaintRects.length;) { if (mergedRepaintRects[i].isZero()) { mergedRepaintRects.splice(i, 1); continue; } for (let j = i + 1; j < mergedRepaintRects.length;) { if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) { hasIntersections = true; mergedRepaintRects[i].union(mergedRepaintRects[j]); mergedRepaintRects.splice(j, 1); } else { j++; } } i++; } } while (hasIntersections); this._paintRects = mergedRepaintRects; return mergedRepaintRects; } /** * Get paint rects for debug usage. */ debugGetPaintRects() { return (this._paintRects || []).slice(); } resize(width: number, height: number) { const dpr = this.dpr; const dom = this.dom; const domStyle = dom.style; const domBack = this.domBack; if (domStyle) { domStyle.width = width + 'px'; domStyle.height = height + 'px'; } dom.width = width * dpr; dom.height = height * dpr; if (domBack) { domBack.width = width * dpr; domBack.height = height * dpr; if (dpr !== 1) { this.ctxBack.scale(dpr, dpr); } } } /** * 清空该层画布 */ clear( clearAll?: boolean, clearColor?: string | GradientObject | ImagePatternObject, repaintRects?: BoundingRect[] ) { const dom = this.dom; const ctx = this.ctx; const width = dom.width; const height = dom.height; clearColor = clearColor || this.clearColor; const haveMotionBLur = this.motionBlur && !clearAll; const lastFrameAlpha = this.lastFrameAlpha; const dpr = this.dpr; const self = this; if (haveMotionBLur) { if (!this.domBack) { this.createBackBuffer(); } this.ctxBack.globalCompositeOperation = 'copy'; this.ctxBack.drawImage( dom, 0, 0, width / dpr, height / dpr ); } const domBack = this.domBack; function doClear(x: number, y: number, width: number, height: number) { ctx.clearRect(x, y, width, height); if (clearColor && clearColor !== 'transparent') { let clearColorGradientOrPattern; // Gradient if (util.isGradientObject(clearColor)) { // Cache canvas gradient clearColorGradientOrPattern = (clearColor as InnerGradientObject).__canvasGradient || getCanvasGradient(ctx, clearColor, { x: 0, y: 0, width: width, height: height }); (clearColor as InnerGradientObject).__canvasGradient = clearColorGradientOrPattern; } // Pattern else if (util.isImagePatternObject(clearColor)) { clearColorGradientOrPattern = createCanvasPattern( ctx, clearColor, { dirty() { // TODO self.setUnpainted(); self.__painter.refresh(); } } ); } ctx.save(); ctx.fillStyle = clearColorGradientOrPattern || (clearColor as string); ctx.fillRect(x, y, width, height); ctx.restore(); } if (haveMotionBLur) { ctx.save(); ctx.globalAlpha = lastFrameAlpha; ctx.drawImage(domBack, x, y, width, height); ctx.restore(); } }; if (!repaintRects || haveMotionBLur) { // Clear the full canvas doClear(0, 0, width, height); } else if (repaintRects.length) { // Clear the repaint areas util.each(repaintRects, rect => { doClear( rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr ); }); } } // Iterface of refresh refresh: (clearColor?: string | GradientObject | ImagePatternObject) => void // Interface of renderToCanvas in getRenderedCanvas renderToCanvas: (ctx: CanvasRenderingContext2D) => void // Events onclick: ElementEventCallback<unknown, this> ondblclick: ElementEventCallback<unknown, this> onmouseover: ElementEventCallback<unknown, this> onmouseout: ElementEventCallback<unknown, this> onmousemove: ElementEventCallback<unknown, this> onmousewheel: ElementEventCallback<unknown, this> onmousedown: ElementEventCallback<unknown, this> onmouseup: ElementEventCallback<unknown, this> oncontextmenu: ElementEventCallback<unknown, this> ondrag: ElementEventCallback<unknown, this> ondragstart: ElementEventCallback<unknown, this> ondragend: ElementEventCallback<unknown, this> ondragenter: ElementEventCallback<unknown, this> ondragleave: ElementEventCallback<unknown, this> ondragover: ElementEventCallback<unknown, this> ondrop: ElementEventCallback<unknown, this> }
the_stack
import React from 'react'; import { Button, createStyles, Divider, IconButton, makeStyles, SvgIcon, Theme, Tooltip, } from '@material-ui/core'; import FormatBoldIcon from '@material-ui/icons/FormatBold'; import FormatItalicIcon from '@material-ui/icons/FormatItalic'; import StrikethroughSIcon from '@material-ui/icons/StrikethroughS'; import FormatListBulletedIcon from '@material-ui/icons/FormatListBulleted'; import FormatListNumberedIcon from '@material-ui/icons/FormatListNumbered'; import FormatUnderlinedIcon from '@material-ui/icons/FormatUnderlined'; import LinkIcon from '@material-ui/icons/Link'; import CodeIcon from '@material-ui/icons/Code'; import FormatAlignLeftIcon from '@material-ui/icons/FormatAlignLeft'; import FormatAlignCenterIcon from '@material-ui/icons/FormatAlignCenter'; import FormatAlignRightIcon from '@material-ui/icons/FormatAlignRight'; import PhotoSizeSelectLargeIcon from '@material-ui/icons/PhotoSizeSelectLarge'; import DeleteIcon from '@material-ui/icons/Delete'; import LinkOffIcon from '@material-ui/icons/LinkOff'; import FunctionsIcon from '@material-ui/icons/Functions'; import AddIcon from '@material-ui/icons/Add'; import OpenInNewIcon from '@material-ui/icons/OpenInNew'; import NewReleasesIcon from '@material-ui/icons/NewReleases'; import InfoIcon from '@material-ui/icons/Info'; import WarningIcon from '@material-ui/icons/Warning'; import ErrorIcon from '@material-ui/icons/Error'; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import SettingsOverscanIcon from '@material-ui/icons/SettingsOverscan'; import LooksOneIcon from '@material-ui/icons/LooksOne'; import ShortTextIcon from '@material-ui/icons/ShortText'; import LocalOfferIcon from '@material-ui/icons/LocalOffer'; import CancelIcon from '@material-ui/icons/Cancel'; import GridIcon from '@material-ui/icons/GridOn'; import KeyboardReturnIcon from '@material-ui/icons/KeyboardReturn'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import LooksOneOutlinedIcon from '@material-ui/icons/LooksOneOutlined'; import classNames from 'classnames'; // import ImageIcon from '@material-ui/icons/Image'; // import TuneIcon from '@material-ui/icons/Tune'; // https://iconify.design/icon-sets/mdi/format-superscript.html function SubscriptIcon(props: any) { return ( <SvgIcon {...props}> <path d="M16 7.41L11.41 12L16 16.59L14.59 18L10 13.41L5.41 18L4 16.59L8.59 12L4 7.41L5.41 6L10 10.59L14.59 6L16 7.41m5.85 13.62h-4.88v-1l.89-.8c.76-.65 1.32-1.19 1.7-1.63c.37-.44.56-.85.57-1.24a.898.898 0 0 0-.27-.7c-.18-.16-.47-.28-.86-.28c-.31 0-.58.06-.84.18l-.66.38l-.45-1.17c.27-.21.59-.39.98-.53s.82-.24 1.29-.24c.78.04 1.38.25 1.78.66c.4.41.62.93.62 1.57c-.01.56-.19 1.08-.54 1.55c-.34.47-.76.92-1.27 1.36l-.64.52v.02h2.58v1.35z" /> </SvgIcon> ); } function SuperscriptIcon(props: any) { return ( <SvgIcon {...props}> <path d="M16 7.41L11.41 12L16 16.59L14.59 18L10 13.41L5.41 18L4 16.59L8.59 12L4 7.41L5.41 6L10 10.59L14.59 6L16 7.41M21.85 9h-4.88V8l.89-.82c.76-.64 1.32-1.18 1.7-1.63c.37-.44.56-.85.57-1.23a.884.884 0 0 0-.27-.7c-.18-.19-.47-.28-.86-.29c-.31.01-.58.07-.84.17l-.66.39l-.45-1.17c.27-.22.59-.39.98-.53S18.85 2 19.32 2c.78 0 1.38.2 1.78.61c.4.39.62.93.62 1.57c-.01.56-.19 1.08-.54 1.55c-.34.48-.76.93-1.27 1.36l-.64.52v.02h2.58V9z" /> </SvgIcon> ); } // Some inspiration from https://icons8.com/icons/set/insert-row function RowAboveIcon(props: any) { return ( <SvgIcon {...props}> <path d="M21,15c-0.7,0.3-1.5,0.5-2.3,0.5c-3.1,0-5.6-2.4-5.8-5.4l-5.4,0V8.7l2.7,0L6.6,5L2.9,8.7l2.8,0v1.4H3.9c-1,0-1.9,0.8-1.9,1.9v6.3c0,1,0.8,1.9,1.9,1.9h15.3c1,0,1.9-0.8,1.9-1.9L21,15z" /> <path d="M18.7,14.4c-2.6,0-4.7-2.1-4.7-4.7S16.1,5,18.7,5s4.7,2.1,4.7,4.7S21.2,14.4,18.7,14.4z M21.5,10.5V8.7h-1.9V6.8h-1.8v1.9h-1.9v1.8h1.9v1.9h1.8v-1.9H21.5z" /> </SvgIcon> ); } function RowBelowIcon(props: any) { return ( <SvgIcon {...props}> <path d="M19.1,5H3.9C2.8,5,2,5.8,2,6.9v6.3c0,1,0.8,1.9,1.9,1.9h1.8v1.4l-2.8,0l3.6,3.7l3.6-3.7l-2.7,0V15l5.4,0c0.2-3,2.7-5.4,5.8-5.4c0.8,0,1.6,0.2,2.3,0.5l0-3.2C21,5.8,20.2,5,19.1,5z" /> <path d="M23.3,15.4c0,2.6-2.1,4.7-4.7,4.7S14,17.9,14,15.4s2.1-4.7,4.7-4.7S23.3,12.8,23.3,15.4z M19.6,14.6v-1.9h-1.8v1.9h-1.9v1.8h1.9v1.9h1.8v-1.9h1.9v-1.8H19.6z" /> </SvgIcon> ); } function RowDelete(props: any) { return ( <SvgIcon {...props}> <path d="M10.9,12.1l-1.2,1.2l1.2,1.2l1.2-1.2l1.2,1.2l1.2-1.2l-1.2-1.2l1.2-1.2l-1.2-1.2l-1.2,1.2l-1.2-1.2l-1.2,1.2L10.9,12.1z" /> <path d="M2.6,15.3V8.9c0-1,0.8-1.8,1.8-1.8h15.4c1,0,1.8,0.8,1.8,1.8v6.4c0,1-0.8,1.8-1.8,1.8H4.4C3.4,17.1,2.6,16.3,2.6,15.3zM15.9,12.1c0-2.1-1.7-3.8-3.8-3.8S8.2,10,8.2,12.1s1.7,3.8,3.8,3.8S15.9,14.2,15.9,12.1z" /> </SvgIcon> ); } function ColLeftIcon(props: any) { return ( <SvgIcon {...props}> <path d="M8.8,10.1V7.4h1.4l0,5.4c3,0.2,5.4,2.7,5.4,5.8c0,0.8-0.2,1.6-0.5,2.3h3.2c1.1,0,1.9-0.9,1.9-1.9V3.7c0-1.1-0.9-1.9-1.9-1.9h-6.2c-1.1,0-1.9,0.9-1.9,1.9v1.9H8.8V2.8L5.1,6.4L8.8,10.1z" /> <path d="M9.8,23.2c-2.6,0-4.7-2.1-4.7-4.7s2.1-4.7,4.7-4.7s4.7,2.1,4.7,4.7S12.4,23.2,9.8,23.2z M10.6,19.4h1.9v-1.8h-1.9v-1.9H8.8v1.9H6.9v1.8h1.9v1.9h1.8V19.4z" /> </SvgIcon> ); } function ColRightIcon(props: any) { return ( <SvgIcon {...props}> <path d="M20.2,6.4l-3.7-3.6l0,2.8h-1.4V3.7c0-1-0.8-1.9-1.9-1.9H7c-1,0-1.9,0.8-1.9,1.9V19c0,1,0.8,1.9,1.9,1.9l3.2,0c-0.3-0.7-0.5-1.5-0.5-2.3c0-3.1,2.4-5.6,5.4-5.8l0-5.4h1.4l0,2.7L20.2,6.4z" /> <path d="M10.8,18.5c0-2.6,2.1-4.7,4.7-4.7s4.7,2.1,4.7,4.7s-2.1,4.7-4.7,4.7S10.8,21.1,10.8,18.5z M14.7,21.3h1.8v-1.9h1.9v-1.8h-1.9v-1.9h-1.8v1.9h-1.9v1.8h1.9V21.3z" /> </SvgIcon> ); } function ColDelete(props: any) { return ( <SvgIcon {...props}> <path d="M12.1,13.2l1.2,1.2l1.2-1.2l-1.2-1.2l1.2-1.2l-1.2-1.2l-1.2,1.2l-1.2-1.2l-1.2,1.2l1.2,1.2l-1.2,1.2l1.2,1.2L12.1,13.2z" /> <path d="M15.3,21.6H8.8c-1,0-1.8-0.8-1.8-1.8V4.4c0-1,0.8-1.8,1.8-1.8h6.4c1,0,1.8,0.8,1.8,1.8v15.4C17.1,20.8,16.3,21.6,15.3,21.6zM12.1,8.3c-2.1,0-3.8,1.7-3.8,3.8s1.7,3.8,3.8,3.8s3.8-1.7,3.8-3.8S14.2,8.3,12.1,8.3z" /> </SvgIcon> ); } function BracketsIcon(props: any) { return ( <SvgIcon {...props}> <path d="M15 4v2h3v12h-3v2h5V4M4 4v16h5v-2H6V6h3V4H4z" /> </SvgIcon> ); } const mac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false; const deMacify = (title: string | React.ReactElement) => mac || typeof title !== 'string' ? title : title.replace('⌘', 'Ctrl-'); const icons = { table: { help: 'Create Table', Icon: GridIcon }, cancel: { help: 'Cancel', Icon: CancelIcon }, enterSave: { help: 'Save', Icon: KeyboardReturnIcon }, bold: { help: 'Bold ⌘B', Icon: FormatBoldIcon }, italic: { help: 'Italic ⌘I', Icon: FormatItalicIcon }, code: { help: 'Code ⌘⇧C', Icon: CodeIcon }, subscript: { help: 'Subscript', Icon: SubscriptIcon }, superscript: { help: 'Superscript', Icon: SuperscriptIcon }, strikethrough: { help: 'Strikethrough', Icon: StrikethroughSIcon }, underline: { help: 'Underline ⌘U', Icon: FormatUnderlinedIcon }, ul: { help: 'Bullet Point List ⌘⇧8', Icon: FormatListBulletedIcon }, ol: { help: 'Ordered List ⌘⇧7', Icon: FormatListNumberedIcon }, link: { help: 'Link ⌘K', Icon: LinkIcon }, left: { help: 'Align Left', Icon: FormatAlignLeftIcon }, center: { help: 'Align Center', Icon: FormatAlignCenterIcon }, right: { help: 'Align Right', Icon: FormatAlignRightIcon }, imageWidth: { help: 'Adjust Width', Icon: PhotoSizeSelectLargeIcon }, remove: { help: 'Remove', Icon: DeleteIcon }, unlink: { help: 'Unlink', Icon: LinkOffIcon }, math: { help: 'Inline Math', Icon: FunctionsIcon }, more: { help: 'Insert', Icon: AddIcon }, expand: { help: 'More Options', Icon: ExpandMoreIcon }, open: { help: 'Open in New Tab', Icon: OpenInNewIcon }, brackets: { help: 'Toggle Brackets', Icon: BracketsIcon }, active: { help: 'Attention', Icon: NewReleasesIcon }, success: { help: 'Success', Icon: CheckCircleIcon }, info: { help: 'Information', Icon: InfoIcon }, warning: { help: 'Warning', Icon: WarningIcon }, danger: { help: 'Danger', Icon: ErrorIcon }, lift: { help: 'Remove from Container', Icon: SettingsOverscanIcon }, numbered: { help: 'Toggle Numbering', Icon: LooksOneIcon }, caption: { help: 'Show/Hide Caption', Icon: ShortTextIcon }, label: { help: 'Reference ID', Icon: LocalOfferIcon }, rowAbove: { help: 'Insert Row Above', Icon: RowAboveIcon }, rowBelow: { help: 'Insert Row Below', Icon: RowBelowIcon }, rowDelete: { help: 'Delete Row', Icon: RowDelete }, colLeft: { help: 'Insert Column Left', Icon: ColLeftIcon }, colRight: { help: 'Insert Column Right', Icon: ColRightIcon }, colDelete: { help: 'Delete Column', Icon: ColDelete }, lineNumbers: { help: 'Toggle Line Numbers', Icon: LooksOneOutlinedIcon }, }; export type IconTypes = keyof typeof icons | 'divider'; const useStyles = makeStyles((theme: Theme) => createStyles({ root: { color: theme.palette.text.secondary, display: 'inline-block', '& button:hover': { backgroundColor: 'transparent', }, '& button.active svg, button:hover svg': { backgroundColor: theme.palette.text.secondary, color: 'white', }, '& button:hover svg.dangerous, svg.error': { backgroundColor: 'transparent', color: theme.palette.error.main, }, '& svg': { margin: 4, padding: 2, borderRadius: 4, }, }, hr: { margin: theme.spacing(0, 0.5), height: 20, }, button: { margin: theme.spacing(0, 0.5), textTransform: 'none', }, }), ); type Props = { kind: IconTypes; disabled?: boolean; active?: boolean; dangerous?: boolean; error?: boolean; title?: string; text?: string; onClick?: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void; }; const MenuIcon: React.FC<Props> = (props) => { const { kind, active, dangerous, error, disabled, onClick, title, text } = props; const classes = useStyles(); if (kind === 'divider') return <Divider className={classes.hr} orientation="vertical" />; const { help, Icon } = icons[kind]; if (text) { return ( <Button disabled={disabled} className={classes.button} size="small" onClickCapture={(e) => { e.stopPropagation(); e.preventDefault(); onClick?.(e); }} disableRipple > {text} <Icon fontSize="small" className={classNames({ dangerous, error })} /> </Button> ); } return ( <Tooltip title={title || deMacify(help)}> <div className={classes.root}> <IconButton disabled={disabled} className={active ? 'active' : ''} size="small" onClickCapture={(e) => { e.stopPropagation(); e.preventDefault(); onClick?.(e); }} disableRipple > <Icon fontSize="small" className={classNames({ dangerous, error })} /> </IconButton> </div> </Tooltip> ); }; MenuIcon.defaultProps = { disabled: false, active: false, dangerous: false, error: false, onClick: undefined, title: undefined, text: undefined, }; export default React.memo(MenuIcon);
the_stack
import axios from 'axios'; import path from 'path'; import fs from 'fs-extra'; import readlineSync from 'readline-sync'; import YAML from 'yaml'; import { isPlainObject, padEnd, sortBy, upperFirst } from 'lodash'; import { EOL } from 'os'; import { logger } from './FSHLogger'; import { loadDependency, loadSupplementalFHIRPackage, FHIRDefinitions } from '../fhirdefs'; import { FSHTank, RawFSH, importText, ensureConfiguration, importConfiguration, loadConfigurationFromIgResource } from '../import'; import { Package } from '../export'; import { Configuration } from '../fshtypes'; const EXT_PKG_TO_FHIR_PKG_MAP: { [key: string]: string } = { 'hl7.fhir.extensions.r2': 'hl7.fhir.r2.core#1.0.2', 'hl7.fhir.extensions.r3': 'hl7.fhir.r3.core#3.0.2', 'hl7.fhir.extensions.r4': 'hl7.fhir.r4.core#4.0.1', 'hl7.fhir.extensions.r5': 'hl7.fhir.r5.core#current' }; export function isSupportedFHIRVersion(version: string): boolean { // For now, allow current or any 4.x/5.x version of FHIR except 4.0.0. This is a quick check; not a guarantee. If a user passes // in an invalid version that passes this test (e.g., 4.99.0), it is still expected to fail when we load dependencies. return version !== '4.0.0' && /^(current|[45]\.\d+.\d+(-.+)?)$/.test(version); } export function ensureInputDir(input: string): string { // If no input folder is specified, set default to current directory if (!input) { input = '.'; logger.info('path-to-fsh-defs defaulted to current working directory'); } return input; } export function hasFshFiles(path: string): boolean { try { fs.statSync(path); const files = getFilesRecursive(path).filter(file => file.endsWith('.fsh')); return files.length > 0; } catch (error) { return false; } } export function findInputDir(input: string): string { const originalInput = input; const inputFshSubdirectoryPath = path.join(originalInput, 'input', 'fsh'); const fshSubdirectoryPath = path.join(originalInput, 'fsh'); const rootIgDataPath = path.join(originalInput, 'ig-data'); const currentTankWithNoFsh = !fs.existsSync(inputFshSubdirectoryPath) && !fs.existsSync(fshSubdirectoryPath) && !fs.existsSync(rootIgDataPath) && !hasFshFiles(originalInput); // Use input/fsh/ subdirectory if not already specified and present // or when in the current tank configuration without FSH files if (fs.existsSync(inputFshSubdirectoryPath) || currentTankWithNoFsh) { input = path.join(originalInput, 'input', 'fsh'); } // TODO: Error about unsupported features. Remove when message no longer needed. // Use fsh/ subdirectory if not already specified and present if (!fs.existsSync(inputFshSubdirectoryPath) && !currentTankWithNoFsh) { let msg = '\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n'; if (fs.existsSync(fshSubdirectoryPath)) { msg += '\nSUSHI detected a "fsh" directory that will be used in the input path.\n' + 'Use of this folder is NO LONGER SUPPORTED.\n' + 'To migrate to the new folder structure, make the following changes:\n' + ` - move fsh${path.sep}config.yaml to .${path.sep}sushi-config.yaml\n` + ` - move fsh${path.sep}*.fsh files to .${path.sep}input${path.sep}fsh${path.sep}*.fsh\n`; if (fs.existsSync(path.join(input, 'fsh', 'ig-data'))) { msg += ` - move fsh${path.sep}ig-data${path.sep}* files and folders to .${path.sep}*\n`; } } else { msg += '\nSUSHI has adopted a new folder structure for FSH tanks (a.k.a. SUSHI projects).\n' + 'Support for other folder structures is NO LONGER SUPPORTED.\n' + 'To migrate to the new folder structure, make the following changes:\n' + ` - rename .${path.sep}config.yaml to .${path.sep}sushi-config.yaml\n` + ` - move .${path.sep}*.fsh files to .${path.sep}input${path.sep}fsh${path.sep}*.fsh\n`; if (fs.existsSync(path.join(input, 'ig-data'))) { msg += ` - move .${path.sep}ig-data${path.sep}* files and folders to .${path.sep}*\n`; } } if (!fs.existsSync(path.join(input, 'ig-data', 'ig.ini'))) { msg += ` - if you used the "template" property in your config, remove it and manage .${path.sep}ig.ini directly\n`; } if (!fs.existsSync(path.join(input, 'ig-data', 'package-list.json'))) { msg += ` - if you used the "history" property in your config, remove it and manage .${path.sep}package-list.json directly\n`; } msg += ' - ensure your .gitignore file is not configured to ignore the sources in their new locations\n' + ' - add /fsh-generated to your .gitignore file to prevent SUSHI output from being checked into source control\n\n' + `NOTE: After you make these changes, the default output folder for SUSHI will change to .${path.sep}fsh-generated.\n\n` + 'For detailed migration instructions, see: https://fshschool.org/docs/sushi/migration/\n\n'; logger.error(msg); } return input; } export function ensureOutputDir(input: string, output: string): string { let outDir = output; if (!output) { // Default output is the parent folder of the input/fsh folder outDir = path.join(input, '..', '..'); logger.info(`No output path specified. Output to ${outDir}`); } fs.ensureDirSync(outDir); // If the outDir contains a fsh-generated folder, we ensure that folder is empty const fshGeneratedFolder = path.join(outDir, 'fsh-generated'); if (fs.existsSync(fshGeneratedFolder)) { try { fs.emptyDirSync(fshGeneratedFolder); } catch (e) { logger.error( `Unable to empty existing fsh-generated folder because of the following error: ${e.message}` ); } } return outDir; } export function readConfig(input: string): Configuration { const configPath = ensureConfiguration(input); let config: Configuration; if (configPath == null || !fs.existsSync(configPath)) { config = loadConfigurationFromIgResource(input); } else { const configYaml = fs.readFileSync(configPath, 'utf8'); config = importConfiguration(configYaml, configPath); } if (!config) { logger.error( `No sushi-config.yaml in ${input} folder, and no configuration could` + ' be extracted from an ImplementationGuide resource.' ); throw Error; } if (!config.fhirVersion.some(v => isSupportedFHIRVersion(v))) { logger.error( `The ${path.basename(config.filePath)} must specify a supported version of FHIR. Be sure to` + ` add "fhirVersion: 4.0.1" (or 4.x.y, 5.0.0-snapshot1, etc., as appropriate) to the ${path.basename( config.filePath )} file.` ); throw Error; } return config; } export async function loadExternalDependencies( defs: FHIRDefinitions, config: Configuration ): Promise<void> { // Add FHIR to the dependencies so it is loaded const dependencies = (config.dependencies ?? []).slice(); // slice so we don't modify actual config; const fhirVersion = config.fhirVersion.find(v => isSupportedFHIRVersion(v)); let fhirPackageId: string; let prerelease = false; if (/^4\.0\./.test(fhirVersion)) { fhirPackageId = 'hl7.fhir.r4.core'; } else if (/^(4\.1\.|4\.3.\d+-)/.test(fhirVersion)) { fhirPackageId = 'hl7.fhir.r4b.core'; prerelease = true; } else if (/^4\.3.\d+$/.test(fhirVersion)) { fhirPackageId = 'hl7.fhir.r4b.core'; } else if (/^5\.0.\d+$/.test(fhirVersion)) { fhirPackageId = 'hl7.fhir.r5.core'; } else { fhirPackageId = 'hl7.fhir.r5.core'; prerelease = true; } if (prerelease) { logger.warn( 'SUSHI support for pre-release versions of FHIR is experimental. Use at your own risk!' ); } dependencies.push({ packageId: fhirPackageId, version: fhirVersion }); // Load dependencies const promises = dependencies.map(dep => { if (dep.version == null) { logger.error( `Failed to load ${dep.packageId}: No version specified. To specify the version in your ` + `${path.basename(config.filePath)}, either use the simple dependency format:\n\n` + 'dependencies:\n' + ` ${dep.packageId}: current\n\n` + 'or use the detailed dependency format to specify other properties as well:\n\n' + 'dependencies:\n' + ` ${dep.packageId}:\n` + ` uri: ${dep.uri ?? 'http://my-fhir-ig.org/ImplementationGuide/123'}\n` + ' version: current' ); return Promise.resolve(); } else if (EXT_PKG_TO_FHIR_PKG_MAP[dep.packageId]) { // It is a special "virtual" FHIR extensions package indicating we need to load supplemental // FHIR versions to support "implied extensions". if (dep.version !== fhirVersion) { logger.warn( `Incorrect package version: ${dep.packageId}#${dep.version}. FHIR extensions packages ` + "should use the same version as the implementation guide's fhirVersion. Version " + `${fhirVersion} will be used instead. Update the dependency version in ` + 'sushi-config.yaml to eliminate this warning.' ); } logger.info( `Loading supplemental version of FHIR to support extensions from ${dep.packageId}` ); return loadSupplementalFHIRPackage(EXT_PKG_TO_FHIR_PKG_MAP[dep.packageId], defs); } else { return loadDependency(dep.packageId, dep.version, defs).catch(e => { let message = `Failed to load ${dep.packageId}#${dep.version}: ${e.message}`; if (/certificate/.test(e.message)) { message += '\n\nSometimes this error occurs in corporate or educational environments that use proxies and/or SSL ' + 'inspection.\nTroubleshooting tips:\n' + ' 1. If a non-proxied network is available, consider connecting to that network instead.\n' + ' 2. Set NODE_EXTRA_CA_CERTS as described at https://bit.ly/3ghJqJZ (RECOMMENDED).\n' + ' 3. Disable certificate validation as described at https://bit.ly/3syjzm7 (NOT RECOMMENDED).\n'; } logger.error(message); }); } }); return Promise.all(promises).then(() => {}); } export function getRawFSHes(input: string): RawFSH[] { let files: string[]; try { fs.statSync(input); files = getFilesRecursive(input); } catch { logger.error('Invalid path to FSH definition folder.'); throw Error; } const rawFSHes = files .filter(file => file.endsWith('.fsh')) .map(file => { const filePath = path.resolve(file); const fileContent = fs.readFileSync(filePath, 'utf8'); return new RawFSH(fileContent, filePath); }); return rawFSHes; } export function fillTank(rawFSHes: RawFSH[], config: Configuration): FSHTank { logger.info('Importing FSH text...'); const docs = importText(rawFSHes); return new FSHTank(docs, config); } export function checkNullValuesOnArray(resource: any, parentName = '', priorPath = ''): void { const resourceName = parentName ? parentName : resource.id ?? resource.name; for (const propertyKey in resource) { const property = resource[propertyKey]; const currentPath = !priorPath ? propertyKey : priorPath.concat(`.${propertyKey}`); // If a property's key begins with "_", we'll want to ignore null values on it's top level // but still check any nested objects for null values if (propertyKey.startsWith('_')) { if (isPlainObject(property)) { // If we encounter an object property, we'll want to check its properties as well checkNullValuesOnArray(property, resourceName, currentPath); } if (Array.isArray(property)) { property.forEach((element: any, index: number) => { if (isPlainObject(element)) { // If we encounter an object property, we'll want to check its properties as well checkNullValuesOnArray(element, resourceName, `${currentPath}[${index}]`); } }); } } else { if (isPlainObject(property)) { // If we encounter an object property, we'll want to check its properties as well checkNullValuesOnArray(property, resourceName, currentPath); } if (Array.isArray(property)) { const nullIndexes: number[] = []; property.forEach((element: any, index: number) => { if (element === null) nullIndexes.push(index); if (isPlainObject(element)) { // If we encounter an object property, we'll want to check its properties as well checkNullValuesOnArray(element, resourceName, `${currentPath}[${index}]`); } }); if (nullIndexes.length > 0) { logger.warn( `The array '${currentPath}' in ${resourceName} is missing values at the following indices: ${nullIndexes}` ); } } } } } export function writeFHIRResources( outDir: string, outPackage: Package, defs: FHIRDefinitions, snapshot: boolean ) { logger.info('Exporting FHIR resources as JSON...'); let count = 0; const predefinedResources = defs.allPredefinedResources(); const writeResources = ( resources: { getFileName: () => string; toJSON: (snapshot: boolean) => any; url?: string; id?: string; resourceType?: string; }[] ) => { const exportDir = path.join(outDir, 'fsh-generated', 'resources'); resources.forEach(resource => { if ( !predefinedResources.find( predef => predef.url === resource.url && predef.resourceType === resource.resourceType && predef.id === resource.id ) ) { checkNullValuesOnArray(resource); fs.outputJSONSync(path.join(exportDir, resource.getFileName()), resource.toJSON(snapshot), { spaces: 2 }); count++; } else { logger.error( `Ignoring FSH definition for ${ resource.url ?? `${resource.resourceType}/${resource.id}` } since it duplicates existing pre-defined resource. ` + 'To use the FSH definition, remove the conflicting file from "input". ' + 'If you do want the FSH definition to be ignored, please comment the definition out ' + 'to remove this error.' ); } }); }; writeResources(outPackage.profiles); writeResources(outPackage.extensions); writeResources(outPackage.logicals); // WARNING: While custom resources are written to disk, the IG Publisher does not // accept newly defined resources. However, it is configured to automatically // search the fsh-generated directory for StructureDefinitions rather than using // the StructureDefinitions defined in the exported implementation guide. So, be // aware that the IG Publisher will attempt to process custom resources. // NOTE: To mitigate against this, the parameter 'autoload-resources = false' is // injected automatically into the IG array pf parameters if the parameter was // not already defined and only if the custom resources were generated by Sushi. writeResources(outPackage.resources); writeResources([...outPackage.valueSets, ...outPackage.codeSystems]); // Filter out inline instances writeResources(outPackage.instances.filter(i => i._instanceMeta.usage !== 'Inline')); logger.info(`Exported ${count} FHIR resources as JSON.`); } export function writePreprocessedFSH(outDir: string, inDir: string, tank: FSHTank) { const preprocessedPath = path.join(outDir, '_preprocessed'); fs.ensureDirSync(preprocessedPath); // Because this is the FSH that exists after processing, some entities from the original FSH are gone. // Specifically, RuleSets have already been applied. // Aliases have already been resolved for most cases, but since they may still // be used in a slice name, they are included. // TODO: Add Resources and Logicals once they are being imported and stored in docs tank.docs.forEach(doc => { let fileContent = ''; // First, get all Aliases. They don't have source information. if (doc.aliases.size > 0) { doc.aliases.forEach((url, alias) => { fileContent += `Alias: ${alias} = ${url}${EOL}`; }); fileContent += EOL; } // Then, get all other applicable entities. They will have source information. const entities = [ ...doc.profiles.values(), ...doc.extensions.values(), ...doc.logicals.values(), ...doc.resources.values(), ...doc.instances.values(), ...doc.valueSets.values(), ...doc.codeSystems.values(), ...doc.invariants.values(), ...doc.mappings.values() ]; // Sort entities by original line number, then write them out. sortBy(entities, 'sourceInfo.location.startLine').forEach(entity => { fileContent += `// Originally defined on lines ${entity.sourceInfo.location.startLine} - ${entity.sourceInfo.location.endLine}${EOL}`; fileContent += `${entity.toFSH()}${EOL}${EOL}`; }); if (fileContent.length === 0) { fileContent = '// This file has no content after preprocessing.'; } const outPath = path.relative(inDir, doc.file); fs.ensureFileSync(path.join(preprocessedPath, outPath)); fs.writeFileSync(path.join(preprocessedPath, outPath), fileContent); }); logger.info(`Wrote preprocessed FSH to ${preprocessedPath}`); } /** * Initializes an empty sample FSH within a user specified subdirectory of the current working directory */ export async function init(): Promise<void> { console.log( '\n╭───────────────────────────────────────────────────────────╮\n' + '│ This interactive tool will use your answers to create a │\n' + "│ working SUSHI project configured with your project's │\n" + '│ basic information. │\n' + '╰───────────────────────────────────────────────────────────╯\n' ); const configDoc = YAML.parseDocument( fs.readFileSync(path.join(__dirname, 'init-project', 'sushi-config.yaml'), 'utf-8') ); // Accept user input for certain fields ['name', 'id', 'canonical', 'status', 'version'].forEach(field => { const userValue = readlineSync.question( `${upperFirst(field)} (Default: ${configDoc.get(field)}): ` ); if (userValue) { if (field === 'status') { const node = YAML.createNode(userValue); node.comment = ' draft | active | retired | unknown'; configDoc.set(field, node); } else { configDoc.set(field, userValue); } } }); // And for nested publisher fields ['name', 'url'].forEach(field => { const userValue = readlineSync.question( `Publisher ${upperFirst(field)} (Default: ${configDoc.get('publisher').get(field)}): ` ); if (userValue) { configDoc.get('publisher').set(field, userValue); } }); // Ensure copyrightYear is accurate configDoc.set('copyrightYear', `${new Date().getFullYear()}+`); const projectName = configDoc.get('name'); // Write init directory out, including user made sushi-config.yaml, files in utils/init-project, and build scripts from ig/files const outputDir = path.resolve('.', projectName); const initProjectDir = path.join(__dirname, 'init-project'); if (!readlineSync.keyInYN(`Initialize SUSHI project in ${outputDir}?`)) { console.log('\nAborting Initialization.\n'); return; } // Add index.md content, updating to reflect the user given name const indexPageContent = fs .readFileSync(path.join(initProjectDir, 'index.md'), 'utf-8') .replace('ExampleIG', projectName); fs.ensureDirSync(path.join(outputDir, 'input', 'pagecontent')); fs.writeFileSync(path.join(outputDir, 'input', 'pagecontent', 'index.md'), indexPageContent); // Add ig.ini, updating to reflect the user given id const iniContent = fs .readFileSync(path.join(initProjectDir, 'ig.ini'), 'utf-8') .replace('fhir.example', configDoc.get('id')); fs.writeFileSync(path.join(outputDir, 'ig.ini'), iniContent); // Add the config fs.writeFileSync(path.join(outputDir, 'sushi-config.yaml'), configDoc.toString()); // Copy over remaining static files fs.ensureDirSync(path.join(outputDir, 'input', 'fsh')); fs.copyFileSync( path.join(initProjectDir, 'patient.fsh'), path.join(outputDir, 'input', 'fsh', 'patient.fsh') ); fs.copyFileSync( path.join(initProjectDir, 'init-gitignore.txt'), path.join(outputDir, '.gitignore') ); fs.copyFileSync( path.join(initProjectDir, 'ignoreWarnings.txt'), path.join(outputDir, 'input', 'ignoreWarnings.txt') ); // Add the _updatePublisher, _genonce, and _gencontinuous scripts console.log('Downloading publisher scripts from https://github.com/HL7/ig-publisher-scripts'); for (const script of [ '_genonce.bat', '_genonce.sh', '_updatePublisher.bat', '_updatePublisher.sh' ]) { const url = `http://raw.githubusercontent.com/HL7/ig-publisher-scripts/main/${script}`; try { const res = await axios.get(url); fs.writeFileSync(path.join(outputDir, script), res.data); if (script.endsWith('.sh')) { fs.chmodSync(path.join(outputDir, script), 0o755); } } catch (e) { logger.error(`Unable to download ${script} from ${url}: ${e.message}`); } } const maxLength = 32; const printName = projectName.length > maxLength ? projectName.slice(0, maxLength - 3) + '...' : projectName; console.log( '\n╭───────────────────────────────────────────────────────────╮\n' + `│ Project initialized at: ./${padEnd(printName, maxLength)}│\n` + '├───────────────────────────────────────────────────────────┤\n' + '│ Now try this: │\n' + '│ │\n' + `│ > cd ${padEnd(printName, maxLength + 21)}│\n` + '│ > sushi . │\n' + '│ │\n' + '│ For guidance on project structure and configuration see │\n' + '│ the SUSHI documentation: https://fshschool.org/docs/sushi │\n' + '╰───────────────────────────────────────────────────────────╯\n' ); } export function getFilesRecursive(dir: string): string[] { // always return absolute paths const absPath = path.resolve(dir); try { if (fs.statSync(absPath).isDirectory()) { const descendants = fs .readdirSync(absPath, 'utf8') .map(f => getFilesRecursive(path.join(absPath, f))); return [].concat(...descendants); } else { return [absPath]; } } catch { return []; } }
the_stack
import * as os from "os"; ("use strict"); import { spawn } from "process-promises"; import { CancellationToken, DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider, FormattingOptions, OnTypeFormattingEditProvider, OutputChannel, Range, TextDocument, TextEdit, window, workspace, WorkspaceConfiguration, Position, extensions } from "vscode"; import * as jsesc from "js-string-escape"; // import * as jsesc from "jsesc"; import { Utils } from "../utils/utils"; import { extname } from "path"; import * as path from "path"; interface IComment { location: number; // character location in the range comment: string; } interface ITermInfo { startLine: number; startChar: number; isValid: boolean; termStr: string; comments: IComment[]; endLine?: number; endChar?: number; charsSofar?: number; } export default class PrologDocumentFormatter implements DocumentRangeFormattingEditProvider, DocumentFormattingEditProvider, OnTypeFormattingEditProvider { private _section: WorkspaceConfiguration; private _tabSize: number; private _insertSpaces: boolean; private _tabDistance: number; private _executable: string; private _args: string[]; private _outputChannel: OutputChannel; private _textEdits: TextEdit[] = []; private _currentTermInfo: ITermInfo = null; private _startChars: number; constructor() { this._section = workspace.getConfiguration("prolog"); this._tabSize = this._section.get("format.tabSize", 4); this._insertSpaces = this._section.get("format.insertSpaces", true); this._tabDistance = this._insertSpaces ? 0 : this._tabSize; this._executable = this._section.get("executablePath", "swipl"); this._args = []; this._outputChannel = window.createOutputChannel("PrologFormatter"); } private getClauseHeadStart(doc: TextDocument, line: number): Position { const headReg = /^\s*[\s\S]+?(?=:-|-->)/; const lineTxt = doc.lineAt(line).text; let match = lineTxt.match(headReg); if (match) { let firstNonSpcIndex = lineTxt.match(/[^\s]/).index; return new Position(line, firstNonSpcIndex); } line--; if (line < 0) { line = 0; return new Position(0, 0); } return this.getClauseHeadStart(doc, line); } private getClauseEnd(doc: TextDocument, line: number): Position { let lineTxt = doc.lineAt(line).text; let dotIndex = lineTxt.indexOf("."); while (dotIndex > -1) { if (this.isClauseEndDot(doc, new Position(line, dotIndex))) { return new Position(line, dotIndex + 1); } dotIndex = lineTxt.indexOf(".", dotIndex + 1); } line++; if (line === doc.lineCount) { line--; return new Position(line, lineTxt.length); } return this.getClauseEnd(doc, line); } private isClauseEndDot(doc: TextDocument, pos: Position): boolean { const txt = doc.getText(); const offset = doc.offsetAt(pos); const subtxt = txt .slice(0, offset + 1) .replace(/\/\*[\s\S]*?\*\//g, "") .replace(/\\'/g, "") .replace(/\\"/g, "") .replace(/"[^\"]*?"/g, "") .replace(/'[^\']*?'/g, "") .replace(/%.*\n/g, ""); const open = subtxt.lastIndexOf("/*"); const close = subtxt.lastIndexOf("*/"); return ( txt.charAt(offset - 1) !== "." && txt.charAt(offset + 1) !== "." && (txt.charAt(offset + 1) === "" || /^\W/.test(txt.slice(offset + 1, offset + 2))) && subtxt.indexOf("'") === -1 && subtxt.indexOf('"') === -1 && !/%[^\n]*$/.test(subtxt) && (open === -1 || open < close) ); } private validRange(doc: TextDocument, initRange: Range): Range { const docTxt = doc.getText(); let end = docTxt.indexOf(".", doc.offsetAt(initRange.end) - 1); while (end > -1) { if (this.isClauseEndDot(doc, doc.positionAt(end))) { break; } end = docTxt.indexOf(".", end + 1); } if (end === -1) { end = docTxt.length - 1; } let endPos = doc.positionAt(end + 1); let start = docTxt.slice(0, doc.offsetAt(initRange.start)).lastIndexOf("."); while (start > -1) { if (this.isClauseEndDot(doc, doc.positionAt(start))) { break; } start = docTxt.slice(0, start - 1).lastIndexOf("."); } if (start === -1) { start = 0; } if (start > 0) { let nonTermStart = 0; let re: RegExp = /^\s+|^%.*\n|^\/\*.*?\*\//; let txt = docTxt.slice(start + 1); let match = txt.match(re); while (match) { nonTermStart += match[0].length; match = txt.slice(nonTermStart).match(re); } start += nonTermStart; } let startPos = doc.positionAt(start === 0 ? 0 : start + 1); return startPos && endPos ? new Range(startPos, endPos) : null; } public provideDocumentRangeFormattingEdits( doc: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken ): TextEdit[] | Thenable<TextEdit[]> { return this.getTextEdits(doc, this.validRange(doc, range)); } public provideDocumentFormattingEdits( doc: TextDocument ): TextEdit[] | Thenable<TextEdit[]> { return this.getTextEdits( doc, new Range( 0, 0, doc.lineCount - 1, doc.lineAt(doc.lineCount - 1).text.length ) ); } public provideOnTypeFormattingEdits( doc: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken ): TextEdit[] | Thenable<TextEdit[]> { if ( ch === "." && doc.languageId === "prolog" && this.isClauseEndDot( doc, new Position(position.line, position.character - 1) ) ) { let range = new Range( position.line, 0, position.line, position.character - 1 ); return this.getTextEdits(doc, this.validRange(doc, range)); } else { return []; } } private outputMsg(msg: string) { this._outputChannel.append(msg); this._outputChannel.show(true); } private async getTextEdits(doc: TextDocument, range: Range) { await this.getFormattedCode(doc, range); return this._textEdits; } private async getFormattedCode(doc: TextDocument, range: Range) { this._textEdits = []; this._currentTermInfo = null; let docText = jsesc(doc.getText()); let rangeTxt = jsesc(doc.getText(range)); let goals: string; switch (Utils.DIALECT) { case "swi": this._args = ["--nodebug", "-q"]; let pfile = jsesc(path.resolve(`${__dirname}/formatter_swi`)); goals = ` use_module('${pfile}'). formatter:format_prolog_source(${this._tabSize}, ${ this._tabDistance }, "${rangeTxt}", "${docText}"). `; break; case "ecl": let efile = jsesc(path.resolve(`${__dirname}/formatter`)); this._args = ["-f", efile]; rangeTxt += " end_of_file."; goals = ` format_prolog_source("${rangeTxt}", "${docText}"). `; break; default: break; } let termStr = ""; let prologProc = null; try { let prologChild = await spawn(this._executable, this._args, { cwd: workspace.rootPath }) .on("process", proc => { if (proc.pid) { prologProc = proc; proc.stdin.write(goals); proc.stdin.end(); } }) .on("stdout", data => { // console.log("data:" + data); if (/::::::ALLOVER/.test(data)) { this.resolveTerms(doc, termStr, range, true); } if (/TERMSEGMENTBEGIN:::/.test(data)) { this.resolveTerms(doc, termStr, range); termStr = data + "\n"; } else { termStr += data + "\n"; } }) .on("stderr", err => { // console.log("formatting err:" + err); // this.outputMsg(err); }) .on("close", _ => { console.log("closed"); }); } catch (error) { let message: string = null; if ((<any>error).code === "ENOENT") { message = `Cannot debug the prolog file. The Prolog executable was not found. Correct the 'prolog.executablePath' configure please.`; } else { message = error.message ? error.message : `Failed to run swipl using path: ${ this._executable }. Reason is unknown.`; } } } private resolveTerms( doc: TextDocument, text: string, range: Range, last: boolean = false ) { if (!/TERMSEGMENTBEGIN:::/.test(text)) { return; } let varsRe = /VARIABLESBEGIN:::\[([\s\S]*?)\]:::VARIABLESEND/; let termRe = /TERMBEGIN:::\n([\s\S]+?):::TERMEND/; let termPosRe = /TERMPOSBEGIN:::(\d+):::TERMPOSEND/; let termEndRe = /TERMENDBEGIN:::(\d+):::TERMENDEND/; let commsRe = /COMMENTSBIGIN:::([\s\S]*?):::COMMENTSEND/; let term = text.match(termRe), vars = text.match(varsRe), termPos = text.match(termPosRe), termEnd = text.match(termEndRe), comms = text.match(commsRe); let termCharA = parseInt(termPos[1]); let termCharZ = termEnd ? parseInt(termEnd[1]) : undefined; let commsArr: IComment[] = comms && comms[1] ? JSON.parse(comms[1]).comments : []; switch (Utils.DIALECT) { case "swi": this.resolveTermsSwi(doc, range, last, term, vars, termCharA, commsArr); break; case "ecl": // comments inside of clause let commReg = /\/\*[\s\S]*?\*\/|%.*?(?=\n)/g; let lastTermEnd = termCharA; if (commsArr && commsArr[0]) { lastTermEnd = commsArr[0].location; } let origTxt = doc .getText() .slice( doc.offsetAt(range.start) + termCharA, doc.offsetAt(range.start) + termCharZ ); let match: RegExpExecArray; while ((match = commReg.exec(origTxt)) !== null) { let m = match[0]; let comm: IComment = null; if (m.startsWith("%")) { let commPos = doc.positionAt( doc.offsetAt(range.start) + termCharA + match.index ); let lineStr = doc.lineAt(commPos.line).text; comm = this.handleLineComment( doc, lineStr, m, match.index, commPos.character, commsArr ); } else { comm = { location: match.index, comment: m }; } if (comm !== null) { commsArr.push(comm); } } this.resolveTermsEcl( doc, range, last, term, vars, termCharA, termCharZ, commsArr ); break; default: break; } } private handleLineComment( doc: TextDocument, lineStr: string, originalMatched: string, index: number, charPos: number, commsArr: IComment[] ): IComment { if (lineStr.replace(/^\s*/, "") === originalMatched) { return { location: index, comment: originalMatched }; } let i = charPos; let docText = jsesc(doc.getText(), { quotes: "double" }); while (i > -1) { let termStr = lineStr.slice(0, i).replace(/(,|;|\.)\s*$/, ""); if (Utils.isValidEclTerm(docText, termStr)) { return { location: index + i - charPos, comment: lineStr.slice(i) }; } i = lineStr.indexOf("%", i + 1); } return null; } private resolveTermsSwi( doc: TextDocument, range: Range, last: boolean, term: RegExpMatchArray, vars: RegExpMatchArray, termCharA: number, commsArr: IComment[] ) { let formattedTerm = this.restoreVariableNames(term[1], vars[1].split(",")); if (last) { termCharA++; // end_of_file offset of memory file } if (commsArr.length > 0) { termCharA = termCharA < commsArr[0].location ? termCharA : commsArr[0].location; commsArr.forEach((comm: IComment) => { comm.location -= termCharA; }); } if (!this._currentTermInfo) { this._startChars = doc.offsetAt(range.start); this._currentTermInfo = { charsSofar: 0, startLine: range.start.line, startChar: range.start.character, isValid: vars[1] === "givingup" ? false : true, termStr: formattedTerm, comments: commsArr }; } else { let endPos = doc.positionAt(termCharA + this._startChars); this._currentTermInfo.endLine = endPos.line; this._currentTermInfo.endChar = endPos.character; if (this._currentTermInfo.isValid) { // preserve original gaps between terms let lastAfterTerm = doc .getText() .slice(this._currentTermInfo.charsSofar, termCharA + this._startChars) .match(/\s*$/)[0]; this._currentTermInfo.termStr = this._currentTermInfo.termStr.replace( /\s*$/, // replace new line produced by portray_clause with original gaps lastAfterTerm ); this.generateTextEdit(doc); } this._currentTermInfo.charsSofar = termCharA + this._startChars; this._currentTermInfo.startLine = this._currentTermInfo.endLine; this._currentTermInfo.startChar = this._currentTermInfo.endChar; this._currentTermInfo.termStr = formattedTerm; this._currentTermInfo.isValid = vars[1] === "givingup" ? false : true; this._currentTermInfo.comments = commsArr; if (last) { this._currentTermInfo.endLine = range.end.line; this._currentTermInfo.endChar = range.end.character; if (this._currentTermInfo.comments.length > 0) { this._currentTermInfo.termStr = ""; this.generateTextEdit(doc); } } } } private resolveTermsEcl( doc: TextDocument, range: Range, last: boolean, term: RegExpMatchArray, vars: RegExpMatchArray, termCharA: number, termCharZ: number, commsArr: IComment[] ) { let formattedTerm = this.restoreVariableNames(term[1], vars[1].split(",")) .replace(/\b_\d+\b/g, "_") .replace(/\s*$/, ""); termCharA += doc.offsetAt(range.start); termCharZ += doc.offsetAt(range.start); this._currentTermInfo = { startLine: doc.positionAt(termCharA).line, startChar: doc.positionAt(termCharA).character, endLine: doc.positionAt(termCharZ).line, endChar: doc.positionAt(termCharZ).character, isValid: true, termStr: formattedTerm, comments: commsArr }; this.generateTextEdit(doc); } private generateTextEdit(doc: TextDocument) { let termRange = new Range( this._currentTermInfo.startLine, this._currentTermInfo.startChar, this._currentTermInfo.endLine, this._currentTermInfo.endChar ); if (this._currentTermInfo.comments.length > 0) { let newComms = this.mergeComments( doc, termRange, this._currentTermInfo.comments ); this._currentTermInfo.termStr = this.getTextWithComments( doc, termRange, this._currentTermInfo.termStr, newComms ); } if (this._currentTermInfo.termStr !== "") { this._textEdits.push( new TextEdit(termRange, this._currentTermInfo.termStr) ); } } // merge adjcent comments between which there are only spaces, including new lines private mergeComments( doc: TextDocument, range: Range, comms: IComment[] ): IComment[] { let origTxt = doc.getText(range); let newComms: IComment[] = []; newComms.push(comms[0]); let i = 1; while (i < comms.length) { let loc = comms[i].location; let last = newComms.length - 1; let lastLoc = newComms[last].location; let lastComm = newComms[last].comment; let lastEnd = lastLoc + lastComm.length; let middleTxt = origTxt.slice(lastEnd, comms[i].location); if (middleTxt.replace(/\s|\r?\n|\t/g, "").length === 0) { newComms[last].comment += middleTxt + comms[i].comment; } else { newComms.push(comms[i]); } i++; } return newComms; } private getTextWithComments( doc: TextDocument, range: Range, formatedText: string, comms: IComment[] ): string { let origTxt = doc.getText(range); let chars = origTxt.length; let txtWithComm = ""; let lastOrigPos = 0; for (let i = 0; i < comms.length; i++) { let index = comms[i].location; let comment = comms[i].comment; let origSeg = origTxt.slice(lastOrigPos, index); let noSpaceOrig = origSeg.replace(/[\s()]/g, ""); lastOrigPos = index + comment.length; let j = 0, noSpaceFormatted: string = ""; while (j < chars) { if (noSpaceFormatted === noSpaceOrig) { if (origTxt.slice(index + comment.length).startsWith(os.EOL)) { comment += os.EOL; lastOrigPos += os.EOL.length; } // if (origTxt.charAt(index + comment.length) === os.EOL) { // comment += os.EOL; // lastOrigPos += os.EOL.length; // } let tail = origSeg.match(/([()\s]*[()])?(\s*)$/); let spaces = tail[2]; if (spaces.length > 0) { comment = spaces + comment; } let tail1 = tail[1] ? tail[1] : ""; txtWithComm += formatedText.slice(0, j) + tail1 + comment; formatedText = formatedText .slice(j + tail1.length) .replace(/^\r?\n/, ""); break; } let char = formatedText.charAt(j); if (!/[\s()]/.test(char)) { noSpaceFormatted += char; } j++; } } return txtWithComm + formatedText; } private restoreVariableNames(text: string, vars: string[]): string { if (vars.length === 1 && vars[0] === "") { return text; } if (vars.length === 0) { return text; } let dups: { newVars: string[]; dup: string[] } = this.getDups(vars); dups.newVars.forEach(pair => { let [abc, orig] = pair.split(":"); text = text.replace( new RegExp("\\b" + abc.trim() + "\\b", "g"), orig.trim() ); }); return this.restoreVariableNames(text, dups.dup); } private getDups(vars: string[]) { let left: string[] = new Array<string>(vars.length); let right: string[] = new Array<string>(vars.length); for (let i = 0; i < vars.length; i++) { [left[i], right[i]] = vars[i].split(":"); } let dup: string[] = []; let index: number; for (let i = 0; i < vars.length; i++) { if ((index = right.indexOf(left[i])) > -1) { let tmp = right[index] + right[index]; while (right.indexOf(tmp) > -1) { tmp += right[index]; } vars[index] = left[index] + ":" + tmp; dup.push(tmp + ":" + right[index]); } } return { newVars: vars, dup: dup }; } }
the_stack
import * as sdk from "../microsoft.cognitiveservices.speech.sdk"; import { ConsoleLoggingListener, WebsocketMessageAdapter, } from "../src/common.browser/Exports"; import { AgentConfig } from "../src/common.speech/Exports"; import { HeaderNames } from "../src/common.speech/HeaderNames"; import { QueryParameterNames } from "../src/common.speech/QueryParameterNames"; import { ConnectionStartEvent, Events, EventType, IDetachable, PlatformEvent, SendingAgentContextMessageEvent, } from "../src/common/Exports"; import { BotFrameworkConfig, OutputFormat, PropertyId, PullAudioOutputStream, ResultReason } from "../src/sdk/Exports"; import { Settings } from "./Settings"; import { closeAsyncObjects, WaitForCondition } from "./Utilities"; import { WaveFileAudioInput } from "./WaveFileAudioInputStream"; // tslint:disable-next-line:no-console const consoleInfo = console.info; const simpleMessageObj = { speak: "This is speech", text: "This is text", type: "message" }; // tslint:disable-next-line:no-console console.info = (...args: any[]): void => { const formatConsoleDate = (): string => { const date = new Date(); const hour = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); const milliseconds = date.getMilliseconds(); return "[" + ((hour < 10) ? "0" + hour : hour) + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds) + "." + ("00" + milliseconds).slice(-3) + "] "; }; const timestamp = formatConsoleDate(); // `[${new Date().toTimeString()}]`; consoleInfo.apply(this, [timestamp, args]); }; let objsToClose: any[]; beforeAll(() => { // Override inputs, if necessary Settings.LoadSettings(); Events.instance.attachListener(new ConsoleLoggingListener(EventType.Debug)); }); beforeEach(() => { objsToClose = []; // tslint:disable-next-line:no-console console.info("------------------Starting test case: " + expect.getState().currentTestName + "-------------------------"); }); afterEach(async (done: jest.DoneCallback) => { await closeAsyncObjects(objsToClose); // tslint:disable-next-line:no-console console.info("End Time: " + new Date(Date.now()).toLocaleString()); done(); }); function BuildCommandsServiceConfig(): sdk.DialogServiceConfig { const config: sdk.CustomCommandsConfig = sdk.CustomCommandsConfig.fromSubscription(Settings.BotSecret, Settings.SpeechSubscriptionKey, Settings.SpeechRegion); if (undefined !== Settings.proxyServer) { config.setProxy(Settings.proxyServer, Settings.proxyPort); } config.setProperty(PropertyId.Conversation_ApplicationId, Settings.BotSecret); expect(config).not.toBeUndefined(); return config; } function BuildBotFrameworkConfig(): sdk.BotFrameworkConfig { const config: sdk.BotFrameworkConfig = sdk.BotFrameworkConfig.fromSubscription(Settings.BotSubscription, Settings.BotRegion); if (undefined !== Settings.proxyServer) { config.setProxy(Settings.proxyServer, Settings.proxyPort); } expect(config).not.toBeUndefined(); return config; } function BuildConnectorFromWaveFile(dialogServiceConfig?: sdk.DialogServiceConfig, audioFileName?: string): sdk.DialogServiceConnector { let connectorConfig: sdk.DialogServiceConfig = dialogServiceConfig; if (connectorConfig === undefined) { connectorConfig = BuildBotFrameworkConfig(); // Since we're not going to return it, mark it for closure. objsToClose.push(connectorConfig); } const audioConfig: sdk.AudioConfig = WaveFileAudioInput.getAudioConfigFromFile(audioFileName === undefined ? Settings.WaveFile : audioFileName); const language: string = Settings.WaveFileLanguage; if (connectorConfig.speechRecognitionLanguage === undefined) { connectorConfig.speechRecognitionLanguage = language; } const connector: sdk.DialogServiceConnector = new sdk.DialogServiceConnector(connectorConfig, audioConfig); expect(connector).not.toBeUndefined(); return connector; } function PostDoneTest(done: jest.DoneCallback, ms: number): any { return setTimeout((): void => { done(); }, ms); } function PostFailTest(done: jest.DoneCallback, ms: number, error?: string): any { return setTimeout((): void => { done.fail(error); }, ms); } function sleep(milliseconds: number): Promise<any> { return new Promise((resolve: any) => setTimeout(resolve, milliseconds)); } // DialogServiceConfig tests: begin test("Create BotFrameworkConfig from subscription, null params", () => { // tslint:disable-next-line:no-console console.info("Name: Create BotFrameworkConfig from subscription, null params"); expect(() => sdk.BotFrameworkConfig.fromSubscription(null, null)).toThrowError(); }); test("Create BotFrameworkConfig from subscription, null Region", () => { expect(() => sdk.BotFrameworkConfig.fromSubscription(Settings.BotSubscription, null)).toThrowError(); }); test("Create BotFrameworkConfig from subscription, null subscription", () => { expect(() => sdk.BotFrameworkConfig.fromSubscription(null, Settings.BotRegion)).toThrowError(); }); test("Create BotFrameworkConfig, null optional botId", () => { const connectorConfig: sdk.BotFrameworkConfig = sdk.BotFrameworkConfig.fromSubscription(Settings.BotSubscription, Settings.BotRegion, ""); expect(connectorConfig).not.toBeUndefined(); }); test("Create DialogServiceConnector, BotFrameworkConfig.fromSubscription", () => { // tslint:disable-next-line:no-console console.info("Name: Create DialogServiceConnector, BotFrameworkConfig.fromSubscription"); const connectorConfig: sdk.BotFrameworkConfig = sdk.BotFrameworkConfig.fromSubscription(Settings.BotSubscription, Settings.BotRegion); expect(connectorConfig).not.toBeUndefined(); const audioConfig: sdk.AudioConfig = WaveFileAudioInput.getAudioConfigFromFile(Settings.WaveFile); const connector: sdk.DialogServiceConnector = new sdk.DialogServiceConnector(connectorConfig, audioConfig); objsToClose.push(connector); expect(connector).not.toBeUndefined(); expect(connector instanceof sdk.DialogServiceConnector); }); test("Output format, default", () => { // tslint:disable-next-line:no-console console.info("Name: Output format, default"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); expect(dialogConfig.outputFormat === sdk.OutputFormat.Simple); }); test("Create BotFrameworkConfig, invalid optional botId", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Create BotFrameworkConfig, invalid optional botId"); const botConfig: sdk.BotFrameworkConfig = sdk.BotFrameworkConfig.fromSubscription(Settings.BotSubscription, Settings.BotRegion, "potato"); objsToClose.push(botConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(botConfig); // the service should return an error if an invalid botId was specified, even though the subscription is valid connector.listenOnceAsync( (successResult: sdk.SpeechRecognitionResult) => { if (successResult.reason !== sdk.ResultReason.Canceled) { done.fail(`listenOnceAsync shouldn't have reason '${successResult.reason}' with this config`); } else { expect(successResult.errorDetails).toContain("1006"); } }, async (failureDetails: string) => { expect(failureDetails).toContain("1006"); // Known issue: reconnection attempts continue upon failure; we'll wait a short // period of time here to avoid logger pollution. await new Promise((resolve: any) => setTimeout(resolve, 1000)); done(); }); }, 15000); test("Connect / Disconnect", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Connect / Disconnect"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = new sdk.DialogServiceConnector(dialogConfig); objsToClose.push(connector); let connected: boolean = false; let disconnected: boolean = false; const connection: sdk.Connection = sdk.Connection.fromRecognizer(connector); expect(connector).not.toBeUndefined(); connector.canceled = (sender: sdk.DialogServiceConnector, args: sdk.SpeechRecognitionCanceledEventArgs) => { // tslint:disable-next-line:no-console console.info("Error code: %d, error details: %s, error reason: %d", args.errorCode, args.errorDetails, args.reason); }; connection.connected = (args: sdk.ConnectionEventArgs) => { connected = true; }; connection.disconnected = (args: sdk.ConnectionEventArgs) => { disconnected = true; }; connection.openConnection(undefined, (error: string): void => { done.fail(error); }); WaitForCondition(() => { return connected; }, () => { connection.closeConnection(() => { if (!!disconnected) { done(); } else { done.fail("Did not disconnect before returning"); } }); }); }); test("GetDetailedOutputFormat", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: GetDetailedOutputFormat"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); dialogConfig.outputFormat = OutputFormat.Detailed; objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); let recoCounter: number = 0; connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result).not.toBeUndefined(); const resultProps = result.properties.getProperty(sdk.PropertyId.SpeechServiceResponse_JsonResult); (expect(resultProps).toContain("NBest")); recoCounter++; }, (error: string) => { done.fail(error); }); WaitForCondition(() => (recoCounter === 1), done); }); test("ListenOnceAsync", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: ListenOnceAsync"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); let sessionId: string; let hypoCounter: number = 0; let recoCounter: number = 0; let turnStatusCounter: number = 0; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; connector.recognizing = (s: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionEventArgs): void => { hypoCounter++; }; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); } catch (error) { done.fail(error); } }; connector.recognized = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionEventArgs) => { recoCounter++; }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; connector.turnStatusReceived = (sender: sdk.DialogServiceConnector, e: sdk.TurnStatusReceivedEventArgs) => { turnStatusCounter++; try { expect(e.statusCode === 200); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result).not.toBeUndefined(); expect(result.errorDetails).toBeUndefined(); expect(result.text).not.toBeUndefined(); expect(hypoCounter).toBeGreaterThanOrEqual(1); expect(recoCounter).toEqual(1); recoCounter++; }, (error: string) => { done.fail(error); }); WaitForCondition(() => (recoCounter === 2), done); WaitForCondition(() => (turnStatusCounter === 1), done); }); Settings.testIfDOMCondition("ListenOnceAsync with audio response", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: ListenOnceAsync with audio response"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig, Settings.InputDir + "weatherinthemountain.wav"); objsToClose.push(connector); let sessionId: string; let hypoCounter: number = 0; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; connector.recognizing = (s: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionEventArgs): void => { hypoCounter++; }; // ServiceRecognizerBase.telemetryData = (json: string): void => { // // Only record telemetry events from this session. // if (json !== undefined && // sessionId !== undefined && // json.indexOf(sessionId) > 0) { // try { // expect(hypoCounter).toBeGreaterThanOrEqual(1); // validateTelemetry(json, 1, hypoCounter); // } catch (error) { // done.fail(error); // } // telemetryEvents++; // } // }; const audioBuffer = new ArrayBuffer(320); const audioReadLoop = (audioStream: PullAudioOutputStream, done: jest.DoneCallback) => { audioStream.read(audioBuffer).then((bytesRead: number) => { try { if (bytesRead === 0) { PostDoneTest(done, 2000); } } catch (error) { done.fail(error); } if (bytesRead > 0) { audioReadLoop(audioStream, done); } }, (error: string) => { done.fail(error); }); }; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); if (e.activity.type === "message") { if (e.activity.speak && (e.activity.speak !== "")) { expect(e.audioStream).not.toBeNull(); audioReadLoop(e.audioStream, done); } } } catch (error) { done.fail(error); } }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { // done.fail(e.errorDetails); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result).not.toBeUndefined(); expect(result.errorDetails).toBeUndefined(); expect(result.text).not.toBeUndefined(); }, (error: string) => { done.fail(error); }); }, 15000); Settings.testIfDOMCondition("Successive ListenOnceAsync with audio response", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Successive ListenOnceAsync with audio response"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig, Settings.InputDir + "weatherinthemountain.wav"); objsToClose.push(connector); let sessionId: string; let hypoCounter: number = 0; let firstReco: boolean = false; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; connector.recognizing = (s: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionEventArgs): void => { hypoCounter++; }; const audioBuffer = new ArrayBuffer(320); const audioReadLoop = (audioStream: PullAudioOutputStream, done: jest.DoneCallback) => { audioStream.read(audioBuffer).then((bytesRead: number) => { try { if (bytesRead === 0) { PostDoneTest(done, 2000); } } catch (error) { done.fail(error); } if (bytesRead > 0) { audioReadLoop(audioStream, done); } }, (error: string) => { done.fail(error); }); }; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); if (e.activity.type === "message") { if (e.activity.speak && (e.activity.speak !== "")) { expect(e.audioStream).not.toBeNull(); audioReadLoop(e.audioStream, done); } } } catch (error) { done.fail(error); } }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { // done.fail(e.errorDetails); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result).not.toBeUndefined(); expect(result.errorDetails).toBeUndefined(); expect(result.text).not.toBeUndefined(); firstReco = true; }, (error: string) => { done.fail(error); }); WaitForCondition(() => { return firstReco; }, () => { connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result).not.toBeUndefined(); expect(result.errorDetails).toBeUndefined(); expect(result.text).not.toBeUndefined(); }, (error: string) => { done.fail(error); }); }); }, 15000); test("Successive ListenOnceAsync calls", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Successive ListenOnceAsync calls"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); let sessionId: string; let firstReco: boolean = false; let connected: number = 0; const connection: sdk.Connection = sdk.Connection.fromRecognizer(connector); connection.connected = (e: sdk.ConnectionEventArgs): void => { connected++; }; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); } catch (error) { done.fail(error); } }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result).not.toBeUndefined(); expect(result.errorDetails).toBeUndefined(); expect(result.text).not.toBeUndefined(); firstReco = true; }, (error: string) => { done.fail(error); }); WaitForCondition(() => { return firstReco; }, () => { connector.listenOnceAsync((result2: sdk.SpeechRecognitionResult) => { try { const recoResult: sdk.SpeechRecognitionResult = result2; expect(recoResult).not.toBeUndefined(); expect(connected).toEqual(1); done(); } catch (error) { done.fail(error); } }, (error: string) => { done.fail(error); }); }); }, 15000); test("ListenOnceAsync with silence returned", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: ListenOnceAsync with silence returned"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig, Settings.InputDir + "initialSilence5s.wav"); objsToClose.push(connector); let sessionId: string; let firstReco: boolean = false; let connected: number = 0; const connection: sdk.Connection = sdk.Connection.fromRecognizer(connector); connection.connected = (e: sdk.ConnectionEventArgs): void => { connected++; }; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); } catch (error) { done.fail(error); } }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result.reason).not.toBeUndefined(); expect(result.errorDetails).toBeUndefined(); firstReco = true; }, (error: string) => { done.fail(error); }); WaitForCondition(() => { return firstReco; }, () => { connector.listenOnceAsync((result2: sdk.SpeechRecognitionResult) => { try { expect(connected).toEqual(1); done(); } catch (error) { done.fail(error); } }, (error: string) => { done.fail(error); }); }); }, 15000); test("Send/Receive messages", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Send/Receive messages"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); let sessionId: string; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; let activityCount: number = 0; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); activityCount++; } catch (error) { done.fail(error); } }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; const message: string = JSON.stringify(simpleMessageObj); connector.sendActivityAsync(message); WaitForCondition(() => (activityCount >= 1), done); }); test("Send multiple messages", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Send multiple messages"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); let sessionId: string; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; let activityCount: number = 0; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); activityCount++; } catch (error) { done.fail(error); } }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; for (let j = 0; j < 5; j++) { const numberedMessage: any = { speak: "This is speech", text: `"Message ${j}`, type: "message" }; const message: string = JSON.stringify(numberedMessage); connector.sendActivityAsync(message); sleep(100).catch(); } // TODO improve, needs a more accurate verification WaitForCondition(() => (activityCount >= 4), done); }); test("Send/Receive messages during ListenOnce", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Send/Receive messages during ListenOnce"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); let sessionId: string; let recoDone: boolean = false; connector.sessionStarted = (s: sdk.DialogServiceConnector, e: sdk.SessionEventArgs): void => { sessionId = e.sessionId; }; let activityCount: number = 0; connector.activityReceived = (sender: sdk.DialogServiceConnector, e: sdk.ActivityReceivedEventArgs) => { try { expect(e.activity).not.toBeNull(); activityCount++; } catch (error) { done.fail(error); } }; connector.speechStartDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs): void => { try { const message: string = JSON.stringify(simpleMessageObj); connector.sendActivityAsync(message); } catch (error) { done.fail(error); } }; connector.canceled = (sender: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; connector.speechEndDetected = (sender: sdk.DialogServiceConnector, e: sdk.RecognitionEventArgs) => { expect(e.sessionId).toEqual(sessionId); }; connector.listenOnceAsync((result: sdk.SpeechRecognitionResult) => { expect(result).not.toBeUndefined(); expect(result.errorDetails).toBeUndefined(); expect(result.text).not.toBeUndefined(); recoDone = true; }, (error: string) => { done.fail(error); }); WaitForCondition(() => (activityCount > 1 && recoDone), done); }); test("SendActivity fails with invalid JSON object", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: SendActivity fails with invalid JSON object"); const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); const malformedJSON: string = '{speak: "This is speech", "text" : "This is JSON is malformed", "type": "message" };'; connector.sendActivityAsync(malformedJSON, () => { done.fail("Should have failed"); }, (error: string) => { expect(error).toContain("Unexpected token"); done(); }); }); describe("Agent config message tests", () => { let eventListener: IDetachable; let observedAgentConfig: AgentConfig; beforeEach(() => { eventListener = Events.instance.attachListener({ onEvent: (event: PlatformEvent) => { if (event instanceof SendingAgentContextMessageEvent) { const agentContextEvent = event as SendingAgentContextMessageEvent; observedAgentConfig = agentContextEvent.agentConfig; } }, }); }); afterEach(async () => { await eventListener.detach(); observedAgentConfig = undefined; }); test("Agent connection id can be set", async (done: jest.DoneCallback) => { const testConnectionId: string = "thisIsTheTestConnectionId"; const dialogConfig: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); dialogConfig.setProperty(sdk.PropertyId.Conversation_Agent_Connection_Id, testConnectionId); objsToClose.push(dialogConfig); const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(dialogConfig); objsToClose.push(connector); connector.listenOnceAsync( () => { try { expect(observedAgentConfig).not.toBeUndefined(); expect(observedAgentConfig.get().botInfo.connectionId).toEqual(testConnectionId); done(); } catch (error) { done.fail(error); } }, (failureMessage: string) => { done.fail(`ListenOnceAsync unexpectedly failed: ${failureMessage}`); }); }); }); describe.each([ /* [ <description>, <method to use for creating the config>, <expected fragments in connection URI>, <unexpected fragments in connection URI>, ?<override region to use>, ?<override host to use>, ?<applicationId to use>, ?<authToken to use>, ?<endpoint to use>, ] */ [ "Standard BotFrameworkConfig.fromSubscription", sdk.BotFrameworkConfig.fromSubscription, ["wss://region.convai.speech", "api/v3"], [QueryParameterNames.BotId], ], [ "BotFrameworkConfig.fromSubscription with region and appId", sdk.BotFrameworkConfig.fromSubscription, ["wss://differentRegion.convai.speech", "api/v3", QueryParameterNames.BotId], ["wss://region.convai"], "differentRegion", undefined, "myApplicationId", ], [ "Standard BotFrameworkConfig.fromHost", sdk.BotFrameworkConfig.fromHost, ["wss://hostname/", "api/v3"], ["convai"], ], [ "BotFrameworkConfig.fromHost with implicit URL generation", sdk.BotFrameworkConfig.fromHost, ["wss://basename.convai.speech.azure.us/", "api/v3"], ["hostname"], undefined, "baseName", undefined, undefined, ], [ "BotFrameworkConfig.fromHost with appId", sdk.BotFrameworkConfig.fromHost, ["ws://customhostname.com/", "api/v3", QueryParameterNames.BotId], ["convai", "wss://", "//hostName", "Authorization"], undefined, new URL("ws://customHostName.com"), "myApplicationId", ], [ "Simulated BotFrameworkConfig.fromHost with appId via properties", "simulatedFromHostWithProperties", ["ws://customhostname.com/", "api/v3", QueryParameterNames.BotId], ["convai", "wss://", "//hostName", "Authorization"], undefined, new URL("ws://customHostName.com"), "myApplicationId", ], [ "BotFrameworkConfig.fromAuthorizationToken with appId", sdk.BotFrameworkConfig.fromAuthorizationToken, ["wss://region.convai.speech", "api/v3", "Authorization", QueryParameterNames.BotId], [HeaderNames.AuthKey], undefined, undefined, "myApplicationId", "myAuthToken", ], [ "BotFrameworkConfig.fromEndpoint", sdk.BotFrameworkConfig.fromEndpoint, ["ws://this.is/my/custom/endpoint", HeaderNames.AuthKey], ["wss", "api/v3", "convai", QueryParameterNames.BotId], undefined, undefined, undefined, undefined, new URL("ws://this.is/my/custom/endpoint"), ], [ "Simulated BotFrameworkConfig.fromEndpoint with properties", "simulatedFromEndpointWithProperties", ["ws://this.is/my/custom/endpoint", "Subscription-Key"], ["wss", "api/v3", "convai", QueryParameterNames.BotId], undefined, undefined, undefined, undefined, new URL("ws://this.is/my/custom/endpoint"), ], [ "Standard CustomCommandsConfig.fromSubscription", sdk.CustomCommandsConfig.fromSubscription, ["wss://region.convai.speech.microsoft.com/commands/api/v1", HeaderNames.CustomCommandsAppId], ["api/v3"], undefined, undefined, "myApplicationId", ], ])("Connection URL contents", ( description: string, configCreationMethod: any, expectedContainedThings: string[], expectedNotContainedThings: string[], overrideRegion: string = undefined, overrideHost: string | URL = undefined, applicationId: string = undefined, authToken: string = undefined, endpoint: URL = undefined, ) => { let observedUri: string; let eventListener: IDetachable; let connector: sdk.DialogServiceConnector; async function detachListener(): Promise<void> { if (eventListener) { await eventListener.detach(); eventListener = undefined; } } beforeEach(() => { eventListener = Events.instance.attachListener({ onEvent: (event: PlatformEvent) => { if (event instanceof ConnectionStartEvent) { const connectionEvent = event as ConnectionStartEvent; observedUri = connectionEvent.uri; } }, }); }); afterEach(async () => { await eventListener.detach(); observedUri = undefined; }); function getConfig(): sdk.DialogServiceConfig { let result: sdk.DialogServiceConfig; switch (configCreationMethod) { case sdk.BotFrameworkConfig.fromSubscription: result = configCreationMethod("testKey", overrideRegion ?? "region"); break; case sdk.BotFrameworkConfig.fromHost: result = configCreationMethod(overrideHost ?? new URL("wss://hostName"), "testKey"); break; case sdk.BotFrameworkConfig.fromAuthorizationToken: expect(authToken).not.toBeUndefined(); result = configCreationMethod(authToken, overrideRegion ?? "region"); break; case sdk.BotFrameworkConfig.fromEndpoint: expect(endpoint).not.toBeUndefined(); result = configCreationMethod(endpoint, "testKey"); break; case sdk.CustomCommandsConfig.fromSubscription: expect(applicationId).not.toBeUndefined(); result = configCreationMethod(applicationId, "testKey", overrideRegion ?? "region"); break; case "simulatedFromHostWithProperties": result = sdk.BotFrameworkConfig.fromSubscription("testKey", overrideRegion ?? "region"); const host = overrideHost ?? "wss://my.custom.host"; const hostPropertyValue: string = overrideHost.toString(); result.setProperty(sdk.PropertyId.SpeechServiceConnection_Host, hostPropertyValue); break; case "simulatedFromEndpointWithProperties": result = sdk.BotFrameworkConfig.fromSubscription("testKey", overrideRegion ?? "region"); result.setProperty(sdk.PropertyId.SpeechServiceConnection_Endpoint, endpoint.toString()); break; default: result = undefined; } expect(result).not.toBeUndefined(); if (applicationId) { result.setProperty(PropertyId.Conversation_ApplicationId, applicationId); } return result; } test(`Validate: ${description}`, async (done: jest.DoneCallback) => { try { const config = getConfig(); connector = new sdk.DialogServiceConnector(config); expect(connector).not.toBeUndefined(); connector.listenOnceAsync( (successArgs: any) => { done.fail("Success callback not expected with invalid auth details!"); }, async (failureArgs?: string) => { expect(observedUri).not.toBeUndefined(); for (const expectedThing of expectedContainedThings) { expect(observedUri).toEqual(expect.stringContaining(expectedThing)); } for (const unexpectedThing of expectedNotContainedThings) { expect(observedUri.toLowerCase()).not.toEqual( expect.stringContaining(unexpectedThing.toLowerCase())); } if (applicationId) { expect(observedUri).toEqual(expect.stringContaining(applicationId)); } // Known issue: reconnection attempts continue upon failure; we'll wait a short // period of time here to avoid logger pollution. await new Promise((resolve: any) => setTimeout(resolve, 1000)); done(); }, ); } catch (error) { done.fail(error); } }, 30000); }); describe.each([ [ "simple keyword gets a result when it should", "contoso", undefined, true ], [ "simple keyword gets rejected when it should", "banana", undefined, false ], [ "simple keyword works with adequate duration", "contoso", "20000000", true ], [ "simple keyword fails with inadequate duration", "contoso", "5000000", false ], [ "works with multiple keywords", "foobar;baz;contoso;quz", "123;456;20000000", true ] ])("Keyword verification", ( description: string, keywords: string, durations: string, successExpected: boolean, ) => { test(`${description}`, async (done: jest.DoneCallback) => { const config: sdk.BotFrameworkConfig = BuildBotFrameworkConfig(); config.setProperty("SPEECH-KeywordsToDetect", keywords); if (durations !== undefined) { config.setProperty("SPEECH-KeywordsToDetect-Durations", durations); } const connector: sdk.DialogServiceConnector = BuildConnectorFromWaveFile(config, Settings.InputDir + "contoso-hows-the-weather.wav"); objsToClose.push(connector); let keywordResultReceived: number = 0; let noMatchesReceived: number = 0; let speechRecognizedReceived: number = 0; connector.recognized = (s: sdk.DialogServiceConnector, e: sdk.SpeechRecognitionEventArgs): void => { if (e.result.reason === ResultReason.RecognizedKeyword) { keywordResultReceived++; expect(keywords).toContain(e.result.text); } else if (e.result.reason === ResultReason.NoMatch) { noMatchesReceived++; } else if (e.result.reason === ResultReason.RecognizedSpeech) { expect(keywordResultReceived).toBe(1); speechRecognizedReceived++; } }; connector.listenOnceAsync( (successfulResult: sdk.SpeechRecognitionResult) => { expect(keywordResultReceived).toBe(successExpected ? 1 : 0); expect(noMatchesReceived).toBe(successExpected ? 0 : 1); expect(speechRecognizedReceived).toBe(successExpected ? 1 : 0); expect(successfulResult.reason).toBe( successExpected ? ResultReason.RecognizedSpeech : ResultReason.NoMatch); done(); }, (error: string) => { done.fail(error); }); }, 30000); });
the_stack
* @packageDocumentation * @module asset-manager */ import { BUILD, EDITOR, PREVIEW } from 'internal:constants'; import { Asset } from '../assets/asset'; import { legacyCC } from '../global-exports'; import { error } from '../platform/debug'; import { sys } from '../platform/sys'; import { basename, extname } from '../utils/path'; import Bundle from './bundle'; import Cache, { ICache } from './cache'; import CacheManager from './cache-manager'; import dependUtil from './depend-util'; import downloader from './downloader'; import factory from './factory'; import fetch from './fetch'; import * as helper from './helper'; import load from './load'; import packManager from './pack-manager'; import parser from './parser'; import { IPipe, Pipeline } from './pipeline'; import preprocess from './preprocess'; import releaseManager from './release-manager'; import RequestItem from './request-item'; import { CompleteCallbackWithData, ProgressCallback, IBundleOptions, IOptions, IRemoteOptions, presets, Request, references, IJsonAssetOptions, assets, BuiltinBundleName, bundles, fetchPipeline, files, parsed, pipeline, transformPipeline } from './shared'; import Task from './task'; import { combine, parse } from './url-transformer'; import { asyncify, parseParameters } from './utilities'; /** * @zh * AssetManager 配置。 * @en * AssetManager configuration. */ export interface IAssetManagerOptions { /* Only valid on Editor */ importBase?: string; /* Only valid on Editor */ nativeBase?: string; /* Only valid on native */ jsbDownloaderMaxTasks?: number; /* Only valid on native */ jsbDownloaderTimeout?: number; /** * @zh * 所有 bundle 的版本信息 * @en * Version for all bundles */ bundleVers?: Record<string, string>; /** * @zh * 远程服务器地址 * @en * Remote server address */ server?: string; /** * @zh * 配置为子包的 bundle * @en * All subpackages */ subpackages?: string[]; /** * @zh * 配置为远程包的 bundle * @en * All remote bundles */ remoteBundles?: string[]; } /** * @en * This module controls asset's behaviors and information, include loading, releasing etc. it is a singleton * All member can be accessed with `cc.assetManager`. * * @zh * 此模块管理资源的行为和信息,包括加载,释放等,这是一个单例,所有成员能够通过 `cc.assetManager` 调用 * */ export class AssetManager { /** * @en * Normal loading pipeline * * @zh * 正常加载管线 * */ public pipeline: Pipeline = pipeline.append(preprocess).append(load); /** * @en * Fetching pipeline * * @zh * 下载管线 * */ public fetchPipeline: Pipeline = fetchPipeline.append(preprocess).append(fetch); /** * @en * Url transformer * * @zh * Url 转换器 * */ public transformPipeline: Pipeline = transformPipeline.append(parse).append(combine); /** * @en * The collection of bundle which is already loaded, you can remove cache with {{#crossLink "AssetManager/removeBundle:method"}}{{/crossLink}} * * @zh * 已加载 bundle 的集合, 你能通过 {{#crossLink "AssetManager/removeBundle:method"}}{{/crossLink}} 来移除缓存 * */ public bundles: ICache<Bundle> = bundles; /** * @en * The collection of asset which is already loaded, you can remove cache with {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} * * @zh * 已加载资源的集合, 你能通过 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} 来移除缓存 */ public assets: ICache<Asset> = assets; public generalImportBase = ''; public generalNativeBase = ''; /** * @en * Manage relationship between asset and its dependencies * * @zh * 管理资源依赖关系 */ public dependUtil = dependUtil; /** * @en * Whether or not load asset forcibly, if it is true, asset will be loaded regardless of error * * @zh * 是否强制加载资源, 如果为 true ,加载资源将会忽略报错 * */ public force = EDITOR || PREVIEW; /** * @en * Whether to use image bitmap to load image first. If enabled, images loading will become faster but memory usage will increase. * * @zh * 是否优先使用 image bitmap 来加载图片,启用之后,图片加载速度会更快, 但内存占用会变高, * */ public allowImageBitmap = !sys.isMobile; /** * @en * Some useful function * * @zh * 一些有用的方法 * */ public utils = helper; /** * @en * Manage all downloading task * * @zh * 管理所有下载任务 * */ public downloader = downloader; /** * @en * Manage all parsing task * * @zh * 管理所有解析任务 * */ public parser = parser; /** * @en * Manage all packed asset * * @zh * 管理所有合并后的资源 * */ public packManager = packManager; /** * @en * Whether or not cache the loaded asset * * @zh * 是否缓存已加载的资源 * */ public cacheAsset = true; /** * @en * Cache manager is a module which controls all caches downloaded from server in non-web platform. * * @zh * 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存 * */ public cacheManager: CacheManager | null = null; /** * @en * The preset of options * * @zh * 可选参数的预设集 * */ public presets = presets; public factory = factory; public preprocessPipe: IPipe = preprocess; public fetchPipe: IPipe = fetch; public loadPipe: IPipe = load; public references = references; private _releaseManager = releaseManager; private _files = files; private _parsed = parsed; private _parsePipeline = BUILD ? null : new Pipeline('parse existing json', [this.loadPipe]); /** * @en * The builtin 'main' bundle * * @zh * 内置 main 包 */ public get main (): Bundle | null { return bundles.get(BuiltinBundleName.MAIN) || null; } /** * @en * The builtin 'resources' bundle * * @zh * 内置 resources 包 * */ public get resources (): Bundle | null { return bundles.get(BuiltinBundleName.RESOURCES) || null; } /** * @en * Initialize assetManager with options * * @zh * 初始化资源管理器 * * @param options - the configuration * */ public init (options: IAssetManagerOptions = {}) { this._files.clear(); this._parsed.clear(); this._releaseManager.init(); this.assets.clear(); this.bundles.clear(); this.packManager.init(); this.downloader.init(options.server, options.bundleVers, options.remoteBundles); this.parser.init(); this.dependUtil.init(); let importBase = options.importBase || ''; if (importBase && importBase.endsWith('/')) { importBase = importBase.substr(0, importBase.length - 1); } let nativeBase = options.nativeBase || ''; if (nativeBase && nativeBase.endsWith('/')) { nativeBase = nativeBase.substr(0, nativeBase.length - 1); } this.generalImportBase = importBase; this.generalNativeBase = nativeBase; } /** * @en * Get the bundle which has been loaded * * @zh * 获取已加载的分包 * * @param name - The name of bundle * @return - The loaded bundle * * @example * // ${project}/assets/test1 * cc.assetManager.getBundle('test1'); * * cc.assetManager.getBundle('resources'); * */ public getBundle (name: string): Bundle | null { return bundles.get(name) || null; } /** * @en * Remove this bundle. NOTE: The asset within this bundle will not be released automatically, * you can call {{#crossLink "Bundle/releaseAll:method"}}{{/crossLink}} manually before remove it if you need * * @zh * 移除此包, 注意:这个包内的资源不会自动释放, 如果需要的话你可以在摧毁之前手动调用 {{#crossLink "Bundle/releaseAll:method"}}{{/crossLink}} 进行释放 * * @param bundle - The bundle to be removed * * @typescript * removeBundle(bundle: cc.AssetManager.Bundle): void */ public removeBundle (bundle: Bundle) { bundle._destroy(); bundles.remove(bundle.name); } /** * @en * General interface used to load assets with a progression callback and a complete callback. You can achieve almost all * effect you want with combination of `requests` and `options`.It is highly recommended that you use more simple API, * such as `load`, `loadDir` etc. Every custom parameter in `options` will be distribute to each of `requests`. if request * already has same one, the parameter in request will be given priority. Besides, if request has dependencies, `options` * will distribute to dependencies too. Every custom parameter in `requests` will be transferred to handler of `downloader` * and `parser` as `options`. You can register you own handler downloader or parser to collect these custom parameters for some effect. * * Reserved Keyword: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, * `bundle`, `onFileProgress`, `maxConcurrency`, `maxRequestsPerFrame`, `maxRetryCount`, `version`, `xhrResponseType`, * `xhrWithCredentials`, `xhrMimeType`, `xhrTimeout`, `xhrHeader`, `reloadAsset`, `cacheAsset`, `cacheEnabled`, * Please DO NOT use these words as custom options! * * @zh * 通用加载资源接口,可传入进度回调以及完成回调,通过组合 `request` 和 `options` 参数,几乎可以实现和扩展所有想要的加载效果。非常建议 * 你使用更简单的API,例如 `load`、`loadDir` 等。`options` 中的自定义参数将会分发到 `requests` 的每一项中,如果request中已存在同名的 * 参数则以 `requests` 中为准,同时如果有其他依赖资源,则 `options` 中的参数会继续向依赖项中分发。request中的自定义参数都会以 `options` * 形式传入加载流程中的 `downloader`, `parser` 的方法中, 你可以扩展 `downloader`, `parser` 收集参数完成想实现的效果。 * * 保留关键字: `uuid`, `url`, `path`, `dir`, `scene`, `type`, `priority`, `preset`, `audioLoadMode`, `ext`, `bundle`, `onFileProgress`, * `maxConcurrency`, `maxRequestsPerFrame`, `maxRetryCount`, `version`, `xhrResponseType`, `xhrWithCredentials`, `xhrMimeType`, `xhrTimeout`, `xhrHeader`, * `reloadAsset`, `cacheAsset`, `cacheEnabled`, 请不要使用这些字段为自定义参数! * * @param requests - The request you want to load * @param options - Optional parameters * @param onProgress - Callback invoked when progression change * @param onProgress.finished - The number of the items that are already completed * @param onProgress.total - The total number of the items * @param onProgress.item - The current request item * @param onComplete - Callback invoked when finish loading * @param onComplete.err - The error occurred in loading process. * @param onComplete.data - The loaded content * * @example * cc.assetManager.loadAny({url: 'http://example.com/a.png'}, (err, img) => cc.log(img)); * cc.assetManager.loadAny(['60sVXiTH1D/6Aft4MRt9VC'], (err, assets) => cc.log(assets)); * cc.assetManager.loadAny([{ uuid: '0cbZa5Y71CTZAccaIFluuZ'}, {url: 'http://example.com/a.png'}], (err, assets) => cc.log(assets)); * cc.assetManager.downloader.register('.asset', (url, options, onComplete) => { * url += '?userName=' + options.userName + "&password=" + options.password; * cc.assetManager.downloader.downloadFile(url, null, onComplete); * }); * cc.assetManager.parser.register('.asset', (file, options, onComplete) => { * var json = JSON.parse(file); * var skin = json[options.skin]; * var model = json[options.model]; * onComplete(null, {skin, model}); * }); * cc.assetManager.loadAny({ url: 'http://example.com/my.asset', skin: 'xxx', model: 'xxx', userName: 'xxx', password: 'xxx' }); * */ public loadAny (requests: Request, options: IOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; public loadAny (requests: Request, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; public loadAny (requests: Request, options: IOptions | null, onComplete?: CompleteCallbackWithData | null): void; public loadAny<T extends Asset> (requests: string, onComplete?: CompleteCallbackWithData<T> | null): void; public loadAny<T extends Asset> (requests: string[], onComplete?: CompleteCallbackWithData<T[]> | null): void; public loadAny (requests: Request, onComplete?: CompleteCallbackWithData | null): void; public loadAny ( requests: Request, options?: IOptions | ProgressCallback | CompleteCallbackWithData | null, onProgress?: ProgressCallback | CompleteCallbackWithData | null, onComplete?: CompleteCallbackWithData | null, ) { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete); opts.preset = opts.preset || 'default'; requests = Array.isArray(requests) ? requests.slice() : requests; const task = Task.create({ input: requests, onProgress: onProg, onComplete: asyncify(onComp), options: opts }); pipeline.async(task); } /** * @en * General interface used to preload assets with a progression callback and a complete callback.It is highly recommended that you use * more simple API, such as `preloadRes`, `preloadResDir` etc. Everything about preload is just likes `cc.assetManager.loadAny`, the * difference is `cc.assetManager.preloadAny` will only download asset but not parse asset. You need to invoke `cc.assetManager.loadAny(preloadTask)` * to finish loading asset * * @zh * 通用预加载资源接口,可传入进度回调以及完成回调,非常建议你使用更简单的 API ,例如 `preloadRes`, `preloadResDir` 等。`preloadAny` 和 `loadAny` * 几乎一样,区别在于 `preloadAny` 只会下载资源,不会去解析资源,你需要调用 `cc.assetManager.loadAny(preloadTask)` 来完成资源加载。 * * @param requests - The request you want to preload * @param options - Optional parameters * @param onProgress - Callback invoked when progression change * @param onProgress.finished - The number of the items that are already completed * @param onProgress.total - The total number of the items * @param onProgress.item - The current request item * @param onComplete - Callback invoked when finish preloading * @param onComplete.err - The error occurred in preloading process. * @param onComplete.items - The preloaded content * * @example * cc.assetManager.preloadAny('0cbZa5Y71CTZAccaIFluuZ', (err) => cc.assetManager.loadAny('0cbZa5Y71CTZAccaIFluuZ')); * */ public preloadAny ( requests: Request, options: IOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]>|null): void; public preloadAny (requests: Request, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void; public preloadAny (requests: Request, options: IOptions | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void; public preloadAny (requests: Request, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void; public preloadAny ( requests: Request, options?: IOptions | ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null, onProgress?: ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null, ) { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters(options, onProgress, onComplete); opts.preset = opts.preset || 'preload'; requests = Array.isArray(requests) ? requests.slice() : requests; const task = Task.create({ input: requests, onProgress: onProg, onComplete: asyncify(onComp), options: opts }); fetchPipeline.async(task); } /** * @en * Load remote asset with url, such as audio, image, text and so on. * * @zh * 使用 url 加载远程资源,例如音频,图片,文本等等。 * * @param url - The url of asset * @param options - Some optional parameters * @param options.audioLoadMode - Indicate which mode audio you want to load * @param options.ext - If the url does not have a extension name, you can specify one manually. * @param onComplete - Callback invoked when finish loading * @param onComplete.err - The error occurred in loading process. * @param onComplete.asset - The loaded texture * * @example * cc.assetManager.loadRemote('http://www.cloud.com/test1.jpg', (err, texture) => console.log(err)); * cc.assetManager.loadRemote('http://www.cloud.com/test2.mp3', (err, audioClip) => console.log(err)); * cc.assetManager.loadRemote('http://www.cloud.com/test3', { ext: '.png' }, (err, texture) => console.log(err)); * */ public loadRemote<T extends Asset> (url: string, options: IRemoteOptions | null, onComplete?: CompleteCallbackWithData<T> | null): void; public loadRemote<T extends Asset> (url: string, onComplete?: CompleteCallbackWithData<T> | null): void; public loadRemote<T extends Asset> (url: string, options?: IRemoteOptions | CompleteCallbackWithData<T> | null, onComplete?: CompleteCallbackWithData<T> | null) { const { options: opts, onComplete: onComp } = parseParameters<CompleteCallbackWithData<T>>(options, undefined, onComplete); if (!opts.reloadAsset && this.assets.has(url)) { asyncify(onComp)(null, this.assets.get(url)); return; } opts.__isNative__ = true; opts.preset = opts.preset || 'remote'; this.loadAny({ url }, opts, null, (err, data) => { if (err) { error(err.message, err.stack); if (onComp) { onComp(err, data); } } else { factory.create(url, data, opts.ext || extname(url), opts, (p1, p2) => { if (onComp) { onComp(p1, p2 as T); } }); } }); } /** * @en * load bundle * * @zh * 加载资源包 * * @param nameOrUrl - The name or root path of bundle * @param options - Some optional paramter, same like downloader.downloadFile * @param options.version - The version of this bundle, you can check config.json in this bundle * @param onComplete - Callback when bundle loaded or failed * @param onComplete.err - The occurred error, null indicates success * @param onComplete.bundle - The loaded bundle * * @example * loadBundle('http://localhost:8080/test', null, (err, bundle) => console.log(err)); * */ public loadBundle (nameOrUrl: string, options: IBundleOptions | null, onComplete?: CompleteCallbackWithData<Bundle> | null): void; public loadBundle (nameOrUrl: string, onComplete?: CompleteCallbackWithData<Bundle> | null): void; public loadBundle (nameOrUrl: string, options?: IBundleOptions | CompleteCallbackWithData<Bundle> | null, onComplete?: CompleteCallbackWithData<Bundle> | null) { const { options: opts, onComplete: onComp } = parseParameters<CompleteCallbackWithData<Bundle>>(options, undefined, onComplete); const bundleName = basename(nameOrUrl); if (this.bundles.has(bundleName)) { asyncify(onComp)(null, this.getBundle(bundleName)); return; } opts.preset = opts.preset || 'bundle'; opts.ext = 'bundle'; opts.__isNative__ = true; this.loadAny({ url: nameOrUrl }, opts, null, (err, data) => { if (err) { error(err.message, err.stack); if (onComp) { onComp(err, data); } } else { factory.create(nameOrUrl, data, 'bundle', opts, (p1, p2) => { if (onComp) { onComp(p1, p2 as Bundle); } }); } }); } /** * @en * Release asset and it's dependencies. * This method will not only remove the cache of the asset in assetManager, but also clean up its content. * For example, if you release a texture, the texture asset and its gl texture data will be freed up. * Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, * they may turn to black and report gl errors. * * @zh * 释放资源以及其依赖资源, 这个方法不仅会从 assetManager 中删除资源的缓存引用,还会清理它的资源内容。 * 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。 * 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。 * * @param asset - The asset to be released * * @example * // release a texture which is no longer need * cc.assetManager.releaseAsset(texture); * */ public releaseAsset (asset: Asset): void { releaseManager.tryRelease(asset, true); } /** * @en * Release all unused assets. Refer to {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} for detailed information. * * @zh * 释放所有没有用到的资源。详细信息请参考 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} * * @hidden * */ public releaseUnusedAssets () { assets.forEach((asset) => { releaseManager.tryRelease(asset); }); } /** * @en * Release all assets. Refer to {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} for detailed information. * * @zh * 释放所有资源。详细信息请参考 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} * */ public releaseAll () { assets.forEach((asset) => { releaseManager.tryRelease(asset, true); }); } /** * For internal usage. * @param json * @param options * @param onComplete * @private */ public loadWithJson<T extends Asset> ( json: Record<string, any>, options: IJsonAssetOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T> | null): void; public loadWithJson<T extends Asset> (json: Record<string, any>, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T> | null): void; public loadWithJson<T extends Asset> (json: Record<string, any>, options: IJsonAssetOptions | null, onComplete?: CompleteCallbackWithData<T> | null): void; public loadWithJson<T extends Asset> (json: Record<string, any>, onComplete?: CompleteCallbackWithData<T> | null): void; public loadWithJson<T extends Asset> ( json: Record<string, any>, options?: IJsonAssetOptions | CompleteCallbackWithData<T> | null, onProgress?: ProgressCallback | CompleteCallbackWithData<T> | null, onComplete?: CompleteCallbackWithData<T> | null, ) { if (BUILD) { throw new Error('Only valid in Editor'); } const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<CompleteCallbackWithData<T>>(options, onProgress, onComplete); const item = RequestItem.create(); item.isNative = false; item.uuid = opts.assetId || (`${new Date().getTime()}${Math.random()}`); item.file = json; item.ext = '.json'; const task = Task.create({ input: [item], onProgress: onProg, options: opts, onComplete: asyncify((err, data: T) => { if (!err) { if (!opts.assetId) { data._uuid = ''; } } if (onComp) { onComp(err, data); } }), }); this._parsePipeline!.async(task); } } AssetManager.Pipeline = Pipeline; AssetManager.Task = Task; AssetManager.Cache = Cache; AssetManager.RequestItem = RequestItem; AssetManager.Bundle = Bundle; AssetManager.BuiltinBundleName = BuiltinBundleName; export declare namespace AssetManager { export { Pipeline }; export { Task }; export { Cache }; export { RequestItem }; export { Bundle }; export { BuiltinBundleName }; } export default legacyCC.assetManager = new AssetManager(); legacyCC.AssetManager = AssetManager;
the_stack
import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql'; import { DBPackageInterface } from '@/schema/package-interface/db-types'; import { DBPackageProposal } from '@/schema/package-proposal/db-types'; import { DBProjectType } from '@/schema/project-type/db-types'; import { DBUser, DBUserAccount } from '@/schema/user/db-types'; import { Context } from '@/context'; export type Maybe<T> = T | null; export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string, String: string, Boolean: boolean, Int: number, Float: number, JSON: any, Date: any, }; export type ApprovePackageProposalInput = { proposalId: Scalars['ID'], }; export type CreateTeamInput = { name: Scalars['String'], projectTypeIds: Array<Scalars['ID']>, userIds: Array<Scalars['ID']>, }; export type DataSourcesInput = { github?: Maybe<GithubDataSourceInput>, npm?: Maybe<NpmDataSourceInput>, }; export type DownloadsPoint = { __typename?: 'DownloadsPoint', downloads: Scalars['Int'], day: Scalars['Date'], }; export type EditPackageInfoInput = { common: EditPackageInterfaceInput, }; export type EditPackageInterfaceInput = { id: Scalars['ID'], info?: Maybe<PackageInfoInput>, dataSources?: Maybe<DataSourcesInput>, }; export type EditPackageProjectTypesInput = { packageId: Scalars['ID'], projectTypeIds: Array<Scalars['ID']>, }; export type EditPackageProposalInfoInput = { common: EditPackageInterfaceInput, }; export type EditTeamInput = { id: Scalars['ID'], name: Scalars['String'], projectTypeIds: Array<Scalars['ID']>, userIds: Array<Scalars['ID']>, }; export type GithubDataSourceInput = { owner: Scalars['String'], repo: Scalars['String'], }; export type Mutation = { __typename?: 'Mutation', togglePackageBookmark?: Maybe<Package>, indexPackages?: Maybe<Scalars['Boolean']>, indexPackage?: Maybe<Scalars['Boolean']>, resetProjectTypeTagCounters?: Maybe<Scalars['Boolean']>, approvePackageProposal?: Maybe<Package>, editPackageProposalProjectTypes?: Maybe<PackageProposal>, editPackageProposalInfo?: Maybe<PackageProposal>, proposePackage?: Maybe<PackageProposal>, removePackageProposal: Scalars['Boolean'], togglePackageProposalUpvote?: Maybe<PackageProposal>, editPackageProjectTypes?: Maybe<Package>, editPackageInfo?: Maybe<Package>, toggleProjectTypeBookmark?: Maybe<ProjectType>, createTeam?: Maybe<Team>, editTeam?: Maybe<Team>, }; export type MutationTogglePackageBookmarkArgs = { input: TogglePackageBookmarkInput }; export type MutationIndexPackageArgs = { id: Scalars['ID'] }; export type MutationApprovePackageProposalArgs = { input: ApprovePackageProposalInput }; export type MutationEditPackageProposalProjectTypesArgs = { input: EditPackageProjectTypesInput }; export type MutationEditPackageProposalInfoArgs = { input: EditPackageProposalInfoInput }; export type MutationProposePackageArgs = { input: ProposePackageInput }; export type MutationRemovePackageProposalArgs = { input: RemovePackageProposalInput }; export type MutationTogglePackageProposalUpvoteArgs = { input: TogglePackageProposalUpvoteInput }; export type MutationEditPackageProjectTypesArgs = { input: EditPackageProjectTypesInput }; export type MutationEditPackageInfoArgs = { input: EditPackageInfoInput }; export type MutationToggleProjectTypeBookmarkArgs = { input: ToggleProjectTypeBookmarkInput }; export type MutationCreateTeamArgs = { input: CreateTeamInput }; export type MutationEditTeamArgs = { input: EditTeamInput }; export type NpmDataSourceInput = { name: Scalars['String'], }; export type Package = PackageInterface & { __typename?: 'Package', id: Scalars['ID'], name: Scalars['String'], projectTypes: Array<ProjectType>, info: PackageInfo, dataSources: Array<PackageDataSource>, insight: PackageInsight, stars?: Maybe<Scalars['Int']>, repo?: Maybe<Scalars['String']>, defaultLogo?: Maybe<Scalars['String']>, maintainers: Array<PackageMaintainer>, homepage?: Maybe<Scalars['String']>, license?: Maybe<Scalars['String']>, description?: Maybe<Scalars['String']>, readme?: Maybe<Scalars['String']>, releases: Array<PackageRelease>, releaseCount?: Maybe<Scalars['Int']>, tagCount?: Maybe<Scalars['Int']>, bookmarked?: Maybe<Scalars['Boolean']>, }; export type PackageDataSource = { __typename?: 'PackageDataSource', type: Scalars['String'], data?: Maybe<Scalars['JSON']>, }; export type PackageInfo = { __typename?: 'PackageInfo', tags: Array<Scalars['String']>, }; export type PackageInfoInput = { tags: Array<Scalars['String']>, }; export type PackageInsight = { __typename?: 'PackageInsight', npm?: Maybe<PackageNpmInsight>, }; export type PackageInterface = { id: Scalars['ID'], name: Scalars['String'], projectTypes: Array<ProjectType>, info: PackageInfo, dataSources: Array<PackageDataSource>, insight: PackageInsight, stars?: Maybe<Scalars['Int']>, repo?: Maybe<Scalars['String']>, defaultLogo?: Maybe<Scalars['String']>, maintainers: Array<PackageMaintainer>, homepage?: Maybe<Scalars['String']>, license?: Maybe<Scalars['String']>, description?: Maybe<Scalars['String']>, readme?: Maybe<Scalars['String']>, releases: Array<PackageRelease>, releaseCount?: Maybe<Scalars['Int']>, tagCount?: Maybe<Scalars['Int']>, }; export type PackageMaintainer = { __typename?: 'PackageMaintainer', name?: Maybe<Scalars['String']>, email?: Maybe<Scalars['String']>, avatar?: Maybe<Scalars['String']>, }; export type PackageNpmInsight = { __typename?: 'PackageNpmInsight', downloads: Scalars['Int'], downloadsPoints: Array<DownloadsPoint>, }; export type PackageNpmInsightDownloadsArgs = { range: PackageNpmInsightDownloadsRange }; export type PackageNpmInsightDownloadsPointsArgs = { range: PackageNpmInsightDownloadsRange }; export enum PackageNpmInsightDownloadsRange { Day = 'day', Week = 'week', Month = 'month' } export type PackageProposal = PackageInterface & { __typename?: 'PackageProposal', id: Scalars['ID'], name: Scalars['String'], projectTypes: Array<ProjectType>, info: PackageInfo, dataSources: Array<PackageDataSource>, insight: PackageInsight, stars?: Maybe<Scalars['Int']>, repo?: Maybe<Scalars['String']>, defaultLogo?: Maybe<Scalars['String']>, maintainers: Array<PackageMaintainer>, homepage?: Maybe<Scalars['String']>, license?: Maybe<Scalars['String']>, description?: Maybe<Scalars['String']>, readme?: Maybe<Scalars['String']>, releases: Array<PackageRelease>, releaseCount?: Maybe<Scalars['Int']>, tagCount?: Maybe<Scalars['Int']>, user?: Maybe<User>, upvotes: Scalars['Int'], upvoted: Scalars['Boolean'], }; export type PackageRelease = { __typename?: 'PackageRelease', id: Scalars['ID'], date?: Maybe<Scalars['Date']>, title?: Maybe<Scalars['String']>, tagName?: Maybe<Scalars['String']>, description?: Maybe<Scalars['String']>, prerelease?: Maybe<Scalars['Boolean']>, assets: Array<PackageReleaseAsset>, }; export type PackageReleaseAsset = { __typename?: 'PackageReleaseAsset', name: Scalars['String'], downloadUrl: Scalars['String'], size: Scalars['Int'], }; export type PackagesPage = { __typename?: 'PackagesPage', items: Array<Package>, after?: Maybe<Scalars['JSON']>, }; export type ProjectType = { __typename?: 'ProjectType', id: Scalars['ID'], name: Scalars['String'], slug: Scalars['String'], logo: Scalars['String'], popularTags: Array<Tag>, tags: Array<Tag>, inTeam: Scalars['Boolean'], packageProposals: Array<PackageProposal>, packageProposalCount: Scalars['Int'], packages: PackagesPage, bookmarked?: Maybe<Scalars['Boolean']>, }; export type ProjectTypePackagesArgs = { tags?: Maybe<Array<Scalars['String']>>, after?: Maybe<Scalars['JSON']> }; export type ProposePackageInput = { projectTypeId: Scalars['ID'], packageName: Scalars['String'], tags: Array<Scalars['String']>, }; export type Query = { __typename?: 'Query', currentUser?: Maybe<User>, allUsers: Array<User>, packageProposal?: Maybe<PackageProposal>, packageProposalByName?: Maybe<PackageProposal>, package?: Maybe<Package>, packageByName?: Maybe<Package>, projectTypes: Array<ProjectType>, projectType?: Maybe<ProjectType>, projectTypeBySlug?: Maybe<ProjectType>, team?: Maybe<Team>, allTeams: Array<Team>, }; export type QueryPackageProposalArgs = { id: Scalars['ID'] }; export type QueryPackageProposalByNameArgs = { name: Scalars['String'] }; export type QueryPackageArgs = { id: Scalars['ID'] }; export type QueryPackageByNameArgs = { name: Scalars['String'] }; export type QueryProjectTypeArgs = { id: Scalars['ID'] }; export type QueryProjectTypeBySlugArgs = { slug: Scalars['String'] }; export type QueryTeamArgs = { id: Scalars['ID'] }; export type RemovePackageProposalInput = { id: Scalars['ID'], }; export type Tag = { __typename?: 'Tag', id: Scalars['ID'], count: Scalars['Int'], }; export type Team = { __typename?: 'Team', id: Scalars['ID'], name: Scalars['String'], projectTypes: Array<ProjectType>, users: Array<User>, }; export type TogglePackageBookmarkInput = { packageId: Scalars['ID'], }; export type TogglePackageProposalUpvoteInput = { proposalId: Scalars['ID'], }; export type ToggleProjectTypeBookmarkInput = { projectTypeId: Scalars['ID'], }; export type User = { __typename?: 'User', id: Scalars['ID'], nickname: Scalars['String'], email: Scalars['String'], accounts: Array<UserAccount>, avatar?: Maybe<Scalars['String']>, admin?: Maybe<Scalars['Boolean']>, teams: Array<Team>, bookmarkedPackages: Array<Package>, }; export type UserAccount = { __typename?: 'UserAccount', id: Scalars['ID'], provider: Scalars['String'], profileId: Scalars['ID'], nickname?: Maybe<Scalars['String']>, profileUrl?: Maybe<Scalars['String']>, }; export type ResolverTypeWrapper<T> = Promise<T> | T; export type ResolverFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => Promise<TResult> | TResult; export type StitchingResolver<TResult, TParent, TContext, TArgs> = { fragment: string; resolve: ResolverFn<TResult, TParent, TContext, TArgs>; }; export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> = | ResolverFn<TResult, TParent, TContext, TArgs> | StitchingResolver<TResult, TParent, TContext, TArgs>; export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>; export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult>; export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>; resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>; } export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>; resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>; } export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> = | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs> | SubscriptionResolverObject<TResult, TParent, TContext, TArgs>; export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> = | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>) | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>; export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = ( parent: TParent, context: TContext, info: GraphQLResolveInfo ) => Maybe<TTypes>; export type NextResolverFn<T> = () => Promise<T>; export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = ( next: NextResolverFn<TResult>, parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult>; /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { Query: ResolverTypeWrapper<{}>, User: ResolverTypeWrapper<DBUser>, ID: ResolverTypeWrapper<Scalars['ID']>, String: ResolverTypeWrapper<Scalars['String']>, UserAccount: ResolverTypeWrapper<DBUserAccount>, Boolean: ResolverTypeWrapper<Scalars['Boolean']>, Team: ResolverTypeWrapper<Omit<Team, 'projectTypes' | 'users'> & { projectTypes: Array<ResolversTypes['ProjectType']>, users: Array<ResolversTypes['User']> }>, ProjectType: ResolverTypeWrapper<DBProjectType>, Tag: ResolverTypeWrapper<Tag>, Int: ResolverTypeWrapper<Scalars['Int']>, PackageProposal: ResolverTypeWrapper<DBPackageProposal>, PackageInterface: ResolverTypeWrapper<DBPackageInterface>, PackageInfo: ResolverTypeWrapper<PackageInfo>, PackageDataSource: ResolverTypeWrapper<PackageDataSource>, JSON: ResolverTypeWrapper<Scalars['JSON']>, PackageInsight: ResolverTypeWrapper<PackageInsight>, PackageNpmInsight: ResolverTypeWrapper<PackageNpmInsight>, PackageNpmInsightDownloadsRange: PackageNpmInsightDownloadsRange, DownloadsPoint: ResolverTypeWrapper<DownloadsPoint>, Date: ResolverTypeWrapper<Scalars['Date']>, PackageMaintainer: ResolverTypeWrapper<PackageMaintainer>, PackageRelease: ResolverTypeWrapper<PackageRelease>, PackageReleaseAsset: ResolverTypeWrapper<PackageReleaseAsset>, PackagesPage: ResolverTypeWrapper<Omit<PackagesPage, 'items'> & { items: Array<ResolversTypes['Package']> }>, Package: ResolverTypeWrapper<Omit<Package, 'projectTypes'> & { projectTypes: Array<ResolversTypes['ProjectType']> }>, Mutation: ResolverTypeWrapper<{}>, TogglePackageBookmarkInput: TogglePackageBookmarkInput, ApprovePackageProposalInput: ApprovePackageProposalInput, EditPackageProjectTypesInput: EditPackageProjectTypesInput, EditPackageProposalInfoInput: EditPackageProposalInfoInput, EditPackageInterfaceInput: EditPackageInterfaceInput, PackageInfoInput: PackageInfoInput, DataSourcesInput: DataSourcesInput, GithubDataSourceInput: GithubDataSourceInput, NpmDataSourceInput: NpmDataSourceInput, ProposePackageInput: ProposePackageInput, RemovePackageProposalInput: RemovePackageProposalInput, TogglePackageProposalUpvoteInput: TogglePackageProposalUpvoteInput, EditPackageInfoInput: EditPackageInfoInput, ToggleProjectTypeBookmarkInput: ToggleProjectTypeBookmarkInput, CreateTeamInput: CreateTeamInput, EditTeamInput: EditTeamInput, }; /** Mapping between all available schema types and the resolvers parents */ export type ResolversParentTypes = { Query: {}, User: DBUser, ID: Scalars['ID'], String: Scalars['String'], UserAccount: DBUserAccount, Boolean: Scalars['Boolean'], Team: Omit<Team, 'projectTypes' | 'users'> & { projectTypes: Array<ResolversParentTypes['ProjectType']>, users: Array<ResolversParentTypes['User']> }, ProjectType: DBProjectType, Tag: Tag, Int: Scalars['Int'], PackageProposal: DBPackageProposal, PackageInterface: DBPackageInterface, PackageInfo: PackageInfo, PackageDataSource: PackageDataSource, JSON: Scalars['JSON'], PackageInsight: PackageInsight, PackageNpmInsight: PackageNpmInsight, PackageNpmInsightDownloadsRange: PackageNpmInsightDownloadsRange, DownloadsPoint: DownloadsPoint, Date: Scalars['Date'], PackageMaintainer: PackageMaintainer, PackageRelease: PackageRelease, PackageReleaseAsset: PackageReleaseAsset, PackagesPage: Omit<PackagesPage, 'items'> & { items: Array<ResolversParentTypes['Package']> }, Package: Omit<Package, 'projectTypes'> & { projectTypes: Array<ResolversParentTypes['ProjectType']> }, Mutation: {}, TogglePackageBookmarkInput: TogglePackageBookmarkInput, ApprovePackageProposalInput: ApprovePackageProposalInput, EditPackageProjectTypesInput: EditPackageProjectTypesInput, EditPackageProposalInfoInput: EditPackageProposalInfoInput, EditPackageInterfaceInput: EditPackageInterfaceInput, PackageInfoInput: PackageInfoInput, DataSourcesInput: DataSourcesInput, GithubDataSourceInput: GithubDataSourceInput, NpmDataSourceInput: NpmDataSourceInput, ProposePackageInput: ProposePackageInput, RemovePackageProposalInput: RemovePackageProposalInput, TogglePackageProposalUpvoteInput: TogglePackageProposalUpvoteInput, EditPackageInfoInput: EditPackageInfoInput, ToggleProjectTypeBookmarkInput: ToggleProjectTypeBookmarkInput, CreateTeamInput: CreateTeamInput, EditTeamInput: EditTeamInput, }; export type AdminDirectiveResolver<Result, Parent, ContextType = Context, Args = { }> = DirectiveResolverFn<Result, Parent, ContextType, Args>; export type AuthDirectiveResolver<Result, Parent, ContextType = Context, Args = { }> = DirectiveResolverFn<Result, Parent, ContextType, Args>; export interface DateScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['Date'], any> { name: 'Date' } export type DownloadsPointResolvers<ContextType = Context, ParentType extends ResolversParentTypes['DownloadsPoint'] = ResolversParentTypes['DownloadsPoint']> = { downloads?: Resolver<ResolversTypes['Int'], ParentType, ContextType>, day?: Resolver<ResolversTypes['Date'], ParentType, ContextType>, }; export interface JsonScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['JSON'], any> { name: 'JSON' } export type MutationResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = { togglePackageBookmark?: Resolver<Maybe<ResolversTypes['Package']>, ParentType, ContextType, RequireFields<MutationTogglePackageBookmarkArgs, 'input'>>, indexPackages?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>, indexPackage?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType, RequireFields<MutationIndexPackageArgs, 'id'>>, resetProjectTypeTagCounters?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>, approvePackageProposal?: Resolver<Maybe<ResolversTypes['Package']>, ParentType, ContextType, RequireFields<MutationApprovePackageProposalArgs, 'input'>>, editPackageProposalProjectTypes?: Resolver<Maybe<ResolversTypes['PackageProposal']>, ParentType, ContextType, RequireFields<MutationEditPackageProposalProjectTypesArgs, 'input'>>, editPackageProposalInfo?: Resolver<Maybe<ResolversTypes['PackageProposal']>, ParentType, ContextType, RequireFields<MutationEditPackageProposalInfoArgs, 'input'>>, proposePackage?: Resolver<Maybe<ResolversTypes['PackageProposal']>, ParentType, ContextType, RequireFields<MutationProposePackageArgs, 'input'>>, removePackageProposal?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType, RequireFields<MutationRemovePackageProposalArgs, 'input'>>, togglePackageProposalUpvote?: Resolver<Maybe<ResolversTypes['PackageProposal']>, ParentType, ContextType, RequireFields<MutationTogglePackageProposalUpvoteArgs, 'input'>>, editPackageProjectTypes?: Resolver<Maybe<ResolversTypes['Package']>, ParentType, ContextType, RequireFields<MutationEditPackageProjectTypesArgs, 'input'>>, editPackageInfo?: Resolver<Maybe<ResolversTypes['Package']>, ParentType, ContextType, RequireFields<MutationEditPackageInfoArgs, 'input'>>, toggleProjectTypeBookmark?: Resolver<Maybe<ResolversTypes['ProjectType']>, ParentType, ContextType, RequireFields<MutationToggleProjectTypeBookmarkArgs, 'input'>>, createTeam?: Resolver<Maybe<ResolversTypes['Team']>, ParentType, ContextType, RequireFields<MutationCreateTeamArgs, 'input'>>, editTeam?: Resolver<Maybe<ResolversTypes['Team']>, ParentType, ContextType, RequireFields<MutationEditTeamArgs, 'input'>>, }; export type PackageResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Package'] = ResolversParentTypes['Package']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, name?: Resolver<ResolversTypes['String'], ParentType, ContextType>, projectTypes?: Resolver<Array<ResolversTypes['ProjectType']>, ParentType, ContextType>, info?: Resolver<ResolversTypes['PackageInfo'], ParentType, ContextType>, dataSources?: Resolver<Array<ResolversTypes['PackageDataSource']>, ParentType, ContextType>, insight?: Resolver<ResolversTypes['PackageInsight'], ParentType, ContextType>, stars?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, repo?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, defaultLogo?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, maintainers?: Resolver<Array<ResolversTypes['PackageMaintainer']>, ParentType, ContextType>, homepage?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, license?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, readme?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, releases?: Resolver<Array<ResolversTypes['PackageRelease']>, ParentType, ContextType>, releaseCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, tagCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, bookmarked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>, }; export type PackageDataSourceResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageDataSource'] = ResolversParentTypes['PackageDataSource']> = { type?: Resolver<ResolversTypes['String'], ParentType, ContextType>, data?: Resolver<Maybe<ResolversTypes['JSON']>, ParentType, ContextType>, }; export type PackageInfoResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageInfo'] = ResolversParentTypes['PackageInfo']> = { tags?: Resolver<Array<ResolversTypes['String']>, ParentType, ContextType>, }; export type PackageInsightResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageInsight'] = ResolversParentTypes['PackageInsight']> = { npm?: Resolver<Maybe<ResolversTypes['PackageNpmInsight']>, ParentType, ContextType>, }; export type PackageInterfaceResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageInterface'] = ResolversParentTypes['PackageInterface']> = { __resolveType?: TypeResolveFn<'PackageProposal' | 'Package', ParentType, ContextType>, id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, name?: Resolver<ResolversTypes['String'], ParentType, ContextType>, projectTypes?: Resolver<Array<ResolversTypes['ProjectType']>, ParentType, ContextType>, info?: Resolver<ResolversTypes['PackageInfo'], ParentType, ContextType>, dataSources?: Resolver<Array<ResolversTypes['PackageDataSource']>, ParentType, ContextType>, insight?: Resolver<ResolversTypes['PackageInsight'], ParentType, ContextType>, stars?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, repo?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, defaultLogo?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, maintainers?: Resolver<Array<ResolversTypes['PackageMaintainer']>, ParentType, ContextType>, homepage?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, license?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, readme?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, releases?: Resolver<Array<ResolversTypes['PackageRelease']>, ParentType, ContextType>, releaseCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, tagCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, }; export type PackageMaintainerResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageMaintainer'] = ResolversParentTypes['PackageMaintainer']> = { name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, email?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, avatar?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, }; export type PackageNpmInsightResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageNpmInsight'] = ResolversParentTypes['PackageNpmInsight']> = { downloads?: Resolver<ResolversTypes['Int'], ParentType, ContextType, RequireFields<PackageNpmInsightDownloadsArgs, 'range'>>, downloadsPoints?: Resolver<Array<ResolversTypes['DownloadsPoint']>, ParentType, ContextType, RequireFields<PackageNpmInsightDownloadsPointsArgs, 'range'>>, }; export type PackageProposalResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageProposal'] = ResolversParentTypes['PackageProposal']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, name?: Resolver<ResolversTypes['String'], ParentType, ContextType>, projectTypes?: Resolver<Array<ResolversTypes['ProjectType']>, ParentType, ContextType>, info?: Resolver<ResolversTypes['PackageInfo'], ParentType, ContextType>, dataSources?: Resolver<Array<ResolversTypes['PackageDataSource']>, ParentType, ContextType>, insight?: Resolver<ResolversTypes['PackageInsight'], ParentType, ContextType>, stars?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, repo?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, defaultLogo?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, maintainers?: Resolver<Array<ResolversTypes['PackageMaintainer']>, ParentType, ContextType>, homepage?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, license?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, readme?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, releases?: Resolver<Array<ResolversTypes['PackageRelease']>, ParentType, ContextType>, releaseCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, tagCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>, user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>, upvotes?: Resolver<ResolversTypes['Int'], ParentType, ContextType>, upvoted?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>, }; export type PackageReleaseResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageRelease'] = ResolversParentTypes['PackageRelease']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, date?: Resolver<Maybe<ResolversTypes['Date']>, ParentType, ContextType>, title?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, tagName?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, prerelease?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>, assets?: Resolver<Array<ResolversTypes['PackageReleaseAsset']>, ParentType, ContextType>, }; export type PackageReleaseAssetResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackageReleaseAsset'] = ResolversParentTypes['PackageReleaseAsset']> = { name?: Resolver<ResolversTypes['String'], ParentType, ContextType>, downloadUrl?: Resolver<ResolversTypes['String'], ParentType, ContextType>, size?: Resolver<ResolversTypes['Int'], ParentType, ContextType>, }; export type PackagesPageResolvers<ContextType = Context, ParentType extends ResolversParentTypes['PackagesPage'] = ResolversParentTypes['PackagesPage']> = { items?: Resolver<Array<ResolversTypes['Package']>, ParentType, ContextType>, after?: Resolver<Maybe<ResolversTypes['JSON']>, ParentType, ContextType>, }; export type ProjectTypeResolvers<ContextType = Context, ParentType extends ResolversParentTypes['ProjectType'] = ResolversParentTypes['ProjectType']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, name?: Resolver<ResolversTypes['String'], ParentType, ContextType>, slug?: Resolver<ResolversTypes['String'], ParentType, ContextType>, logo?: Resolver<ResolversTypes['String'], ParentType, ContextType>, popularTags?: Resolver<Array<ResolversTypes['Tag']>, ParentType, ContextType>, tags?: Resolver<Array<ResolversTypes['Tag']>, ParentType, ContextType>, inTeam?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>, packageProposals?: Resolver<Array<ResolversTypes['PackageProposal']>, ParentType, ContextType>, packageProposalCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>, packages?: Resolver<ResolversTypes['PackagesPage'], ParentType, ContextType, RequireFields<ProjectTypePackagesArgs, 'tags' | 'after'>>, bookmarked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>, }; export type QueryResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = { currentUser?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>, allUsers?: Resolver<Array<ResolversTypes['User']>, ParentType, ContextType>, packageProposal?: Resolver<Maybe<ResolversTypes['PackageProposal']>, ParentType, ContextType, RequireFields<QueryPackageProposalArgs, 'id'>>, packageProposalByName?: Resolver<Maybe<ResolversTypes['PackageProposal']>, ParentType, ContextType, RequireFields<QueryPackageProposalByNameArgs, 'name'>>, package?: Resolver<Maybe<ResolversTypes['Package']>, ParentType, ContextType, RequireFields<QueryPackageArgs, 'id'>>, packageByName?: Resolver<Maybe<ResolversTypes['Package']>, ParentType, ContextType, RequireFields<QueryPackageByNameArgs, 'name'>>, projectTypes?: Resolver<Array<ResolversTypes['ProjectType']>, ParentType, ContextType>, projectType?: Resolver<Maybe<ResolversTypes['ProjectType']>, ParentType, ContextType, RequireFields<QueryProjectTypeArgs, 'id'>>, projectTypeBySlug?: Resolver<Maybe<ResolversTypes['ProjectType']>, ParentType, ContextType, RequireFields<QueryProjectTypeBySlugArgs, 'slug'>>, team?: Resolver<Maybe<ResolversTypes['Team']>, ParentType, ContextType, RequireFields<QueryTeamArgs, 'id'>>, allTeams?: Resolver<Array<ResolversTypes['Team']>, ParentType, ContextType>, }; export type TagResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Tag'] = ResolversParentTypes['Tag']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>, }; export type TeamResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Team'] = ResolversParentTypes['Team']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, name?: Resolver<ResolversTypes['String'], ParentType, ContextType>, projectTypes?: Resolver<Array<ResolversTypes['ProjectType']>, ParentType, ContextType>, users?: Resolver<Array<ResolversTypes['User']>, ParentType, ContextType>, }; export type UserResolvers<ContextType = Context, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, nickname?: Resolver<ResolversTypes['String'], ParentType, ContextType>, email?: Resolver<ResolversTypes['String'], ParentType, ContextType>, accounts?: Resolver<Array<ResolversTypes['UserAccount']>, ParentType, ContextType>, avatar?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, admin?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>, teams?: Resolver<Array<ResolversTypes['Team']>, ParentType, ContextType>, bookmarkedPackages?: Resolver<Array<ResolversTypes['Package']>, ParentType, ContextType>, }; export type UserAccountResolvers<ContextType = Context, ParentType extends ResolversParentTypes['UserAccount'] = ResolversParentTypes['UserAccount']> = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, provider?: Resolver<ResolversTypes['String'], ParentType, ContextType>, profileId?: Resolver<ResolversTypes['ID'], ParentType, ContextType>, nickname?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, profileUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>, }; export type Resolvers<ContextType = Context> = { Date?: GraphQLScalarType, DownloadsPoint?: DownloadsPointResolvers<ContextType>, JSON?: GraphQLScalarType, Mutation?: MutationResolvers<ContextType>, Package?: PackageResolvers<ContextType>, PackageDataSource?: PackageDataSourceResolvers<ContextType>, PackageInfo?: PackageInfoResolvers<ContextType>, PackageInsight?: PackageInsightResolvers<ContextType>, PackageInterface?: PackageInterfaceResolvers, PackageMaintainer?: PackageMaintainerResolvers<ContextType>, PackageNpmInsight?: PackageNpmInsightResolvers<ContextType>, PackageProposal?: PackageProposalResolvers<ContextType>, PackageRelease?: PackageReleaseResolvers<ContextType>, PackageReleaseAsset?: PackageReleaseAssetResolvers<ContextType>, PackagesPage?: PackagesPageResolvers<ContextType>, ProjectType?: ProjectTypeResolvers<ContextType>, Query?: QueryResolvers<ContextType>, Tag?: TagResolvers<ContextType>, Team?: TeamResolvers<ContextType>, User?: UserResolvers<ContextType>, UserAccount?: UserAccountResolvers<ContextType>, }; /** * @deprecated * Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config. */ export type IResolvers<ContextType = Context> = Resolvers<ContextType>; export type DirectiveResolvers<ContextType = Context> = { admin?: AdminDirectiveResolver<any, any, ContextType>, auth?: AuthDirectiveResolver<any, any, ContextType>, }; /** * @deprecated * Use "DirectiveResolvers" root object instead. If you wish to get "IDirectiveResolvers", add "typesPrefix: I" to your config. */ export type IDirectiveResolvers<ContextType = Context> = DirectiveResolvers<ContextType>;
the_stack
declare var SmoothieChart : any; declare var TimeSeries : any; module VORLON { export class UWPDashboard extends DashboardPlugin { //Do any setup you need, call super to configure //the plugin with html and css for the dashboard constructor() { // name , html for dash css for dash super("uwp", "control.html", "control.css"); this._ready = true; //this.debug = true; } //Return unique id for your plugin public getID(): string { return "UWP"; } public _startStopButton: HTMLButtonElement; public _startStopButtonState: HTMLElement; public _refreshButton: HTMLButtonElement; public _nowinrtpanel: HTMLElement; public _metadatapanel: HTMLElement; public _memorypanel: HTMLElement; public _cpupanel: HTMLElement; public _diskpanel: HTMLElement; public _networkpanel: HTMLElement; public _powerpanel: HTMLElement; public _energypanel: HTMLElement; running: boolean; _metadataDisplay: MetadataDisplayControl; _memoryMonitor: MemoryMonitorControl; _cpuMonitor: CpuMonitorControl; _networkMonitor: NetworkMonitorControl; _diskMonitor: DiskMonitorControl; _powerMonitor: PowerMonitorControl; _energyMonitor: EnergyMonitorControl; public startDashboardSide(div: HTMLDivElement = null): void { this._insertHtmlContentAsync(div, (filledDiv) => { this._startStopButton = <HTMLButtonElement>filledDiv.querySelector('x-action[event="toggleState"]'); this._startStopButtonState = <HTMLElement>filledDiv.querySelector('x-action[event="toggleState"]>i'); this._refreshButton = <HTMLButtonElement>filledDiv.querySelector('x-action[event="btnrefresh"]'); this._nowinrtpanel = <HTMLElement>filledDiv.querySelector("#nowinrt"); this._metadatapanel = <HTMLElement>filledDiv.querySelector("#metadata"); this._networkpanel = <HTMLElement>filledDiv.querySelector("#network"); this._memorypanel = <HTMLElement>filledDiv.querySelector("#memory"); this._cpupanel = <HTMLElement>filledDiv.querySelector("#cpu"); this._diskpanel = <HTMLElement>filledDiv.querySelector("#disk"); this._powerpanel = <HTMLElement>filledDiv.querySelector("#power"); this._energypanel = <HTMLElement>filledDiv.querySelector("#energy"); this._refreshButton.onclick = (arg) => { this.sendCommandToClient('getMetadata'); this.sendCommandToClient('getStatus'); } this.sendCommandToClient('getMetadata'); this._startStopButton.addEventListener('click', (arg) => { if (!this._startStopButtonState.classList.contains('fa-spin')) { this._startStopButtonState.classList.remove('fa-play'); this._startStopButtonState.classList.remove('fa-stop'); this._startStopButtonState.classList.remove('no-anim'); this._startStopButtonState.classList.add('fa-spin'); this._startStopButtonState.classList.add('fa-spinner'); if (this.running) { this.sendCommandToClient('stopMonitor'); } else { this.sendCommandToClient('startMonitor', { interval: streamdelay }); } } }); }) } // When we get a message from the client, just show it public onRealtimeMessageReceivedFromClientSide(receivedObject: any): void { // var message = document.createElement('p'); // message.textContent = receivedObject.message; // this._outputDiv.appendChild(message); } public showNoWinRT() { if (this._nowinrtpanel) { this._nowinrtpanel.style.display = ""; } } public hideNoWinRT() { if (this._nowinrtpanel) { this._nowinrtpanel.style.display = "none"; } } public checkBtnState(isRunning: boolean) { this.running = isRunning; if (isRunning) { this._startStopButtonState.classList.remove('fa-play'); this._startStopButtonState.classList.remove('fa-spin'); this._startStopButtonState.classList.remove('fa-spinner'); this._startStopButtonState.classList.add('fa-stop'); this._startStopButtonState.classList.add('no-anim'); }else{ this._startStopButtonState.classList.remove('fa-stop'); this._startStopButtonState.classList.remove('fa-spin'); this._startStopButtonState.classList.remove('fa-spinner'); this._startStopButtonState.classList.add('fa-play'); this._startStopButtonState.classList.add('no-anim'); } } public renderMetadata(metadata: IUWPMetadata) { if (!metadata.winRTAvailable) { this.showNoWinRT(); return; } else { this.hideNoWinRT(); } this.checkBtnState(metadata.isRunning); if (!this._metadataDisplay) { this._metadataDisplay = new MetadataDisplayControl(this._metadatapanel); } this._metadataDisplay.setData(metadata); } public initControls() { if (!this._memoryMonitor) this._memoryMonitor = new MemoryMonitorControl(this._memorypanel); if (!this._cpuMonitor) this._cpuMonitor = new CpuMonitorControl(this._cpupanel); if (!this._diskMonitor) this._diskMonitor = new DiskMonitorControl(this._diskpanel); if (!this._networkMonitor) this._networkMonitor = new NetworkMonitorControl(this._networkpanel); if (!this._powerMonitor) this._powerMonitor = new PowerMonitorControl(this._powerpanel); if (!this._energyMonitor) this._energyMonitor = new EnergyMonitorControl(this._energypanel); } public renderStatus(status: IUWPStatus) { if (!status.winRTAvailable) { this.showNoWinRT(); return; } else { this.hideNoWinRT(); } var date = new Date(<any>status.statusDate); this.checkBtnState(status.isRunning); this.initControls(); this._memoryMonitor.setData(date, status.memory, status.phone ? status.phone.memory : null); this._cpuMonitor.setData(date, status.cpu); this._diskMonitor.setData(date, status.disk); this._networkMonitor.setData(date, status.network); this._powerMonitor.setData(date, status.power); this._energyMonitor.setData(date, status.energy); } } UWPDashboard.prototype.DashboardCommands = { showStatus: function(data: any) { var plugin = <UWPDashboard>this; plugin.renderStatus(data); }, showMetadata: function(data: any) { var plugin = <UWPDashboard>this; plugin.renderMetadata(data); } } Core.RegisterDashboardPlugin(new UWPDashboard()); function formatTime(time : number){ if (time < 1000) return (time << 0) + " ms"; time = time / 1000; if (time < 60){ return (time << 0) + ' s'; } var min = (time / 60); var sec = time % 60; if (min < 60) return (min << 0) + 'min'; var hours = min / 60; return (hours << 0) + 'h' + (min - hours*60) + 'min'; } function formatBytes(bytes : number){ var current = bytes; if (current < 1024) return current + ' bytes'; current = current / 1024; if (current < 1024) return (current << 0) + ' ko'; current = current / 1024; if (current < 1024) return (current << 0) + ' Mo'; current = current / 1024; return (current << 0) + ' Go'; } export class MetadataDisplayControl { element: HTMLElement; name: HTMLElement; language: HTMLElement; region: HTMLElement; deviceType: HTMLElement; appversion: HTMLElement; systemManufacturer: HTMLElement; systemProductName: HTMLElement; constructor(element: HTMLElement) { this.element = element; this.render(); } render() { var entry = (title, identifier) => { return `<div class="labelval"><div class="label">${title}</div><div class="val ${identifier}"></div></div>` } this.element.innerHTML = `<h1>Client device</h1> ${entry("app. name", "name")} ${entry("app. version", "appversion")} ${entry("language", "language")} ${entry("region", "region")} ${entry("device family", "deviceType")} ${entry("manufacturer", "systemManufacturer")} ${entry("product name", "systemProductName")} `; this.name = <HTMLElement>this.element.querySelector(".name"); this.language = <HTMLElement>this.element.querySelector(".language"); this.region = <HTMLElement>this.element.querySelector(".region"); this.deviceType = <HTMLElement>this.element.querySelector(".deviceType"); this.appversion = <HTMLElement>this.element.querySelector(".appversion"); this.systemManufacturer = <HTMLElement>this.element.querySelector(".systemManufacturer"); this.systemProductName = <HTMLElement>this.element.querySelector(".systemProductName"); } setData(metadata: IUWPMetadata) { if (!metadata) { this.element.style.display = "none"; return; } else { this.element.style.display = ""; } if (this.name) { this.name.textContent = metadata.name; this.language.textContent = metadata.language; this.region.textContent = metadata.region; this.deviceType.textContent = metadata.deviceType; this.appversion.textContent = metadata.appversion.major + "." + metadata.appversion.minor + "." + metadata.appversion.build + "." + metadata.appversion.revision; this.systemManufacturer.textContent = metadata.systemManufacturer; this.systemProductName.textContent = metadata.systemProductName; } } } var timescale = 200; var lineColor = '#00a5b3'; var linewidth = 2; var streamdelay = 5000; var maxValueScale = 1.1; export class MemoryMonitorControl { element: HTMLElement; workingSet: HTMLElement; canvas : HTMLCanvasElement; smoothie : any; lineWorkset : any; linePeakWorkset : any; constructor(element: HTMLElement) { this.element = element; this.render(); } render() { var entry = (title, identifier) => { return `<div class="labelval"><div class="label">${title}</div><div class="val ${identifier}"></div></div>` } this.element.innerHTML = `<h1>Memory</h1> ${entry("working set", "workingSet")} <canvas id="memoryrealtime" width="360" height="100"></canvas>`; this.workingSet = <HTMLElement>this.element.querySelector(".workingSet"); this.canvas = <HTMLCanvasElement>this.element.querySelector("#memoryrealtime"); this.smoothie = new SmoothieChart({ millisPerPixel : timescale, maxValueScale: maxValueScale }); this.smoothie.streamTo(this.canvas, streamdelay); this.lineWorkset = new TimeSeries(); //this.linePeakWorkset = new TimeSeries(); this.smoothie.addTimeSeries(this.lineWorkset, { lineWidth:linewidth, strokeStyle : lineColor }); //this.smoothie.addTimeSeries(this.linePeakWorkset, { lineWidth:linewidth, strokeStyle : lineColor }); } setData(date : Date, memory: IUWPMemoryStatus, phone: IUWPPhoneMemoryStatus) { if (!memory) { this.element.style.display = "none"; return; } else { this.element.style.display = ""; } var workset = ((memory.workingSet / (1024 * 1024)) << 0); //var peakworkset = ((memory.peakWorkingSet / (1024 * 1024)) << 0); this.workingSet.textContent = formatBytes(memory.workingSet); this.lineWorkset.append(date, workset); //this.linePeakWorkset.append(date, peakworkset); } } export class CpuMonitorControl { lastDate : Date; lastUserTime : number; element: HTMLElement; userTime: HTMLElement; percent: HTMLElement; canvas : HTMLCanvasElement; smoothie : any; lineUser : any; constructor(element: HTMLElement) { this.element = element; this.render(); } render() { var entry = (title, identifier) => { return `<div class="labelval"><div class="label">${title}</div><div class="val ${identifier}"></div></div>` } this.element.innerHTML = `<h1>CPU</h1> ${entry("total time", "userTime")} ${entry("percent", "percent")} <canvas id="userrealtime" width="360" height="100"></canvas>`; this.canvas = <HTMLCanvasElement>this.element.querySelector("#userrealtime"); this.smoothie = new SmoothieChart({ millisPerPixel : timescale, maxValueScale: maxValueScale }); this.smoothie.streamTo(this.canvas, streamdelay); this.lineUser = new TimeSeries(); this.smoothie.addTimeSeries(this.lineUser, { lineWidth:linewidth, strokeStyle : lineColor }); this.userTime = <HTMLElement>this.element.querySelector(".userTime"); this.percent = <HTMLElement>this.element.querySelector(".percent"); } setData(date : Date, cpu: IUWPCpuStatus) { if (!cpu) { this.element.style.display = "none"; return; } else { this.element.style.display = ""; } this.userTime.textContent = cpu.user + " ms"; if (this.lastDate){ var difDate = <any>date - <any>this.lastDate; var difUserTime = cpu.user - this.lastUserTime; var percent = (100 * difUserTime / difDate); this.percent.textContent = percent.toFixed(1) + " %"; this.lineUser.append(date, percent); } this.lastDate = date; this.lastUserTime = cpu.user; } } export class DiskMonitorControl { element: HTMLElement; read: HTMLElement; write: HTMLElement; canvasRead : HTMLCanvasElement; smoothieRead : any; lineRead: any; canvasWrite : HTMLCanvasElement; smoothieWrite : any; lineWrite: any; lastDate : Date; lastRead : number; lastWrite : number; constructor(element: HTMLElement) { this.element = element; this.render(); } render() { var entry = (title, identifier) => { return `<div class="labelval"><div class="label">${title}</div><div class="val ${identifier}"></div></div>` } this.element.innerHTML = `<h1>Disk</h1> ${entry("read bytes", "bytesRead")} <canvas id="readrealtime" width="360" height="60"></canvas> ${entry("write bytes", "bytesWritten")} <canvas id="writerealtime" width="360" height="60"></canvas>`; this.canvasRead = <HTMLCanvasElement>this.element.querySelector("#readrealtime"); this.smoothieRead = new SmoothieChart({ millisPerPixel : timescale, maxValueScale: maxValueScale }); this.smoothieRead.streamTo(this.canvasRead, streamdelay); this.lineRead= new TimeSeries(); this.smoothieRead.addTimeSeries(this.lineRead, { lineWidth:linewidth, strokeStyle : lineColor }); this.canvasWrite = <HTMLCanvasElement>this.element.querySelector("#writerealtime"); this.smoothieWrite = new SmoothieChart({ millisPerPixel : timescale, maxValueScale: maxValueScale }); this.smoothieWrite.streamTo(this.canvasWrite, streamdelay); this.lineWrite= new TimeSeries(); this.smoothieWrite.addTimeSeries(this.lineWrite, { lineWidth:linewidth, strokeStyle : lineColor }); this.read = <HTMLElement>this.element.querySelector(".bytesRead"); this.write = <HTMLElement>this.element.querySelector(".bytesWritten"); } setData(date : Date, disk: IUWPDiskStatus) { if (!disk) { this.element.style.display = "none"; return; } else { this.element.style.display = ""; } this.read.textContent = formatBytes(disk.bytesRead); this.write.textContent = formatBytes(disk.bytesWritten); if (this.lastDate){ var datedif = <any>date - <any>this.lastDate; var readDif = disk.bytesRead - this.lastRead; var read = (readDif / datedif); var writeDif = disk.bytesWritten - this.lastWrite; var write = (writeDif / datedif); this.lineRead.append(date, read); this.lineWrite.append(date, write); } this.lastDate = date; this.lastRead = disk.bytesRead; this.lastWrite = disk.bytesWritten; } } export class NetworkMonitorControl { element: HTMLElement; ianaInterfaceType:HTMLElement; signal:HTMLElement; constructor(element: HTMLElement) { this.element = element; this.render(); } render() { var entry = (title, identifier) => { return `<div class="labelval"><div class="label">${title}</div><div class="val ${identifier}"></div></div>` } this.element.innerHTML = `${entry("network type", "ianaInterfaceType")} ${entry("signal", "signal")} `; this.ianaInterfaceType = <HTMLElement>this.element.querySelector(".ianaInterfaceType"); this.signal = <HTMLElement>this.element.querySelector(".signal"); } setData(date : Date, network: IUWPNetworkStatus) { if (!network) { this.element.style.display = "none"; return; } else { this.element.style.display = ""; } var networkType = "unknown (" + network.ianaInterfaceType + ")"; if (network.ianaInterfaceType == 243 || network.ianaInterfaceType == 244){ networkType = "3G or 4G"; } else if (network.ianaInterfaceType == 71){ networkType = "Wifi"; } else if (network.ianaInterfaceType == 6){ networkType = "LAN"; } this.ianaInterfaceType.textContent = networkType; this.signal.textContent = (network.signal || "") + ""; } } export class PowerMonitorControl { element: HTMLElement; power: HTMLElement; constructor(element: HTMLElement) { this.element = element; this.render(); } render() { var entry = (title, identifier) => { return `<div class="labelval"><div class="label">${title}</div><div class="val ${identifier}"></div></div>` } this.element.innerHTML = `${entry("power", "power")} `; this.power = <HTMLElement>this.element.querySelector(".power"); } setData(date : Date, power: IUWPPowerStatus) { if (!power) { this.element.style.display = "none"; return; } else { this.element.style.display = ""; } //this.power.textContent = power.remainingChargePercent + '% (' + formatTime(power.remainingDischargeTime) + ')'; this.power.textContent = power.remainingChargePercent + '%'; } } export class EnergyMonitorControl { element: HTMLElement; recentEnergyUsage: HTMLElement; canvas : HTMLCanvasElement; smoothie : any; lineFgUsage : any; constructor(element: HTMLElement) { this.element = element; this.render(); } render() { var entry = (title, identifier) => { return `<div class="labelval"><div class="label">${title}</div><div class="val ${identifier}"></div></div>` } this.element.innerHTML = `<h1>Energy</h1> ${entry("usage", "recentEnergyUsage")} <canvas id="fgusagerealtime" width="360" height="100"></canvas>`; this.canvas = <HTMLCanvasElement>this.element.querySelector("#fgusagerealtime"); this.smoothie = new SmoothieChart({ millisPerPixel : timescale, maxValueScale: maxValueScale }); this.smoothie.streamTo(this.canvas, streamdelay); this.lineFgUsage = new TimeSeries(); this.smoothie.addTimeSeries(this.lineFgUsage, { lineWidth:linewidth, strokeStyle : lineColor }); this.recentEnergyUsage = <HTMLElement>this.element.querySelector(".recentEnergyUsage"); } setData(date : Date, energy: IUWPEnergyStatus) { if (!energy || !energy.foregroundEnergy) { this.element.style.display = "none"; return; } else { this.element.style.display = ""; } this.recentEnergyUsage.textContent = energy.foregroundEnergy.recentEnergyUsage + " %"; this.lineFgUsage.append(date, energy.foregroundEnergy.recentEnergyUsage); } } }
the_stack
import React, { useEffect, useLayoutEffect, useState } from "react"; import { EnvManagerComponent } from "@ui_types"; import { Api, Model, Rbac } from "@core/types"; import * as ui from "@ui"; import * as g from "@core/lib/graph"; import { getEnvParentPath } from "@ui_lib/paths"; import { style } from "typestyle"; import * as styles from "@styles"; import { SvgImage } from "@images"; import { Link } from "react-router-dom"; import { logAndAlertError } from "@ui_lib/errors"; export const SubEnvs: EnvManagerComponent = (props) => { const { graph, graphUpdatedAt } = props.core; const currentUserId = props.ui.loadedAccountId!; const parentEnvironmentId = props.parentEnvironmentId!; const parentEnvironment = graph[parentEnvironmentId] as Model.Environment; const environmentRole = graph[ parentEnvironment.environmentRoleId ] as Rbac.EnvironmentRole; const envParent = graph[props.envParentId] as Model.EnvParent; const envParentPath = getEnvParentPath(envParent); const subEnvironments = g.getSubEnvironmentsByParentEnvironmentId(graph)[parentEnvironmentId] ?? []; const searchParams = new URLSearchParams(props.location.search); const selectedNew = props.routeParams.subEnvironmentId == "new"; let subEnvironmentId = selectedNew ? undefined : props.routeParams.subEnvironmentId; let localsUserId: string | undefined; if (environmentRole.hasLocalKeys && subEnvironmentId) { const subEnvironment = graph[subEnvironmentId] as | Model.Environment | undefined; if (!subEnvironment) { const split = subEnvironmentId.split("|"); localsUserId = split[1]; subEnvironmentId = undefined; } } useLayoutEffect(() => { if (!(selectedNew || subEnvironmentId || localsUserId)) { if (environmentRole.hasLocalKeys) { pushSubEnvRoute([props.envParentId, currentUserId].join("|")); } else if (subEnvironments.length > 0) { pushSubEnvRoute(subEnvironments[0].id); } else if (canCreate) { pushNewRoute(); } else { props.history.push( props.orgRoute(`${envParentPath}/${parentEnvironmentId}`) ); } } }, [graphUpdatedAt, selectedNew, subEnvironmentId]); useLayoutEffect(() => { if (subEnvironmentId && !localsUserId && !graph[subEnvironmentId]) { pushSubEnvBaseRoute(); } }, [graphUpdatedAt, subEnvironmentId]); useEffect(() => { if (selectedNew && props.ui.envManager.showAddForm) { props.setEnvManagerState({ showAddForm: false }); } }, [selectedNew]); const canCreate = g.authz.canCreateSubEnvironment( graph, currentUserId, parentEnvironmentId ); const listWidth = props.subEnvsListWidth; const selectedWidth = props.viewWidth - listWidth; const subEnvBasePath = `${envParentPath}/environments/${parentEnvironmentId}/sub-environments`; const pushSubEnvBaseRoute = () => props.history.push(props.orgRoute(subEnvBasePath)); const pushNewRoute = () => props.history.push(props.orgRoute(`${subEnvBasePath}/new`)); const pushSubEnvRoute = (id: string) => props.history.push(props.orgRoute(`${subEnvBasePath}/${id}`)); const [newSubName, setNewSubName] = useState(""); const [isSubmittingNew, setIsSubmittingNew] = useState(false); const [hasSubmitError, setHasSubmitError] = useState(false); const [createdId, setCreatedId] = useState<string>(); const createdEnvironment = createdId ? (graph[createdId] as Model.Environment | undefined) : undefined; useLayoutEffect(() => { if (createdEnvironment) { props.history.push( props.orgRoute( `${envParentPath}/environments/${parentEnvironmentId}/sub-environments/${createdEnvironment.id}` ) ); setCreatedId(undefined); setNewSubName(""); setIsSubmittingNew(false); setHasSubmitError(false); } }, [Boolean(createdEnvironment)]); useEffect(() => { setNewSubName(""); setIsSubmittingNew(false); setHasSubmitError(false); }, [parentEnvironmentId]); const onSubmitNew = async (e: React.FormEvent) => { e.preventDefault(); if (!newSubName) { return; } setIsSubmittingNew(true); const res = await props .dispatch({ type: Api.ActionType.CREATE_ENVIRONMENT, payload: { envParentId: props.envParentId, environmentRoleId: parentEnvironment.environmentRoleId, isSub: true, parentEnvironmentId, subName: newSubName, }, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem creating the environment.`, (res.resultAction as any)?.payload ); } return res; }); if (res.success) { const created = g .graphTypes(res.state.graph) .environments.find( ({ createdAt }) => createdAt === res.state.graphUpdatedAt ); if (created) { setCreatedId(created.id); } } else { setHasSubmitError(true); } }; const onDeleteSub = async () => { const subEnvironment = graph[subEnvironmentId!] as Model.Environment; if (!subEnvironment.isSub) { return; } const parentEnvironment = graph[ subEnvironment.parentEnvironmentId ] as Model.Environment; if ( confirm( `Are you sure you want to delete ${g.getEnvironmentName( graph, parentEnvironment.id )} > ${subEnvironment.subName}?` ) ) { props .dispatch({ type: Api.ActionType.DELETE_ENVIRONMENT, payload: { id: subEnvironmentId! }, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem deleting the environment.`, (res.resultAction as any)?.payload ); } }); } }; const renderBackLink = () => { if (props.routeParams.environmentId) { const backPath = searchParams.get("backPath"); return ( <Link className={styles.EnvLabelArrowButton + " has-tooltip"} to={ backPath ? decodeURIComponent(backPath) : props.orgRoute(envParentPath + `/environments`) } > {"←"} <span className="tooltip">Go back</span> </Link> ); } }; const renderNewListItem = () => ( <li className={ "sub-label" + (selectedNew ? " selected " : " ") + style({ width: listWidth, }) } key="sub-label" > {renderBackLink()} {g.getEnvironmentName(graph, parentEnvironment.id)} {canCreate ? ( <div className="actions"> <span className="add has-tooltip" onClick={() => pushNewRoute()}> <SvgImage type="add" /> {selectedNew ? "" : <span className="tooltip">Add a branch</span>} </span> </div> ) : ( <div className="actions"> <span className="add" style={{ visibility: "hidden" }}></span> </div> )} </li> ); const renderDeleteSubEnv = (subEnvironment: Model.Environment) => { if (!subEnvironment.isSub) { return ""; } return g .getEnvironmentPermissions( graph, subEnvironment.parentEnvironmentId, currentUserId ) .has("write_branches") ? ( <span onClick={onDeleteSub} className="remove"> <SvgImage type="x" /> </span> ) : ( "" ); }; const renderSubEnvListItem = ( subEnvironment: Model.Environment, i: number ) => ( <li key={i} className={subEnvironmentId == subEnvironment.id ? "selected" : ""} > <div> {renderDeleteSubEnv(subEnvironment)} <div className="select" onClick={() => pushSubEnvRoute(subEnvironment.id)} > <span>{g.getEnvironmentName(graph, subEnvironment.id)}</span> <SvgImage type="right-caret" /> </div> </div> </li> ); const renderLocalsListItem = () => environmentRole.hasLocalKeys ? ( <li key="locals" className={localsUserId ? "selected" : ""}> <div> <div className="select" onClick={() => pushSubEnvRoute([props.envParentId, currentUserId].join("|")) } > <span>Locals</span> <SvgImage type="right-caret" /> </div> </div> </li> ) : ( "" ); const renderList = () => { return ( <ul> {[ renderNewListItem(), renderLocalsListItem(), ...subEnvironments.map(renderSubEnvListItem), ]} </ul> ); }; const renderNewSubError = () => { if (hasSubmitError) { return <p>There was a problem creating the branch.</p>; } }; const renderNewSubCopy = () => { if (subEnvironments.length == 0) { return ( <p> <strong>BRANCHES</strong> allow you to extend base environments like Development, Staging, or Production by overriding existing variables or setting new ones. </p> ); } }; const renderSubmitBtn = () => { return ( <input className="primary" type="submit" disabled={!newSubName || isSubmittingNew} value={`${isSubmittingNew ? "Creating" : "Create"} Branch${ isSubmittingNew ? "..." : "" }`} /> ); }; const renderNewForm = () => { return ( <form className={ styles.NewSubEnvForm + (subEnvironments.length == 0 ? " new-form-only" : "") } onSubmit={onSubmitNew} > {renderNewSubCopy()} {renderNewSubError()} <div className="field"> {/* <label> New {g.getEnvironmentName(graph, parentEnvironmentId)}{" "} Branch </label> */} <input type="text" autoFocus disabled={isSubmittingNew} placeholder="Enter a name..." value={newSubName} onChange={(e) => setNewSubName(e.target.value)} /> </div> <div className="buttons">{renderSubmitBtn()}</div> </form> ); }; const renderSelected = () => { if ( props.editingMultiline && props.ui.envManager.showAddForm && props.ui.envManager.entryForm.editingEnvironmentId ) { return ""; } if (selectedNew) { return renderNewForm(); } else if (subEnvironmentId || localsUserId) { const entryColWidth = Math.min( Math.max( selectedWidth * props.ui.envManager.entryColPct, styles.layout.ENTRY_COL_MIN_WIDTH ), styles.layout.ENTRY_COL_MAX_WIDTH ); const environmentIds = [ subEnvironmentId ?? [props.envParentId, localsUserId].join("|"), ]; const gridProps = { ...props, environmentIds: environmentIds, entryColWidth, valColWidth: selectedWidth - entryColWidth, }; return props.envParentType == "app" ? ( <ui.AppEnvGrid {...gridProps} visibleEnvironmentIds={environmentIds} /> ) : ( <ui.BlockEnvGrid {...gridProps} visibleEnvironmentIds={environmentIds} /> ); } }; if (subEnvironments.length == 0 && !environmentRole.hasLocalKeys) { return <div>{renderNewForm()}</div>; } return ( <div className={styles.SubEnvs}> <section className={ "sub-selected " + style({ marginLeft: listWidth, }) } > {renderSelected()} </section> <section className={ "sub-list " + style({ width: listWidth, height: `calc(100% - ${ styles.layout.MAIN_HEADER_HEIGHT + props.ui.pendingFooterHeight }px)`, transition: "height", transitionDuration: "0.2s", }) } > {renderList()} </section> </div> ); };
the_stack
import { DEFAULT_PLACEHOLDER_CHAR, FormatCharacters, mergeFormatCharacters } from './helpers'; import { Pattern } from './Pattern'; type SelectionObject = { start: number; end: number }; type Options = { formatCharacters: FormatCharacters; pattern: string; isRevealingMask: boolean; placeholderChar: string; selection: SelectionObject; value: string; }; export class InputMask { static Pattern = Pattern; formatCharacters!: FormatCharacters; pattern!: Pattern; isRevealingMask!: boolean; placeholderChar!: string; selection!: SelectionObject; value!: string[]; emptyValue = ''; _history: { value: string; selection: SelectionObject; lastOp: string | null; startUndo?: boolean; }[] = []; _historyIndex: null | number = null; _lastOp: null | string = null; _lastSelection: null | SelectionObject = null; constructor(options: Partial<Options>) { const mergedOptions: Options = { ...{ isRevealingMask: false, placeholderChar: DEFAULT_PLACEHOLDER_CHAR, selection: { start: 0, end: 0 }, value: '' }, ...options } as Options; if (!mergedOptions.pattern) { throw new Error('InputMask: you must provide a pattern.'); } if ( typeof mergedOptions.placeholderChar !== 'string' || mergedOptions.placeholderChar.length > 1 ) { throw new Error( 'InputMask: placeholderChar should be a single character or an empty string.' ); } this.placeholderChar = mergedOptions.placeholderChar; this.formatCharacters = mergeFormatCharacters( mergedOptions.formatCharacters ); this.setPattern(mergedOptions.pattern, { value: mergedOptions.value, selection: mergedOptions.selection, isRevealingMask: mergedOptions.isRevealingMask }); } setPattern(patternSource: string, options: Partial<Options>) { const merged = { selection: { start: 0, end: 0 }, value: '', ...options }; this.pattern = new Pattern( patternSource, this.formatCharacters, this.placeholderChar, merged.isRevealingMask ); this.setValue(merged.value); this.emptyValue = this.pattern.formatValue([]).join(''); this.selection = merged.selection; this._resetHistory(); } setValue(value?: string) { if (value == null) { value = ''; } this.value = this.pattern.formatValue((value || '').split('')); } _resetHistory() { this._history = []; this._historyIndex = null; this._lastOp = null; this._lastSelection = { ...this.selection }; } getValue(): string { if (this.pattern.isRevealingMask) { this.value = this.pattern.formatValue( (this.getRawValue() || '').split('') ); } return (this.value || []).join(''); } getRawValue(): string { var rawValue = []; for (var i = 0; i < this.value.length; i++) { if (this.pattern._editableIndices[i] === true) { rawValue.push(this.value[i]); } } return rawValue.join(''); } /** * Applies a single character of input based on the current selection. * @param {string} char * @return {boolean} true if a change has been made to value or selection as a * result of the input, false otherwise. */ input(char: string) { // Ignore additional input if the cursor's at the end of the pattern if ( this.selection.start === this.selection.end && this.selection.start === this.pattern.length ) { return false; } const selectionBefore = copy(this.selection); const valueBefore = this.getValue(); let inputIndex = this.selection.start; // If the cursor or selection is prior to the first editable character, make // sure any input given is applied to it. if (inputIndex < this.pattern.firstEditableIndex) { inputIndex = this.pattern.firstEditableIndex; } // Bail out or add the character to input if (this.pattern.isEditableIndex(inputIndex)) { if (!this.pattern.isValidAtIndex(char, inputIndex)) { return false; } this.value[inputIndex] = this.pattern.transform(char, inputIndex); } else { console.log('not editable'); } // If multiple characters were selected, blank the remainder out based on the // pattern. let end = this.selection.end - 1; while (end > inputIndex) { if (this.pattern.isEditableIndex(end)) { this.value[end] = this.placeholderChar; } end--; } // Advance the cursor to the next character this.selection.start = this.selection.end = inputIndex + 1; // Skip over any subsequent static characters while ( this.pattern.length > this.selection.start && !this.pattern.isEditableIndex(this.selection.start) ) { this.selection.start++; this.selection.end++; } // History if (this._historyIndex != null) { // Took more input after undoing, so blow any subsequent history away this._history.splice( this._historyIndex, this._history.length - this._historyIndex ); this._historyIndex = null; } if ( this._lastOp !== 'input' || selectionBefore.start !== selectionBefore.end || (this._lastSelection !== null && selectionBefore.start !== this._lastSelection.start) ) { this._history.push({ value: valueBefore, selection: selectionBefore, lastOp: this._lastOp }); } this._lastOp = 'input'; this._lastSelection = copy(this.selection); return true; } /** * Attempts to delete from the value based on the current cursor position or * selection. * @return {boolean} true if the value or selection changed as the result of * backspacing, false otherwise. */ backspace() { // If the cursor is at the start there's nothing to do if (this.selection.start === 0 && this.selection.end === 0) { return false; } var selectionBefore = { ...this.selection }; var valueBefore = this.getValue(); // No range selected - work on the character preceding the cursor if (this.selection.start === this.selection.end) { if (this.pattern.isEditableIndex(this.selection.start - 1)) { if (this.pattern.isRevealingMask) { this.value.splice(this.selection.start - 1); } else { this.value[this.selection.start - 1] = this.placeholderChar; } } this.selection.start--; this.selection.end--; } // Range selected - delete characters and leave the cursor at the start of the selection else { var end = this.selection.end - 1; while (end >= this.selection.start) { if (this.pattern.isEditableIndex(end)) { this.value[end] = this.placeholderChar; } end--; } this.selection.end = this.selection.start; } // History if (this._historyIndex != null) { // Took more input after undoing, so blow any subsequent history away this._history.splice( this._historyIndex, this._history.length - this._historyIndex ); } if ( this._lastOp !== 'backspace' || selectionBefore.start !== selectionBefore.end || (this._lastSelection !== null && selectionBefore.start !== this._lastSelection.start) ) { this._history.push({ value: valueBefore, selection: selectionBefore, lastOp: this._lastOp }); } this._lastOp = 'backspace'; this._lastSelection = { ...this.selection }; return true; } /** * Attempts to paste a string of input at the current cursor position or over * the top of the current selection. * Invalid content at any position will cause the paste to be rejected, and it * may contain static parts of the mask's pattern. * @param {string} input * @return {boolean} true if the paste was successful, false otherwise. */ paste(input: string) { // This is necessary because we're just calling input() with each character // and rolling back if any were invalid, rather than checking up-front. var initialState = { value: this.value.slice(), selection: { ...this.selection }, _lastOp: this._lastOp, _history: this._history.slice(), _historyIndex: this._historyIndex, _lastSelection: { ...this._lastSelection } }; // If there are static characters at the start of the pattern and the cursor // or selection is within them, the static characters must match for a valid // paste. if (this.selection.start < this.pattern.firstEditableIndex!) { for ( var i = 0, l = this.pattern.firstEditableIndex! - this.selection.start; i < l; i++ ) { if (input.charAt(i) !== this.pattern.pattern[i]) { return false; } } // Continue as if the selection and input started from the editable part of // the pattern. input = input.substring( this.pattern.firstEditableIndex! - this.selection.start ); this.selection.start = this.pattern.firstEditableIndex!; } for ( i = 0, l = input.length; i < l && this.selection.start <= this.pattern.lastEditableIndex!; i++ ) { var valid = this.input(input.charAt(i)); // Allow static parts of the pattern to appear in pasted input - they will // already have been stepped over by input(), so verify that the value // deemed invalid by input() was the expected static character. if (!valid) { if (this.selection.start > 0) { // XXX This only allows for one static character to be skipped var patternIndex = this.selection.start - 1; if ( !this.pattern.isEditableIndex(patternIndex) && input.charAt(i) === this.pattern.pattern[patternIndex] ) { continue; } } Object.keys(initialState).forEach(key => { // @ts-ignore this[key] = initialState[key]; }); return false; } } return true; } undo() { // If there is no history, or nothing more on the history stack, we can't undo if (this._history.length === 0 || this._historyIndex === 0) { return false; } var historyItem; if (this._historyIndex == null) { // Not currently undoing, set up the initial history index this._historyIndex = this._history.length - 1; historyItem = this._history[this._historyIndex]; // Add a new history entry if anything has changed since the last one, so we // can redo back to the initial state we started undoing from. var value = this.getValue(); if ( historyItem.value !== value || historyItem.selection.start !== this.selection.start || historyItem.selection.end !== this.selection.end ) { this._history.push({ value: value, selection: { ...this.selection }, lastOp: this._lastOp, startUndo: true }); } } else { historyItem = this._history[--this._historyIndex]; } this.value = historyItem.value.split(''); this.selection = historyItem.selection; this._lastOp = historyItem.lastOp; return true; } redo() { if (this._history.length === 0 || this._historyIndex == null) { return false; } var historyItem = this._history[++this._historyIndex]; // If this is the last history item, we're done redoing if (this._historyIndex === this._history.length - 1) { this._historyIndex = null; // If the last history item was only added to start undoing, remove it if (historyItem.startUndo) { this._history.pop(); } } this.value = historyItem.value.split(''); this.selection = historyItem.selection; this._lastOp = historyItem.lastOp; return true; } setSelection(selection: SelectionObject) { this.selection = { ...selection }; if (this.selection.start === this.selection.end) { if (this.selection.start < this.pattern.firstEditableIndex!) { this.selection!.start = this.selection!.end = this.pattern .firstEditableIndex as number; return true; } // Set selection to the first editable, non-placeholder character before the selection // OR to the beginning of the pattern var index = this.selection.start; while (index >= this.pattern.firstEditableIndex!) { if ( (this.pattern.isEditableIndex(index - 1) && this.value[index - 1] !== this.placeholderChar) || index === this.pattern.firstEditableIndex ) { this.selection.start = this.selection.end = index; break; } index--; } return true; } return false; } } function extend(dest: any, src: any) { if (src) { let props = Object.keys(src); for (var i = 0, l = props.length; i < l; i++) { dest[props[i]] = src[props[i]]; } } return dest; } function copy<T = any>(obj: T): T { return extend({}, obj); } export default InputMask;
the_stack
import {Observable, Subject} from 'rxjs'; import {Configuration} from './configuration'; import {UnitBase} from './abstract-unit-base'; import {NonPrimitiveUnitBase} from './abstract-non-primitive-unit-base'; import {isDict, isObject, isValidKey, IteratorSymbol, makeNonEnumerable} from '../utils/funcs'; import { DictUnitEvents, DictValue, EventDictUnitAssign, EventDictUnitDelete, EventDictUnitSet, KOf, UnitConfig, } from '../models'; /** * DictUnit is a reactive storage Unit that is loosely based on `Map`. * * It only accepts plain dictionary `object` as its value. * It ensures that at any point of time the value would always be a dictionary `object`. * * Learn more about Units [here](https://docs.activejs.dev/fundamentals/units). \ * Learn more about DictUnit [here](https://docs.activejs.dev/fundamentals/units/dictunit). * * Just like every other Non-Primitive ActiveJS Unit: * - DictUnit extends {@link NonPrimitiveUnitBase} * - Which further extends {@link UnitBase}, {@link Base} and `Observable` * * @category 1. Units */ export class DictUnit< T extends DictValue<T>, K extends keyof T = keyof T, V extends T[K] = T[K] > extends NonPrimitiveUnitBase<T> { /** * @internal please do not use. */ protected readonly eventsSubject: Subject<DictUnitEvents<T>>; /** * On-demand observable events. */ readonly events$: Observable<DictUnitEvents<T>>; /** * The length of keys of the properties in the dictionary {@link value}. */ get length(): number { return this.objectKeys().length; } /** * Indicates whether the length of the keys of the properties in the dictionary {@link value} is 0 or not. */ get isEmpty(): boolean { return this.length === 0; } /** * @internal please do not use. */ protected defaultValue(): T { return {} as T; } constructor(config?: UnitConfig<T>) { super({ ...(Configuration.DICT_UNIT as UnitConfig<T>), ...config, }); makeNonEnumerable(this); } /** * Extends {@link UnitBase.wouldDispatch} and adds additional check for Object dictionary {@link isDict}, * which cannot be bypassed even by using {@link force}. * * @param value The value to be dispatched. * @param force Whether dispatch-checks should be bypassed or not. * @returns A boolean indicating whether the param `value` would pass the dispatch-checks if dispatched. * * @category Common Units */ wouldDispatch(value: T, force?: boolean): boolean { return this.isValidValue(value) && super.wouldDispatch(value, force); } /** * Adds a property by setting given property-value on the given key in the dictionary {@link value}. \ * Also, dispatches it as new dictionary, without mutating the current {@link value}. * * It only works if the Unit is not frozen and the `key` is either `string` or `number`. * * @param key The name of the property. * @param value The property-value. * * @triggers {@link EventDictUnitSet} * @category Custom DictUnit */ set<k extends K>(key: k, value: T[k]): void { if (this.isFrozen || !isValidKey(key)) { return; } this.checkSerializabilityMaybe(value); const dictShallowCopy = {...this.rawValue()}; dictShallowCopy[key] = this.deepCopyMaybe(value); this.updateValueAndCache(dictShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventDictUnitSet(key, value)); } } /** * Deletes properties with given keys from the dictionary value. See {@link value}. \ * Deletion is performed on a copy of the value, which is then dispatched, without mutating the current value. * * It only works if the Unit is not frozen, and the value is not empty, \ * and at least one of the passed keys exist in the value. * ie: at least 1 key value pair exists in the dictionary. * * @param keys The names of the properties to be removed. * @returns The removed properties or an empty `object-literal`. * * @triggers {@link EventDictUnitDelete} * @category Custom DictUnit */ delete<k extends K>(...keys: k[]): {[key in k]: T[k]} { keys = keys.filter(key => this.has(key)); if (this.isFrozen || this.isEmpty || !keys.length) { return {} as any; } const dictShallowCopy: T = {...this.rawValue()}; const removedProps: {[key in k]: T[k]} = {} as any; keys.forEach(key => { removedProps[key] = this.deepCopyMaybe(dictShallowCopy[key]); delete dictShallowCopy[key]; }); this.updateValueAndCache(dictShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventDictUnitDelete(removedProps)); } return removedProps; } /** * Deletes properties from the dictionary {@link value} where the predicate returns `true`. \ * Also, dispatches it as new dictionary, without mutating the current {@link value}. * * It only works if the Unit is not frozen, and * the predicate is a function, and the dictionary is not empty. * * @param predicate A callback function that gets called for every property in the dictionary * with the property-value and key as arguments. * @returns The removed properties, or an empty `object-literal`. * * @triggers {@link EventDictUnitDelete} * @category Custom DictUnit */ deleteIf(predicate: (value: V, key: K, index: number) => boolean): T { if (this.isFrozen || typeof predicate !== 'function' || this.isEmpty) { return {} as any; } const dictShallowCopy = {...this.rawValue()}; const removedProps: T = {} as any; (Object.keys(dictShallowCopy) as K[]).forEach((key: K, index) => { if (predicate(this.deepCopyMaybe(dictShallowCopy[key]), key, index)) { removedProps[key] = dictShallowCopy[key]; delete dictShallowCopy[key]; } }); this.updateValueAndCache(dictShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventDictUnitDelete(removedProps)); } return removedProps; } /** * Copy the values of all the enumerable own properties from one or more source objects to the dictionary. \ * Also, dispatches it as new dictionary, without mutating the current {@link value}. * * It only works if the Unit is not frozen, and at least 1 source is provided, and it is a non-null object. * eg: `array`, `object` * * @param sources The source objects from which to copy properties. * * @triggers {@link EventDictUnitAssign} * @category Custom DictUnit */ assign(...sources: T[]): void { sources = sources.filter(isObject); if (this.isFrozen || !sources.length) { return; } this.checkSerializabilityMaybe(sources); const dictShallowCopy = {...this.rawValue()}; const newProps = Object.assign({}, ...sources); this.updateValueAndCache(Object.assign(dictShallowCopy, this.deepCopyMaybe(newProps))); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventDictUnitAssign(sources, newProps)); } } /** * Returns the value of the property with the name equal to the given key in the dictionary {@link value}. * * It only returns own-properties, e.g.: key 'toString' would return `undefined`. * * @param key The name of the property. * * @category Custom DictUnit */ get<k extends K>(key: k): T[k] | undefined { return this.hasOwnProperty(key) ? this.deepCopyMaybe(this.rawValue()[key]) : undefined; } /** * Returns whether a property with the given key exists in the dictionary {@link value}. * * @param key The name of the property. * * @category Custom DictUnit */ has<k extends K>(key: k): boolean { return this.hasOwnProperty(key); } /** * Finds direct properties of the dictionary that have a direct child property * that matches with `key` and `value` passed as params. * * @example * ```ts * const initialValue = {'first': {b: 1}, 'second': {b: 1, b2: 2}, 'third': {c: 1}, 'fourth': {b: null}}; * const dict = new DictUnit({initialValue}); * const itemsFound = dict.findByProp('b', 1); * console.log(itemsFound); // logs [['first', {b: 1}], ['second', {b: 1, b2: 2}]] * ``` * * @param key The key of the property whose value needs to be matched against param `value`. * @param value A primitive value that will be matched against every item's prop-value using equality operator. * @param strictEquality A flag governing whether the value be matched using `===` or `==` operator. * Default is `true`, ie: strict equality `===`. Pass `false` to use `==` instead. * @returns An `array` of key/values of the matched properties, an empty `array` otherwise. * * @category Custom DictUnit */ findByProp<k extends KOf<V>>( key: k, value: string | number | boolean, strictEquality = true ): [K, V][] { if (this.isEmpty) { return []; } return this.deepCopyMaybe( (Object.entries<V>(this.rawValue()) as [K, V][]).filter( ([propKey, prop]) => isObject(prop) && (strictEquality === false ? // tslint:disable-next-line:triple-equals prop[key as string | number] == value : prop[key as string | number] === value) ) ); } /** * Performs the specified action for each property in the object value. See {@link value}. \ * It's a drop-in replacement for the `forEach` method. * * @param callbackFn A function that accepts up to two arguments. * forEvery calls the callbackFn function one time for each property in the object value. * @param thisArg An object to which this keyword can refer in the callbackFn function. * If thisArg is omitted, undefined is used as this value. * * @category Custom DictUnit */ forEvery( callbackFn: (value: V, key: K, index: number, entries: [K, V][]) => void, thisArg?: any ): void { this.objectEntries().forEach(([key, value], i, valueEntries) => callbackFn.call(thisArg, value, key, i, valueEntries) ); } /** Iterator */ [Symbol.iterator](): Iterator<[string, V]>; /** * @internal please do not use. */ [IteratorSymbol](): Iterator<[string, V]> { let index = 0; const items: [string, V][] = this.objectEntries(); const length: number = items.length; return { next(): IteratorResult<[string, V]> { return {value: items[index++], done: index > length}; }, }; } /** * @internal please do not use. */ protected isValidValue(value: any): boolean { return isDict(value); } }
the_stack
import { Injectable } from '@angular/core'; import { HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { AdalService } from './adal.service'; import { CONFIGURATIONS } from './../../../config/configurations'; import { OnPremAuthenticationService } from './onprem-authentication.service'; import { Router } from '@angular/router'; import { AssetGroupObservableService } from './asset-group-observable.service'; import { LoggerService } from './../../shared/services/logger.service'; import { HttpService } from '../../shared/services/http-response.service'; import { DataCacheService } from './data-cache.service'; import { UtilsService } from '../../shared/services/utils.service'; import { environment } from '../../../environments/environment'; import { CommonResponseService } from '../../shared/services/common-response.service'; @Injectable() export class AuthService { private adAuthentication; constructor(private adalService: AdalService, private onPremAuthentication: OnPremAuthenticationService, private router: Router, private assetGroupObservableService: AssetGroupObservableService, private loggerService: LoggerService, private httpService: HttpService, private dataStore: DataCacheService, private utilService: UtilsService, private commonResponseService: CommonResponseService, private logger: LoggerService) { this.adAuthentication = CONFIGURATIONS.optional.auth.AUTH_TYPE === 'azuresso'; } /* desc: This initiates the login process based on configuration */ doLogin() { if (this.authenticated) { const userDefaultAssetGroup = this.dataStore.getUserDefaultAssetGroup(); this.redirectPostLogin(userDefaultAssetGroup); } else { const loginUrl = '/home/login'; this.router.navigateByUrl(loginUrl).then(result => { this.loggerService.log('info', 'Redirected to login page successfully - ' + result); }, error => { this.loggerService.log('error', 'Error navigating to login - ' + error); }); } } doLogout() { if (this.adAuthentication) { this.clearSessionStorage(); this.adalService.logout(); } else { this.onPremAuthentication.logout(); this.clearSessionStorage(); } } clearSessionStorage() { this.dataStore.clearAll(); // Calling clear session from data store localStorage.setItem('logout', 'true'); localStorage.removeItem('logout'); } authenticateUserOnPrem(url, method, payload, headers) { return this.httpService.getHttpResponse(url, method, payload, {}, headers) .map(response => { return response; }) .catch(error => { return Observable.throw(error.message || error); }); } refreshToken() { // Write API code to refresh token try { const tokenObj = this.dataStore.getUserDetailsValue().getAuthToken(); if (!tokenObj || !tokenObj.refresh_token) { return null; } return new Observable(observer => { const refreshToken = tokenObj.refresh_token; const url = environment.refresh.url; const method = environment.refresh.method; const payload = { refreshToken: refreshToken }; let userLoginDetails = JSON.parse(this.dataStore.getCurrentUserLoginDetails()); this.commonResponseService.getData(url, method, payload, {}).subscribe(response => { if (response && response.success && response.access_token) { // Successful response /* Response will have user info and access tokens. */ userLoginDetails = response; this.dataStore.setCurrentUserLoginDetails(JSON.stringify(userLoginDetails)); observer.next(userLoginDetails.access_token); observer.complete(); } else { const errorMessage = response.message || 'Error renewing the access token'; this.logger.log('error ', errorMessage); observer.error(null); } }, error => { this.logger.log('info', '**Error renewing the access token**'); observer.error(null); }); }); } catch (error) { this.logger.log('error', 'JS Error - ' + error); } } getAuthToken() { /* Get the custom access token retuned from API */ // Get the token object from data store and return access token let accessToken; const tokenObject = this.dataStore.getUserDetailsValue().getAuthToken(); accessToken = tokenObject.access_token || null; return accessToken; } redirectPostLogin(defaultAssetGroup?) { const redirectUrl = this.redirectUrl; if (redirectUrl && redirectUrl !== '') { const redirect = this.utilService.getContextUrlExceptDomain(redirectUrl); if (redirect && this.redirectIsNotHomePage(redirect)) { this.router.navigateByUrl(redirect).then(result => { this.loggerService.log('info', 'returnUrl navigated successfully'); }, error => { this.loggerService.log('error', 'returnUrl - error in navigation - ' + error); }); } else { this.redirectToPostLoginDefault(defaultAssetGroup); } } else { this.redirectToPostLoginDefault(defaultAssetGroup); } } private redirectToPostLoginDefault(defaultAssetGroup) { let url; if (!defaultAssetGroup || defaultAssetGroup === '') { url = '/pl/first-time-user-journey'; } else { this.assetGroupObservableService.updateAssetGroup(defaultAssetGroup); url = '/pl/compliance/compliance-dashboard?ag=' + defaultAssetGroup; } this.router.navigateByUrl(url).then(result => { if ( result ) { this.loggerService.log('info', 'Successful navigation to ' + url); } else { this.loggerService.log('info', 'You are not authorised to access ' + url); } }, error => { this.loggerService.log('error', 'Error while navigating - ' + error); }); } get authenticated(): boolean { let authenticationStatus; // If adAuthentication is enabled for this app. if (this.adAuthentication) { authenticationStatus = this.adalService.userInfo ? this.adalService.userInfo.authenticated : false; } else { /* When on premise server authentication is enabled for application */ authenticationStatus = this.onPremAuthentication.isAuthenticated(); } return authenticationStatus; } get redirectUrl(): string { let redirectUrl = ''; redirectUrl = this.dataStore.getRedirectUrl() || redirectUrl; return redirectUrl; } redirectIsNotHomePage(redirect) { return redirect !== '/home' && redirect !== '/home/login'; } /* User informatin like user roles, user id */ setUserFetchedInformation() { try { const idToken = this.adalService.getIdToken(); const authToken = idToken; return new Observable(observer => { const url = environment.azureAuthorize.url; const method = environment.azureAuthorize.method; let headers: HttpHeaders = new HttpHeaders(); headers = headers.set('Content-Type', 'application/json'); headers = headers.set('Authorization', 'Bearer ' + authToken); const httpOptions = { headers: headers }; let userLoginDetails = JSON.parse(this.dataStore.getCurrentUserLoginDetails()); this.commonResponseService.getData(url, method, {}, {}, httpOptions).subscribe(response => { if (response && response.success) { // Successful response /* Response will have user info and access tokens. */ userLoginDetails = response; this.dataStore.setCurrentUserLoginDetails(JSON.stringify(userLoginDetails)); this.dataStore.setUserDefaultAssetGroup(userLoginDetails.userInfo.defaultAssetGroup); observer.next('success'); observer.complete(); } else { const errorMessage = response.message || 'Error authenticating the id_token'; this.logger.log('error ', errorMessage); userLoginDetails.userInfo.defaultAssetGroup = 'aws-all'; this.dataStore.setCurrentUserLoginDetails(JSON.stringify(userLoginDetails)); this.dataStore.setUserDefaultAssetGroup(userLoginDetails.userInfo.defaultAssetGroup); observer.error(errorMessage); } }, error => { this.logger.log('info', '**Error fetching the user roles from backend**'); userLoginDetails.userInfo.defaultAssetGroup = 'aws-all'; this.dataStore.setCurrentUserLoginDetails(JSON.stringify(userLoginDetails)); this.dataStore.setUserDefaultAssetGroup(userLoginDetails.userInfo.defaultAssetGroup); observer.error('error'); }); }); } catch (error) { this.logger.log('error', 'JS Error - ' + error); } } }
the_stack
import { TrieRoot, TrieNode } from '../TrieNode'; import { CompoundWordsMethod, JOIN_SEPARATOR, WORD_SEPARATOR } from './walker'; import { SuggestionGenerator, suggestionCollector, SuggestionResult } from './suggestCollector'; import { PairingHeap } from '../utils/PairingHeap'; import { visualLetterMaskMap } from './orthography'; import { createSuggestionOptions, GenSuggestionOptionsStrict, SuggestionOptions } from './genSuggestionsOptions'; export function* genCompoundableSuggestions( root: TrieRoot, word: string, options: GenSuggestionOptionsStrict ): SuggestionGenerator { const { compoundMethod, ignoreCase, changeLimit } = options; const len = word.length; const nodes = determineInitialNodes(root, ignoreCase); const noFollow = determineNoFollow(root); function compare(a: Candidate, b: Candidate): number { const deltaCost = a.g - b.g; if (deltaCost) return deltaCost; // The costs are the some return the one with the most progress. return b.i - a.i; } const opCosts = { baseCost: 100, swapCost: 75, duplicateLetterCost: 25, visuallySimilar: 1, firstLetterBias: 25, wordBreak: 99, } as const; const bc = opCosts.baseCost; const maxCostScale = 1.03 / 2; const mapSugCost = opCosts.visuallySimilar; const wordSeparator = compoundMethod === CompoundWordsMethod.JOIN_WORDS ? JOIN_SEPARATOR : WORD_SEPARATOR; const compoundIndicator = root.compoundCharacter; let costLimit = bc * Math.min(len * maxCostScale, changeLimit); let stopNow = false; const candidates = new PairingHeap(compare); const locationCache: LocationCache = new Map(); const wordsToEmit: EmitWord[] = []; const pathToLocation: Map<Path, LocationNode> = new Map(); const edgesToResolve: EdgeToResolve[] = []; const emittedWords = new Map<string, number>(); function updateCostLimit(maxCost: number | symbol | undefined) { switch (typeof maxCost) { case 'number': costLimit = Math.min(maxCost, costLimit); break; case 'symbol': stopNow = true; break; } } function getLocationNode(path: Path): LocationNode { const index = path.i; const node = path.n; const foundByIndex = locationCache.get(index); const byTrie: LocationByTriNode = foundByIndex || new Map<TrieNode, LocationNode>(); if (!foundByIndex) locationCache.set(index, byTrie); const f = byTrie.get(node); const n: LocationNode = f || { in: new Map(), er: [], bc: 0, p: path, sbc: -1, sfx: [] }; if (!f) byTrie.set(node, n); return n; } function* emitWord(word: string, cost: number): SuggestionGenerator { if (cost <= costLimit) { // console.log(`e: ${word} ${cost}`); const f = emittedWords.get(word); if (f !== undefined && f <= cost) return undefined; emittedWords.set(word, cost); const lastChar = word[word.length - 1]; if (!noFollow[lastChar]) { updateCostLimit(yield { word: word, cost: cost }); } } return undefined; } function* emitWords(): SuggestionGenerator { for (const w of wordsToEmit) { yield* emitWord(w.word, w.cost); } wordsToEmit.length = 0; return undefined; } function addEdgeToBeResolved(path: Path, edge: Edge) { path.r = path.r || new Set(); path.r.add(edge); } function addEdge(path: Path, edge: Edge): Edge | undefined { const g = path.g + edge.c; const i = edge.i; if (g > costLimit) return undefined; const { n } = edge; const w = path.w + edge.s; const can: Path = { e: edge, n, i, w, g, r: undefined, a: true }; const location = getLocationNode(can); location.er.push(edge); // Is Location Resolved if (location.sbc >= 0 && location.sbc <= can.g) { // No need to go further, this node has been resolved. // Return the edge to be resolved addEdgeToBeResolved(path, edge); edgesToResolve.push({ edge, suffixes: location.sfx }); return undefined; } const found = location.in.get(can.w); if (found) { // If the existing path is cheaper or the same keep it. // Do not add the edge. if (found.g <= can.g) return undefined; // Otherwise mark it as inactive and const e = found.e; if (e) { edgesToResolve.push({ edge: e, suffixes: [] }); } found.a = false; } addEdgeToBeResolved(path, edge); location.in.set(can.w, can); if (location.p.g > can.g) { pathToLocation.delete(location.p); location.sbc = -1; location.sfx.length = 0; location.p = can; } if (location.p === can) { // Make this path the representation of this location. pathToLocation.set(can, location); candidates.add(can); } return edge; } function opWordFound(best: Candidate): void { if (!best.n.f) return; const i = best.i; const toDelete = len - i; const edge: Edge = { p: best, n: best.n, i, s: '', c: bc * toDelete, a: Action.Delete }; addEdgeToBeResolved(best, edge); edgesToResolve.push({ edge, suffixes: [{ s: '', c: 0 }] }); if (compoundMethod && best.g + opCosts.wordBreak <= costLimit) { const s = wordSeparator; nodes.forEach((node) => { const e: Edge = { p: best, n: node, i, s, c: opCosts.wordBreak, a: Action.WordBreak }; addEdge(best, e); }); } } function opCompoundWord(best: Candidate): void { if (!best.n.c?.get(compoundIndicator)) return; const i = best.i; const s = ''; nodes.forEach((node) => { const n = node.c?.get(compoundIndicator); if (!n) return; const e: Edge = { p: best, n, i, s, c: opCosts.wordBreak, a: Action.CompoundWord }; addEdge(best, e); }); } function opInsert(best: Candidate): void { const children = best.n.c; if (!children) return; const i = best.i; const c = bc; for (const [s, n] of children) { const e: Edge = { p: best, n, i, s, c, a: Action.Insert }; addEdge(best, e); } } function opDelete(best: Candidate, num = 1): Edge | undefined { const i = best.i; const e: Edge = { p: best, n: best.n, i: i + num, s: '', c: bc * num, a: Action.Delete, // t: word.slice(i, i + num), }; return addEdge(best, e); } function opIdentity(best: Candidate): void { const s = word[best.i]; const n = best.n.c?.get(s); if (!n) return; const i = best.i + 1; const e: Edge = { p: best, n, i, s, c: 0, a: Action.Identity }; addEdge(best, e); } function opReplace(best: Candidate): void { const children = best.n.c; if (!children) return; const wc = word[best.i]; const wg = visualLetterMaskMap[wc] || 0; const i = best.i + 1; const cost = bc + (best.i ? 0 : opCosts.firstLetterBias); for (const [s, n] of children) { if (s == wc) continue; const sg = visualLetterMaskMap[s] || 0; const c = wg & sg ? mapSugCost : cost; const e: Edge = { p: best, n, i, s, c, a: Action.Replace /* , t: wc */ }; addEdge(best, e); } } function opSwap(best: Candidate): void { const children = best.n.c; const i = best.i; const i2 = i + 1; if (!children || len <= i2) return; const wc1 = word[i]; const wc2 = word[i2]; if (wc1 === wc2) return; const n = best.n.c?.get(wc2); const n2 = n?.c?.get(wc1); if (!n || !n2) return; const e: Edge = { p: best, n: n2, i: i2 + 1, s: wc2 + wc1, c: opCosts.swapCost, a: Action.Swap, // , t: wc1 + wc2, }; addEdge(best, e); } function opDuplicate(best: Candidate): void { const children = best.n.c; const i = best.i; const i2 = i + 1; if (!children || len <= i2) return; const wc1 = word[i]; const wc2 = word[i2]; const n = best.n.c?.get(wc1); if (!n) return; if (wc1 === wc2) { // convert double letter to single const e: Edge = { p: best, n, i: i + 2, s: wc1, c: opCosts.duplicateLetterCost, a: Action.Delete }; addEdge(best, e); return; } const n2 = n?.c?.get(wc1); if (!n2) return; // convert single to double letter const e: Edge = { p: best, n: n2, i: i2, s: wc1 + wc1, c: opCosts.duplicateLetterCost, a: Action.Insert }; addEdge(best, e); } function resolveEdges() { let e: EdgeToResolve | undefined; while ((e = edgesToResolve.shift())) { resolveEdge(e); } } function resolveLocationEdges(location: LocationNode, suffixes: Suffix[]) { for (const edge of location.er) { edgesToResolve.push({ edge, suffixes }); } } function resolveEdge({ edge, suffixes }: EdgeToResolve) { const { p, s: es, c: ec } = edge; if (!p.r?.has(edge)) return; const edgeSuffixes = suffixes.map((sfx) => ({ s: es + sfx.s, c: ec + sfx.c })); for (const { s, c } of edgeSuffixes) { const cost = p.g + c; if (cost <= costLimit) { const word = p.w + s; wordsToEmit.push({ word, cost }); } } p.r.delete(edge); const location = pathToLocation.get(p); if (location?.p === p) { location.sfx = location.sfx.concat(edgeSuffixes); if (!p.r.size) { location.sbc = p.g; resolveLocationEdges(location, edgeSuffixes); } } else if (!p.r.size) { if (p.e) { // Keep rolling up. edgesToResolve.push({ edge: p.e, suffixes: edgeSuffixes }); } } } function cancelEdges(path: Path) { if (!path.r) return; const suffixes: Suffix[] = []; for (const edge of path.r) { edgesToResolve.push({ edge, suffixes }); } } /************ * Below is the core of the A* algorithm */ updateCostLimit(yield undefined); nodes.forEach((node, idx) => { const g = idx ? 1 : 0; candidates.add({ e: undefined, n: node, i: 0, w: '', g, r: undefined, a: true }); }); const iterationsBeforePolling = 100; let i = iterationsBeforePolling; let maxSize = 0; let best: Candidate | undefined; // const bc2 = 2 * bc; while (!stopNow && (best = candidates.dequeue())) { if (--i < 0) { i = iterationsBeforePolling; updateCostLimit(yield undefined); } maxSize = Math.max(maxSize, candidates.length); if (!best.a) { // best's edges are already part of a location node. continue; } if (best.g > costLimit) { cancelEdges(best); continue; } const bi = best.i; opWordFound(best); const children = best.n.c; if (!children) continue; if (bi === len) { opInsert(best); } else { opIdentity(best); opReplace(best); opDelete(best); opInsert(best); opSwap(best); opCompoundWord(best); opDuplicate(best); } resolveEdges(); yield* emitWords(); } resolveEdges(); yield* emitWords(); // console.log(` // word: ${word} // maxSize: ${maxSize} // length: ${candidates.length} // `); return undefined; } enum Action { Identity, Replace, Delete, Insert, Swap, CompoundWord, WordBreak, } interface Edge { /** from */ p: Path; /** to Node */ n: TrieNode; /** index into the original word */ i: number; /** suffix character to add to Path p. */ s: string; /** edge cost */ c: number; /** Action */ a: Action; /** Optional Transform */ // t?: string | undefined; } interface Path { /** Edge taken to get here */ e: Edge | undefined; /** to Node */ n: TrieNode; /** index into the original word */ i: number; /** Suggested word so far */ w: string; /** cost so far */ g: number; /** active */ a: boolean; /** Edges to be resolved. */ r: Set<Edge> | undefined; } interface Suffix { /** suffix */ s: string; /** Cost of using suffix */ c: number; } interface LocationNode { /** Incoming Paths */ in: Map<string, Path>; /** Edges to Resolve when Location is Resolved */ er: Edge[]; /** Best Possible cost - only non-zero when location has been resolved. */ bc: number; /** Pending Path to be resolved */ p: Path; /** * Suffix Base Cost * The base cost used when calculating the suffixes. * If a new path comes in with a lower base cost, * then the suffixes need to be recalculated. */ sbc: number; /** Set of suffixes, calculated when location has been resolved. */ sfx: Suffix[]; } type LocationByTriNode = Map<TrieNode, LocationNode>; type LocationCache = Map<number, LocationByTriNode>; type Candidate = Path; type NoFollow = Record<string, true | undefined>; interface EmitWord { word: string; cost: number; } interface EdgeToResolve { edge: Edge; suffixes: Suffix[]; } export function suggest(root: TrieRoot | TrieRoot[], word: string, options: SuggestionOptions): SuggestionResult[] { const opts = createSuggestionOptions(options); const collector = suggestionCollector(word, { numSuggestions: opts.numSuggestions, changeLimit: opts.changeLimit, includeTies: opts.includeTies, ignoreCase: opts.ignoreCase, timeout: opts.timeout, }); collector.collect(genSuggestions(root, word, opts)); return collector.suggestions; } export function* genSuggestions( root: TrieRoot | TrieRoot[], word: string, options: GenSuggestionOptionsStrict ): SuggestionGenerator { const roots = Array.isArray(root) ? root : [root]; for (const r of roots) { yield* genCompoundableSuggestions(r, word, options); } return undefined; } function determineNoFollow(root: TrieRoot): NoFollow { const noFollow: NoFollow = Object.assign(Object.create(null), { [root.compoundCharacter]: true, [root.forbiddenWordPrefix]: true, [root.stripCaseAndAccentsPrefix]: true, }); return noFollow; } function determineInitialNodes(root: TrieRoot | TrieRoot[], ignoreCase: boolean): TrieNode[] { const roots = Array.isArray(root) ? root : [root]; const rootNodes: TrieNode[] = roots; const noCaseNodes = ignoreCase ? roots .filter((r) => r.stripCaseAndAccentsPrefix) .map((n) => n.c?.get(n.stripCaseAndAccentsPrefix)) .filter(isDefined) : []; const nodes: TrieNode[] = rootNodes.concat(noCaseNodes); return nodes; } function isDefined<T>(v: T | undefined): v is T { return v !== undefined; }
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/youtubeAnalytics/v1/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load YouTube Analytics API v1 */ function load(name: "youtubeanalytics", version: "v1"): PromiseLike<void>; function load(name: "youtubeanalytics", version: "v1", callback: () => any): void; const groupItems: youtubeanalytics.GroupItemsResource; const groups: youtubeanalytics.GroupsResource; const reports: youtubeanalytics.ReportsResource; namespace youtubeanalytics { interface Group { contentDetails?: { itemCount?: string; itemType?: string; }; etag?: string; id?: string; kind?: string; snippet?: { publishedAt?: string; title?: string; }; } interface GroupItem { etag?: string; groupId?: string; id?: string; kind?: string; resource?: { id?: string; kind?: string; }; } interface GroupItemListResponse { etag?: string; items?: GroupItem[]; kind?: string; } interface GroupListResponse { etag?: string; items?: Group[]; kind?: string; nextPageToken?: string; } interface ResultTable { /** * This value specifies information about the data returned in the rows fields. Each item in the columnHeaders list identifies a field returned in the * rows value, which contains a list of comma-delimited data. The columnHeaders list will begin with the dimensions specified in the API request, which * will be followed by the metrics specified in the API request. The order of both dimensions and metrics will match the ordering in the API request. For * example, if the API request contains the parameters dimensions=ageGroup,gender&metrics=viewerPercentage, the API response will return columns in this * order: ageGroup,gender,viewerPercentage. */ columnHeaders?: Array<{ /** The type of the column (DIMENSION or METRIC). */ columnType?: string; /** The type of the data in the column (STRING, INTEGER, FLOAT, etc.). */ dataType?: string; /** The name of the dimension or metric. */ name?: string; }>; /** This value specifies the type of data included in the API response. For the query method, the kind property value will be youtubeAnalytics#resultTable. */ kind?: string; /** * The list contains all rows of the result table. Each item in the list is an array that contains comma-delimited data corresponding to a single row of * data. The order of the comma-delimited data fields will match the order of the columns listed in the columnHeaders field. If no data is available for * the given query, the rows element will be omitted from the response. The response for a query with the day dimension will not contain rows for the most * recent days. */ rows?: any[][]; } interface GroupItemsResource { /** Removes an item from a group. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The id parameter specifies the YouTube group item ID for the group that is being deleted. */ id: 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; /** * Note: This parameter is intended exclusively for YouTube content partners. * * The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the * content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube * channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. */ onBehalfOfContentOwner?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<void>; /** Creates a group item. */ 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; /** * Note: This parameter is intended exclusively for YouTube content partners. * * The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the * content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube * channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. */ onBehalfOfContentOwner?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<GroupItem>; /** Returns a collection of group items that match the API request parameters. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The id parameter specifies the unique ID of the group for which you want to retrieve group items. */ groupId: 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; /** * Note: This parameter is intended exclusively for YouTube content partners. * * The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the * content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube * channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. */ onBehalfOfContentOwner?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<GroupItemListResponse>; } interface GroupsResource { /** Deletes a group. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The id parameter specifies the YouTube group ID for the group that is being deleted. */ id: 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; /** * Note: This parameter is intended exclusively for YouTube content partners. * * The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the * content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube * channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. */ onBehalfOfContentOwner?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<void>; /** Creates a group. */ 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; /** * Note: This parameter is intended exclusively for YouTube content partners. * * The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the * content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube * channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. */ onBehalfOfContentOwner?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<Group>; /** * Returns a collection of groups that match the API request parameters. For example, you can retrieve all groups that the authenticated user owns, or you * can retrieve one or more groups by their unique IDs. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * The id parameter specifies a comma-separated list of the YouTube group ID(s) for the resource(s) that are being retrieved. In a group resource, the id * property specifies the group's YouTube group ID. */ id?: 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; /** Set this parameter's value to true to instruct the API to only return groups owned by the authenticated user. */ mine?: boolean; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Note: This parameter is intended exclusively for YouTube content partners. * * The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the * content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube * channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. */ onBehalfOfContentOwner?: string; /** * The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken property identifies * the next page that can be retrieved. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<GroupListResponse>; /** Modifies a group. For example, you could change a group's title. */ update(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; /** * Note: This parameter is intended exclusively for YouTube content partners. * * The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the * content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube * channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication * credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. */ onBehalfOfContentOwner?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * 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; }): Request<Group>; } interface ReportsResource { /** Retrieve your YouTube Analytics reports. */ query(request: { /** Data format for the response. */ alt?: string; /** * The currency to which financial metrics should be converted. The default is US Dollar (USD). If the result contains no financial metrics, this flag * will be ignored. Responds with an error if the specified currency is not recognized. */ currency?: string; /** * A comma-separated list of YouTube Analytics dimensions, such as views or ageGroup,gender. See the Available Reports document for a list of the reports * that you can retrieve and the dimensions used for those reports. Also see the Dimensions document for definitions of those dimensions. */ dimensions?: string; /** The end date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format. */ "end-date": string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * A list of filters that should be applied when retrieving YouTube Analytics data. The Available Reports document identifies the dimensions that can be * used to filter each report, and the Dimensions document defines those dimensions. If a request uses multiple filters, join them together with a * semicolon (;), and the returned result table will satisfy both filters. For example, a filters parameter value of video==dMH0bHeiRNg;country==IT * restricts the result set to include data for the given video in Italy. */ filters?: string; /** * Identifies the YouTube channel or content owner for which you are retrieving YouTube Analytics data. * - To request data for a YouTube user, set the ids parameter value to channel==CHANNEL_ID, where CHANNEL_ID specifies the unique YouTube channel ID. * - To request data for a YouTube CMS content owner, set the ids parameter value to contentOwner==OWNER_NAME, where OWNER_NAME is the CMS name of the * content owner. */ ids: string; /** If set to true historical data (i.e. channel data from before the linking of the channel to the content owner) will be retrieved. */ "include-historical-channel-data"?: boolean; /** 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 maximum number of rows to include in the response. */ "max-results"?: number; /** * A comma-separated list of YouTube Analytics metrics, such as views or likes,dislikes. See the Available Reports document for a list of the reports that * you can retrieve and the metrics available in each report, and see the Metrics document for definitions of those metrics. */ metrics: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * A comma-separated list of dimensions or metrics that determine the sort order for YouTube Analytics data. By default the sort order is ascending. The * '-' prefix causes descending sort order. */ sort?: string; /** The start date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format. */ "start-date": string; /** An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter (one-based, inclusive). */ "start-index"?: number; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<ResultTable>; } } }
the_stack
import { Convert } from "../ExtensionMethods"; import { Dictionary, DictionaryWithStringKey } from "../AltDictionary"; import { EwsLogging } from "../Core/EwsLogging"; import { EwsServiceJsonReader } from "../Core/EwsServiceJsonReader"; import { Exception } from "../Exceptions/Exception"; import { ServiceError } from "../Enumerations/ServiceError"; import { XmlAttributeNames } from "../Core/XmlAttributeNames"; import { XmlElementNames } from "../Core/XmlElementNames"; /** * Represents SoapFault details. * * /remarks/ ews-javascript-api -> removing internal modifier to, this class will be used to pass on to error delegate of promise instead of Exceptions. * * /remarks/ ews-javascript-api -> 0.9 - Extending from Error object to avoid BlueBird errors when promise is rejected without and Error object * /remarks/ ews-javascript-api -> 0.9 - extending from Exception which looks like Error to BlueBird. can not extend from Error. Typescript 1.8+ can not extend builtin objects property, it swallows inheriting properties see https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work */ export class SoapFaultDetails extends Exception { private faultCode: string = null; private faultString: string = null; private faultActor: string = null; /** * Response code returned by EWS requests. * Default to InternalServerError. */ private responseCode: ServiceError = ServiceError.ErrorInternalServerError; /** * Message text of the error. */ message: string ; //not private to comply with Error object // ref: message is initialized in Exception class /** * This is returned by Availability requests. */ private errorCode: ServiceError = ServiceError.NoError; /** * This is returned by UM requests. It's the name of the exception that was raised. */ private exceptionType: string = null; /** * When a schema validation error is returned, this is the line number in the request where the error occurred. */ private lineNumber: number = 0; /** * When a schema validation error is returned, this is the offset into the line of the request where the error occurred. */ private positionWithinLine: number = 0; /** * Dictionary of key/value pairs from the MessageXml node in the fault. Usually empty but there are a few cases where SOAP faults may include MessageXml details (e.g. CASOverBudgetException includes BackoffTime value). */ private errorDetails: Dictionary<string, string> = new DictionaryWithStringKey<string>(); /** * @internal Gets or sets the SOAP fault code. * * @value The SOAP fault code. */ get FaultCode(): string { return this.faultCode; } set FaultCode(value: string) { this.faultCode = value; } /** * @internal Gets or sets the SOAP fault string. * * @value The fault string. */ get FaultString(): string { return this.faultString; } set FaultString(value: string) { this.faultString = value; } /** * @internal Gets or sets the SOAP fault actor. * * @value The fault actor. */ get FaultActor(): string { return this.faultActor; } set FaultActor(value: string) { this.faultActor = value; } /** * @internal Gets or sets the response code. * * @value The response code. */ get ResponseCode(): ServiceError { return this.responseCode; } set ResponseCode(value: ServiceError) { this.responseCode = value; } /** * @internal Gets or sets the message. * * @value The message. */ get Message(): string { return this.message; } set Message(value: string) { this.message = value; } /** * @internal Gets or sets the error code. * * @value The error code. */ get ErrorCode(): ServiceError { return this.errorCode; } set ErrorCode(value: ServiceError) { this.errorCode = value; } /** * @internal Gets or sets the type of the exception. * * @value The type of the exception. */ get ExceptionType(): string { return this.exceptionType; } set ExceptionType(value: string) { this.exceptionType = value; } /** * @internal Gets or sets the line number. * * @value The line number. */ get LineNumber(): number { return this.lineNumber; } set LineNumber(value: number) { this.lineNumber = value; } /** * @internal Gets or sets the position within line. * * @value The position within line. */ get PositionWithinLine(): number { return this.positionWithinLine; } set PositionWithinLine(value: number) { this.positionWithinLine = value; } /** * @internal Gets or sets the error details dictionary. * * @value The error details dictionary. */ get ErrorDetails(): Dictionary<string, string> { return this.errorDetails; } set ErrorDetails(value: Dictionary<string, string>) { this.errorDetails = value; } /** * Exception generated based on ExchangeService parsing * Exception property to carry this to caller. */ Exception: Exception; /** * ews-javascript-api specific: HTTP status code */ HttpStatusCode = 200; // /** // * @private Initializes a new instance of the **SoapFaultDetails** class. // */ // // constructor() { // // super(); // // } /** * @internal Parses the soap:Fault content. * * @param {any} jsObject The converted Xml JsObject. * @return {SoapFaultDetails} SOAP fault details. */ static Parse(jsObject: any): SoapFaultDetails { var soapFaultDetails = new SoapFaultDetails(); for (let key in jsObject) { switch (key) { case XmlElementNames.SOAPFaultCodeElementName: soapFaultDetails.FaultCode = jsObject[key]; break; case XmlElementNames.SOAPFaultStringElementName: soapFaultDetails.FaultString = jsObject[key]; break; case XmlElementNames.SOAPFaultActorElementName: soapFaultDetails.FaultActor = jsObject[key]; break; case XmlElementNames.SOAPDetailElementName: soapFaultDetails.ParseDetailNode(jsObject[key]); break; default: break; } } return soapFaultDetails; } /** * Parses the detail node. * * @param {any} jsObject The detail node. */ private ParseDetailNode(jsObject: any): void { for (let key in jsObject) { switch (key) { case XmlElementNames.EwsResponseCodeElementName: // ServiceError couldn't be mapped to enum value, treat as an ISE this.ResponseCode = ServiceError[<string>jsObject[key]] || ServiceError.ErrorInternalServerError;; break; case XmlElementNames.EwsMessageElementName: this.Message = jsObject[key]; break; case XmlElementNames.EwsLineElementName: this.LineNumber = Convert.toNumber(jsObject[key]); break; case XmlElementNames.EwsPositionElementName: this.PositionWithinLine = Convert.toNumber(jsObject[key]); break; case XmlElementNames.EwsErrorCodeElementName: // ServiceError couldn't be mapped to enum value, treat as an ISE this.ErrorCode = ServiceError[<string>jsObject[key]] || ServiceError.ErrorInternalServerError; break; case XmlElementNames.EwsExceptionTypeElementName: this.ExceptionType = jsObject[key]; break; case XmlElementNames.MessageXml: this.ParseMessageXml(jsObject[key]); break; default: // Ignore any other details break; } } } /** * Parses the message XML. * * @param {any} jsObject The message Xml object. */ private ParseMessageXml(jsObject: any): void { for (var key in jsObject) { if (key.indexOf("__") === 0) { continue; } switch (key) { case XmlElementNames.Value: let values = EwsServiceJsonReader.ReadAsArray(jsObject, key); values.forEach((value, index) => { let name = value[XmlAttributeNames.Name]; if (name) { if (this.ErrorDetails.containsKey(name)) { name = name + " - " + (index + 1) } this.errorDetails.Add(name, value[key]); } }); case XmlElementNames.EwsLineElementName: case "LineNumber": this.LineNumber = Convert.toNumber(jsObject[key]); break; case XmlElementNames.EwsPositionElementName: case "LinePosition": this.PositionWithinLine = Convert.toNumber(jsObject[key]); break; default: if (typeof jsObject[key] === "string") { this.errorDetails.addUpdate(key, jsObject[key]) } EwsLogging.Assert(false, "SoapFaultDetails.ParseMessageXml", "Element: " + key + " - Please report example of this operation to ews-javascript-api repo to improve SoapFault parsing"); break; } } } }
the_stack
import { Transaction } from "prosemirror-state"; import { ActionSetConfigValue, ActionRequestError, ActionRequestMatchesSuccess, ActionRequestMatchesForDocument, ActionRequestMatchesForDirtyRanges, ActionHandleNewDirtyRanges, ActionNewHoverIdReceived, ActionNewHighlightIdReceived, ActionSelectMatch, NEW_HOVER_ID, NEW_HIGHLIGHT_ID, REQUEST_FOR_DIRTY_RANGES, REQUEST_FOR_DOCUMENT, REQUEST_SUCCESS, REQUEST_ERROR, REQUEST_COMPLETE, SELECT_MATCH, REMOVE_MATCH, REMOVE_ALL_MATCHES, APPLY_NEW_DIRTY_RANGES, SET_CONFIG_VALUE, Action, ActionRequestComplete, ActionRemoveMatch, SET_FILTER_STATE, ActionSetFilterState } from "./actions"; import { IMatch, IRange, IMatchRequestError, IBlockWithSkippedRanges } from "../interfaces/IMatch"; import { DecorationSet, Decoration } from "prosemirror-view"; import omit from "lodash/omit"; import { createDebugDecorationFromRange, DECORATION_DIRTY, DECORATION_INFLIGHT, removeDecorationsFromRanges, DECORATION_MATCH, createDecorationsForMatch, createDecorationsForMatches, IMatchTypeToColourMap, defaultMatchColours } from "../utils/decoration"; import { mergeRanges, blockToRange, mapAndMergeRanges, mapRanges, findOverlappingRangeIndex, removeOverlappingRanges } from "../utils/range"; import { ExpandRanges, IFilterOptions } from "../createTyperighterPlugin"; import { getBlocksFromDocument } from "../utils/prosemirror"; import { Node } from "prosemirror-model"; import { selectSingleBlockInFlightById, selectBlockQueriesInFlightForSet, selectMatchByMatchId, selectBlockQueriesInFlightById } from "./selectors"; import { Mapping } from "prosemirror-transform"; import { createBlock, doNotSkipRanges, TGetSkippedRanges } from "../utils/block"; import { addMatchesToState, deriveFilteredDecorations, isFilterStateStale } from "./helpers"; import { TFilterMatches } from "../utils/plugin"; export interface IBlockInFlight { // The categories that haven't yet reported for this block. pendingCategoryIds: string[]; block: IBlockWithSkippedRanges; } /** * A consumer-supplied predicate that allows consumers to ignore matches. * Handy when, for example, consumers know that parts of the document are * exempt from checks. */ export type IIgnoreMatchPredicate = (match: IMatch) => boolean; export const includeAllMatches: IIgnoreMatchPredicate = () => false; export interface IBlocksInFlightState { totalBlocks: number; // The category ids that were sent with the request. categoryIds: string[]; pendingBlocks: IBlockInFlight[]; mapping: Mapping; } export interface IPluginConfig { // Should we trigger a request when the document is modified? requestMatchesOnDocModified: boolean; // Is the plugin in debug mode? Debug mode adds marks to show dirtied // and expanded ranges. debug: boolean; // The colours to use when rendering matches matchColours: IMatchTypeToColourMap; } export interface IPluginState< TFilterState extends unknown = unknown, TMatches extends IMatch = IMatch > { config: IPluginConfig; // The current decorations the plugin is applying to the document. decorations: DecorationSet; // The current matches for the document. currentMatches: TMatches[]; // The current matches, filtered by the current filterState and the // supplied filter predicate. This is cached in the state and only // recomputed when necessary – filtering decorations in the plugin // decoration mapping on every transaction is not performant. filteredMatches: TMatches[]; // The current ranges that are marked as dirty, that is, have been // changed since the last request. dirtiedRanges: IRange[]; // The currently selected match. selectedMatch: string | undefined; // The id of the match the user is currently hovering over – // e.g. to display a tooltip. hoverId: string | undefined; // The index of the clientRect closest to the hover mouseover event. // Spans can contain multiple clientRects when they're broken across lines. // By indicating which clientRect we're closest to, we can position our match // popup next to the correct section of the span. // See https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects. hoverRectIndex: number | undefined; // The id of the match the user is currently highlighting – // triggers a focus state on the match decoration. highlightId: string | undefined; // Are there requests pending: have ranges been dirtied but // not yet been expanded and sent in a request? requestPending: boolean; // The sets of blocks that have been sent to the matcher service // and have not yet completed processing. requestsInFlight: { [requestId: string]: IBlocksInFlightState; }; // The current error message. requestErrors: IMatchRequestError[]; // The current state of the filter filterState: TFilterState; // Has the document changed since the last document check? docChangedSinceCheck: boolean; } // The transaction meta key that namespaces our actions. export const PROSEMIRROR_TYPERIGHTER_ACTION = "PROSEMIRROR_TYPERIGHTER_ACTION"; interface IInitialStateOpts< TFilterState extends unknown, TMatch extends IMatch > { doc: Node; matches: TMatch[]; ignoreMatch: IIgnoreMatchPredicate; matchColours: IMatchTypeToColourMap; filterOptions: IFilterOptions<TFilterState, TMatch> | undefined; } /** * Initial state. */ export const createInitialState = < TFilterState extends unknown, TMatch extends IMatch >({ doc, matches = [], ignoreMatch = includeAllMatches, matchColours = defaultMatchColours, filterOptions }: IInitialStateOpts<TFilterState, TMatch>): IPluginState< TFilterState, TMatch > => { const initialState = { config: { debug: false, requestMatchesOnDocModified: false, matchColours }, decorations: DecorationSet.create( doc, createDecorationsForMatches(matches, matchColours) ), dirtiedRanges: [], currentMatches: [] as TMatch[], filteredMatches: [] as TMatch[], selectedMatch: undefined, hoverId: undefined, hoverRectIndex: undefined, highlightId: undefined, requestsInFlight: {}, requestPending: false, requestErrors: [], filterState: filterOptions?.initialFilterState as TFilterState, docChangedSinceCheck: false }; const stateWithMatches = addMatchesToState( initialState, doc, matches, ignoreMatch ); if (!filterOptions) { return stateWithMatches; } return deriveFilteredDecorations( doc, stateWithMatches, filterOptions.filterMatches ); }; export const createReducer = <TPluginState extends IPluginState>( expandRanges: ExpandRanges, ignoreMatch: IIgnoreMatchPredicate = includeAllMatches, filterMatches?: TFilterMatches< TPluginState["filterState"], TPluginState["currentMatches"][0] >, getIgnoredRanges: TGetSkippedRanges = doNotSkipRanges ) => { const handleMatchesRequestForDirtyRanges = createHandleMatchesRequestForDirtyRanges( expandRanges, getIgnoredRanges ); const handleMatchesRequestForDocument = createHandleMatchesRequestForDocument( getIgnoredRanges ); const handleNewHoverId = createHandleNewFocusState<TPluginState>("hoverId"); const handleNewHighlightId = createHandleNewFocusState<TPluginState>( "highlightId" ); return ( tr: Transaction, incomingState: TPluginState, action?: Action<TPluginState> ): TPluginState => { // There are certain things we need to do every time the document is changed, e.g. mapping ranges. const state = tr.docChanged ? getNewStateFromTransaction(tr, incomingState) : incomingState; if (!action) { return state; } const applyNewState = () => { switch (action.type) { case NEW_HOVER_ID: return handleNewHoverId(tr, state, action); case NEW_HIGHLIGHT_ID: return handleNewHighlightId(tr, state, action); case REQUEST_FOR_DIRTY_RANGES: return handleMatchesRequestForDirtyRanges(tr, state, action); case REQUEST_FOR_DOCUMENT: return handleMatchesRequestForDocument(tr, state, action); case REQUEST_SUCCESS: return handleMatchesRequestSuccess(ignoreMatch)(tr, state, action); case REQUEST_ERROR: return handleMatchesRequestError(tr, state, action); case REQUEST_COMPLETE: return handleRequestComplete(tr, state, action); case SELECT_MATCH: return handleSelectMatch(tr, state, action); case REMOVE_MATCH: return handleRemoveMatch(tr, state, action); case REMOVE_ALL_MATCHES: return handleRemoveAllMatches(tr, state); case APPLY_NEW_DIRTY_RANGES: return handleNewDirtyRanges(tr, state, action); case SET_CONFIG_VALUE: return handleSetConfigValue(tr, state, action); case SET_FILTER_STATE: return handleSetFilterState(tr, state, action); default: return state; } }; const newState = applyNewState(); if (!isFilterStateStale(state, newState, filterMatches)) { return newState; } return deriveFilteredDecorations(tr.doc, newState, filterMatches); }; }; /** * Get a new plugin state from the incoming transaction. * * We need to respond to each transaction in our reducer, whether or not there's * an action present, in order to maintain mappings and respond to user input. */ const getNewStateFromTransaction = <TPluginState extends IPluginState>( tr: Transaction, incomingState: TPluginState ): TPluginState => { const mappedRequestsInFlight = Object.entries( incomingState.requestsInFlight ).reduce((acc, [requestId, requestsInFlight]) => { // We create a new mapping here to preserve state immutability, as // appendMapping mutates an existing mapping. const mapping = new Mapping(); mapping.appendMapping(requestsInFlight.mapping); mapping.appendMapping(tr.mapping); return { ...acc, [requestId]: { ...requestsInFlight, mapping } }; }, {}); return { ...incomingState, decorations: incomingState.decorations.map(tr.mapping, tr.doc), dirtiedRanges: mapAndMergeRanges(incomingState.dirtiedRanges, tr.mapping), currentMatches: mapRanges(incomingState.currentMatches, tr.mapping), requestsInFlight: mappedRequestsInFlight, docChangedSinceCheck: true }; }; /** * Action handlers. */ /** * Handle the selection of a hover id. */ const handleSelectMatch = <TPluginState extends IPluginState>( _: unknown, state: TPluginState, action: ActionSelectMatch ): TPluginState => { return { ...state, selectedMatch: action.payload.matchId }; }; /** * Remove a match and its decoration from the state. */ const handleRemoveMatch = <TPluginState extends IPluginState>( _: unknown, state: TPluginState, { payload: { id } }: ActionRemoveMatch ): TPluginState => { const decorationToRemove = state.decorations.find( undefined, undefined, spec => spec.id === id ); const decorations = decorationToRemove ? state.decorations.remove(decorationToRemove) : state.decorations; const currentMatches = state.currentMatches.filter( match => match.matchId !== id ); return { ...state, decorations, currentMatches }; }; /** * Remove all matches and their decoration from the state. */ const handleRemoveAllMatches = <TPluginState extends IPluginState>( _: unknown, state: TPluginState ): TPluginState => { const decorationToRemove = state.decorations.find(); const decorations = decorationToRemove ? state.decorations.remove(decorationToRemove) : state.decorations; return { ...state, decorations, currentMatches: [], requestErrors: [] }; }; /** * Handle the receipt of a new focus state. */ const createHandleNewFocusState = <TPluginState extends IPluginState>( focusState: "highlightId" | "hoverId" ) => ( tr: Transaction, state: TPluginState, action: ActionNewHoverIdReceived | ActionNewHighlightIdReceived ): TPluginState => { let decorations = state.decorations; const incomingHoverId = action.payload.matchId; const currentHoverId = state[focusState]; // The current hover decorations are no longer valid -- remove them. const currentHoverDecorations = decorations.find( undefined, undefined, spec => (spec.id === currentHoverId || spec.id === incomingHoverId) && spec.type === DECORATION_MATCH ); decorations = decorations.remove(currentHoverDecorations); // Add the new decorations for the current and incoming matches. const decorationData = [{ id: incomingHoverId, isSelected: true }]; if (incomingHoverId !== currentHoverId) { decorationData.push({ id: currentHoverId, isSelected: false }); } decorations = decorationData.reduce((acc, hoverData) => { const output = selectMatchByMatchId(state, hoverData.id || ""); if (!output) { return acc; } return decorations.add( tr.doc, createDecorationsForMatch( output, state.config.matchColours, hoverData.isSelected ) ); }, decorations); const hoverRectIndex = action.type === "NEW_HOVER_ID" ? action.payload.rectIndex : state.hoverRectIndex; return { ...state, decorations, hoverRectIndex, [focusState]: action.payload.matchId }; }; const handleNewDirtyRanges = <TPluginState extends IPluginState>( tr: Transaction, state: TPluginState, { payload: { ranges: dirtiedRanges } }: ActionHandleNewDirtyRanges ): TPluginState => { // Map our dirtied ranges through the current transaction, and append any new ranges it has dirtied. let newDecorations = state.config.debug ? state.decorations.add( tr.doc, dirtiedRanges.map(range => createDebugDecorationFromRange(range)) ) : state.decorations; // Remove any matches and associated decorations touched by the dirtied ranges from the doc newDecorations = removeDecorationsFromRanges(newDecorations, dirtiedRanges); const currentMatches = state.currentMatches.filter( output => findOverlappingRangeIndex(output, dirtiedRanges) === -1 ); return { ...state, currentMatches, decorations: newDecorations, // We only care about storing dirtied ranges if we're validating // in response to user edits. requestPending: state.config.requestMatchesOnDocModified ? true : false, dirtiedRanges: state.config.requestMatchesOnDocModified ? state.dirtiedRanges.concat(dirtiedRanges) : [] }; }; /** * Handle a matches request for the current set of dirty ranges. */ const createHandleMatchesRequestForDirtyRanges = ( expandRanges: ExpandRanges, getIgnoredRanges: TGetSkippedRanges ) => <TPluginState extends IPluginState>( tr: Transaction, state: TPluginState, { payload: { requestId, categoryIds } }: ActionRequestMatchesForDirtyRanges ): TPluginState => { const ranges = expandRanges(state.dirtiedRanges, tr.doc); const blocks = ranges.map(range => createBlock(tr.doc, range, tr.time, getIgnoredRanges) ); return handleRequestStart(requestId, blocks, categoryIds)(tr, state); }; /** * Handle a matches request for the entire document. */ const createHandleMatchesRequestForDocument = ( getIgnoredRanges: TGetSkippedRanges ) => <TPluginState extends IPluginState>( tr: Transaction, state: TPluginState, { payload: { requestId, categoryIds } }: ActionRequestMatchesForDocument ): TPluginState => { return handleRequestStart( requestId, getBlocksFromDocument(tr.doc, tr.time, getIgnoredRanges), categoryIds )(tr, state); }; /** * Handle a matches request for a given set of blocks. */ const handleRequestStart = ( requestId: string, blocks: IBlockWithSkippedRanges[], categoryIds: string[] ) => <TPluginState extends IPluginState>( tr: Transaction, state: TPluginState ): TPluginState => { // Replace any debug decorations, if they exist. const decorations = state.config.debug ? removeDecorationsFromRanges(state.decorations, blocks, [ DECORATION_DIRTY ]).add( tr.doc, blocks.map(range => createDebugDecorationFromRange(range, false)) ) : state.decorations; const newBlockQueriesInFlight: IBlockInFlight[] = blocks.map(block => ({ block, pendingCategoryIds: categoryIds })); return { ...state, requestErrors: [], decorations, // We reset the dirty ranges, as they've been expanded and sent in a request. dirtiedRanges: [], requestPending: false, requestsInFlight: { ...state.requestsInFlight, [requestId]: { totalBlocks: newBlockQueriesInFlight.length, pendingBlocks: newBlockQueriesInFlight, mapping: tr.mapping, categoryIds } }, docChangedSinceCheck: false }; }; const amendBlockQueriesInFlight = ( state: IPluginState, requestId: string, blockId: string, categoryIds: string[] ) => { const currentBlockQueriesInFlight = selectBlockQueriesInFlightForSet( state, requestId ); if (!currentBlockQueriesInFlight) { return state.requestsInFlight; } const newBlockQueriesInFlight: IBlocksInFlightState = { ...currentBlockQueriesInFlight, pendingBlocks: currentBlockQueriesInFlight.pendingBlocks.reduce( (acc, blockInFlight) => { // Don't modify blocks that don't match if (blockInFlight.block.id !== blockId) { return acc.concat(blockInFlight); } const newBlockInFlight = { ...blockInFlight, pendingCategoryIds: blockInFlight.pendingCategoryIds.filter( id => !categoryIds.includes(id) ) }; return newBlockInFlight.pendingCategoryIds.length ? acc.concat(newBlockInFlight) : acc; }, [] as IBlockInFlight[] ) }; if (!newBlockQueriesInFlight.pendingBlocks.length) { return omit(state.requestsInFlight, requestId); } return { ...state.requestsInFlight, [requestId]: newBlockQueriesInFlight }; }; /** * Handle a response, decorating the document with any matches we've received. */ const handleMatchesRequestSuccess = (ignoreMatch: IIgnoreMatchPredicate) => < TMatch extends IMatch, TPluginState extends IPluginState<unknown, TMatch> >( tr: Transaction, state: TPluginState, { payload: { response } }: ActionRequestMatchesSuccess<TPluginState> ): TPluginState => { if (!response) { return state; } const requestsInFlight = selectBlockQueriesInFlightById( state, response.requestId, response.blocks.map(_ => _.id) ); if (!requestsInFlight.length) { return state; } // Remove matches superceded by the incoming matches. let currentMatches = removeOverlappingRanges( state.currentMatches, requestsInFlight.map(_ => _.block), match => !response.categoryIds.includes(match.category.id) ); // Remove decorations superceded by the incoming matches. const decsToRemove = requestsInFlight.reduce( (acc, blockInFlight) => acc.concat( state.decorations .find(blockInFlight.block.from, blockInFlight.block.to, spec => response.categoryIds.includes(spec.categoryId) ) .concat( state.config.debug ? // Ditch any decorations marking inflight matches. state.decorations.find( undefined, undefined, _ => _.type === DECORATION_INFLIGHT ) : [] ) ), [] as Decoration[] ); const matchesToAdd = response.matches.filter(match => !ignoreMatch(match)); const currentMapping = selectBlockQueriesInFlightForSet( state, response.requestId )!.mapping; const mappedMatchesToAdd = mapRanges(matchesToAdd, currentMapping); // Add the response to the current matches. currentMatches = currentMatches.concat(mappedMatchesToAdd); // We don't apply incoming matches to ranges that have // been dirtied since they were requested. currentMatches = removeOverlappingRanges(currentMatches, state.dirtiedRanges); // Create our decorations for the newly current matches. const newDecorations = createDecorationsForMatches( mappedMatchesToAdd, state.config.matchColours ); // Amend the block queries in flight to remove the returned blocks and categories const newBlockQueriesInFlight = requestsInFlight.reduce( (acc, blockInFlight) => amendBlockQueriesInFlight( { ...state, requestsInFlight: acc }, response.requestId, blockInFlight.block.id, response.categoryIds ), state.requestsInFlight ); return { ...state, requestsInFlight: newBlockQueriesInFlight, currentMatches, decorations: state.decorations .remove(decsToRemove) .add(tr.doc, newDecorations) }; }; /** * Handle a matches request error. */ const handleMatchesRequestError = <TPluginState extends IPluginState>( tr: Transaction, state: TPluginState, { payload: { matchRequestError } }: ActionRequestError ): TPluginState => { const { requestId, blockId, categoryIds } = matchRequestError; if (!blockId) { return { ...state, requestErrors: state.requestErrors.concat(matchRequestError) }; } const requestsInFlight = selectBlockQueriesInFlightForSet(state, requestId); if (!requestsInFlight) { return state; } const blockInFlight = selectSingleBlockInFlightById( state, requestId, blockId ); if (!blockInFlight) { return { ...state, requestErrors: state.requestErrors.concat(matchRequestError) }; } const dirtiedRanges = blockInFlight ? mapRanges([blockToRange(blockInFlight.block)], requestsInFlight.mapping) : []; const decsToRemove = dirtiedRanges.reduce( (acc, range) => acc.concat( state.decorations.find( range.from, range.to, _ => _.type === DECORATION_INFLIGHT ) ), [] as Decoration[] ); // When we get errors, we map the ranges due to be checked back // through the document and add them to the dirtied ranges to be // checked on the next pass. let decorations = state.decorations.remove(decsToRemove); if (dirtiedRanges.length && state.config.debug) { decorations = decorations.add( tr.doc, dirtiedRanges.map(range => createDebugDecorationFromRange(range)) ); } return { ...state, dirtiedRanges: dirtiedRanges.length ? mergeRanges(state.dirtiedRanges.concat(dirtiedRanges)) : state.dirtiedRanges, decorations, requestsInFlight: amendBlockQueriesInFlight( state, requestId, blockId, categoryIds ), requestErrors: state.requestErrors.concat(matchRequestError) }; }; const handleRequestComplete = <TPluginState extends IPluginState>( _: Transaction, state: TPluginState, { payload: { requestId } }: ActionRequestComplete ): TPluginState => { const requestInFlight = selectBlockQueriesInFlightForSet(state, requestId); const hasUnfinishedWork = requestInFlight && requestInFlight.pendingBlocks.some( block => block.pendingCategoryIds.length ); if (requestInFlight && hasUnfinishedWork) { /* tslint:disable-next-line:no-console */ console.warn( `Request ${requestId} was marked as complete, but there is still work remaining.`, requestInFlight.pendingBlocks ); } return { ...state, requestsInFlight: omit(state.requestsInFlight, requestId) }; }; const handleSetConfigValue = <TPluginState extends IPluginState>( _: Transaction, state: TPluginState, { payload: { key, value } }: ActionSetConfigValue ): TPluginState => ({ ...state, config: { ...state.config, [key]: value } }); const handleSetFilterState = <TPluginState extends IPluginState>( _: Transaction, state: TPluginState, { payload: { filterState } }: ActionSetFilterState<TPluginState> ): TPluginState => ({ ...state, filterState });
the_stack
import Index from "./indices"; import { IindexOptions, IStorageDriver, IRange, IupdateOptions, Isanitize, Iexist } from "./types"; import { Cursor, Ioptions} from "./index"; import { $set, $inc, $mul, $unset, $rename } from "./updateOperators"; import { getUUID, getDate} from "./utils"; import * as BTT from "binary-type-tree"; import { isEmpty, compressObj, expandObj, rmArrObjDups, flattenArr, saveArrDups, getObjValue } from "tedb-utils"; /** * ~~~ * Array String Number, Date, Boolean, -> symbol was redacted. : Used for keys * BTT.ASNDBS = Array<any[]|string|number|Date|boolean|null>|string|number|Date|boolean|null * -> redacted symbol, Number, Date, Boolean, String, Array : Used for values * BTT.SNDBSA = Array<{}|any[]|string|number|Date|boolean|null>; * ~~~ */ export interface IDatastore { insert(doc: any): Promise<any>; find(query: any): Cursor; count(query: any): Cursor; update(query: any, operation: any, options: IupdateOptions): Promise<any>; remove(query: any): Promise<number>; ensureIndex(options: IindexOptions): Promise<null>; san(fieldName: string, index: Index): Promise<any>; sanitize(): Promise<any>; storageSan(fieldName: string): Promise<any>; storageSanitize(): any; removeIndex(fieldName: string): Promise<null>; saveIndex(fieldName: string): Promise<null>; insertIndex(key: string, index: any[]): Promise<null>; getIndices(): Promise<any>; getDocs(options: Ioptions, ids: string | string[]): Promise<any[]>; search(fieldName: string, value: any): Promise<string[]>; } /** * Datastore class * * Example: * ~~~ * const UserStorage = new yourStorageClass("users"); * const Users = new Datastore({storage: UserStorage}); * ~~~ * Creates a new Datastore using a specified storageDriver */ export default class Datastore implements IDatastore { /** A HashMap of all the indices keyed by the fieldName. <fieldName, Index> */ private indices: Map<string, Index>; /** StorageDriver that is used for this Datastore */ private storage: IStorageDriver; /** whether or not to generate IDs automatically */ private generateId: boolean; /** * @param config - config object `{storage: IStorageDriver}` */ constructor(config: {storage: IStorageDriver}) { this.storage = config.storage; this.generateId = true; this.indices = new Map(); } /** * Insert a single document and insert any indices of document into * its respective binary tree. * * ~~~ * Users.insert({name: "xyz", age: 30}) * .then((doc) => console.log(doc)) // {_id: "...", name: "xyz", age: 30} * .catch((e) => console.log(e)); * ~~~ * * @param doc - document to insert * @returns {Promise<any>} */ public insert(doc: any): Promise<any> { return new Promise<any>((resolve, reject) => { if (isEmpty(doc)) { return reject(new Error("Cannot insert empty document")); } // doc._id = this.createId(); if (!doc.hasOwnProperty("_id")) { doc._id = this.createId(); } else if (doc._id.length !== 64) { doc._id = this.createId(); } const indexPromises: Array<Promise<any>> = []; this.indices.forEach((v) => { indexPromises.push(v.insert(doc)); }); Promise.all(indexPromises) .then((): any => { return this.storage.setItem(doc._id, doc); }) .then(resolve) .catch(reject); }); } /** * Find documents * * Examples: * ~~~ * Users.find() * .sort({age: -1}) * .skip(1) * .limit(10) * .exec() * .then((users) => console.log(users)) * .catch((e) => console.log(e)); * * Users.find({$or: [{name: "a"}, {name: "b"}]}) * .then((docs) => console.log(docs.length)) // 2 if unique * .catch((e) => console.log(e)); * * return Users.find({age: {$gt: 0, $lte: 27, $ne: 5}}); * * // sort from doc creation date. Auto generated by the _id * Users.find({}) * .sort({$created_at: -1}) // descending * .exec() * .then(resolve) * .catch(reject); * ~~~ * @param query * @returns {Cursor} */ public find(query: any = {}): Cursor { return new Cursor(this, query); } /** * Count documents * @param query */ public count(query: any = {}): Cursor { return new Cursor(this, query, true); } /** * Update document/s * * Examples: -> lets say two users {name: "bob", age: 1}, * {name: "slydel", age: 45, companies: {name: "Initech", alternate: "Intertrode"}} * ~~~ * Users.update({name: "bob"},{$rename: {name: "first"}, $set: {job: "consultant"}}, * {returnUpdatedDocs: true}) * .then((docs) => console.log(docs[0]) // {_id: "...", first: "bob", age: 1, job: "consultant"} * .catch(); * * Users.update({first: "bob"},{$unset: {"companies.alternate": ""}, $inc: {age: -44}, * $mul: {age: 5}}, {returnUpdatedDocs: true}) * .then((docs) => console.log(docs[0]) // {_id: "...", name: "bob", age: 5, companies: {name: "Initech"}} * .catch(); * * Users.update({name: "Charles", age: 22}, {$inc: {age: 4}}, {upser: true, returnUpdatedDocs: true}}) * .then((docs) => console.log(docs[0]) // {_id: "...", name: "Charles", age: 26} * .catch(); * * Users.update({age: {$gt: 0}},{$unset: {age: "", name: ""}},{ multi: true, returnUpdatedDocs: true}) * .then((docs) => console.log(docs)) // {_id: ".."}, {_id: ".."}, {_id: "..", companies: {name: "Initech"}} * .catch(); * ~~~ * @param query - query document/s to update * @param operation - update operation, either a new doc or modifies portions of a document(eg. `$set`) * @param options - { fieldName, unique?, compareKeys?, checkKeyEquality? } * @returns {Promise<any>} */ public update(query: any, operation: any, options: IupdateOptions = {}): Promise<any> { return new Promise<any>((resolve, reject) => { if (isEmpty(operation)) { return reject(new Error("No update without update operation")); } const promises: Array<Promise<any[]>> = []; const indexPromises: Array<Promise<null>> = []; const operators: string[] = ["$set", "$mul", "$inc", "$unset", "$rename"]; const multi: boolean = options.multi || false; const upsert: boolean = options.upsert || false; const exactObjectFind: boolean = options.exactObjectFind || false; const returnUpdatedDocs: boolean = options.returnUpdatedDocs || false; const operationKeys: string[] = Object.keys(operation); if (exactObjectFind) { // compresses all object + nested objects to "dot.notation"; const target: any = {}; compressObj(query, target); query = target; } if (multi) { return this.find(query) .exec() .then((res): any => { res = res as any[]; if (res.length === 0) { if (upsert) { if (exactObjectFind) { query = expandObj(query); } query._id = this.createId(); this.indices.forEach((v) => indexPromises.push(v.insert(query))); this.updateDocsIndices([query], promises, indexPromises, operation, operators, operationKeys, reject); } else { return []; } } else { // no return value, all are passed and used by reference. this.updateDocsIndices(res, promises, indexPromises, operation, operators, operationKeys, reject); } // If any index changes - error, reject and do not update and save. return Promise.all(indexPromises); }) .then(() => { return Promise.all(promises); }) .then((docs: any[]) => rmArrObjDups(docs, "_id")) .then((docs: any[]) => { const docPromises: Array<Promise<any[]>> = []; // save new docs to storage driver. docs.forEach((doc) => { docPromises.push(this.storage.setItem(doc._id, doc)); }); return Promise.all(docPromises); }) .then((res) => { if (returnUpdatedDocs) { resolve(res); } else { resolve(); } }) .catch(reject); } else { return this.find(query) .limit(1) .exec() .then((res) => { res = res as any[]; if (res.length === 0) { if (upsert) { if (exactObjectFind) { query = expandObj(query); } query._id = this.createId(); this.indices.forEach((v: Index) => { indexPromises.push(v.insert(query)); }); this.updateDocsIndices([query], promises, indexPromises, operation, operators, operationKeys, reject); } else { return []; } } else { this.updateDocsIndices(res, promises, indexPromises, operation, operators, operationKeys, reject); } return Promise.all(indexPromises); }) .then(() => { return Promise.all(promises); }) .then((docs: any[]) => { return rmArrObjDups(docs, "_id"); }) .then((docs: any[]) => { const docPromises: Array<Promise<any[]>> = []; // save new docs to storage driver. docs.forEach((doc) => { docPromises.push(this.storage.setItem(doc._id, doc)); }); return Promise.all(docPromises); }) .then((res) => { if (returnUpdatedDocs) { resolve(res); } else { resolve(); } }) .catch(reject); } }); } // public san(obj: any): Promise<any> { public san(fieldName: string, index: Index): Promise<any> { return new Promise((resolve, reject) => { // const values: any[] = []; return this.getIndices() .then((indices) => indices.get(fieldName)) .then((INDEX) => { const values: Isanitize[] = []; // Upgrade here if you ever get an error from a user // about there being a crash or slow down when they have an // extremely large index. millions. thousands of levels INDEX.traverse((ind: BTT.AVLNode) => { // values.push({key: ind.key, value: ind.value}); ind.value.forEach((i) => { if (i !== undefined && i !== null && i !== false) { values.push({key: ind.key, value: i}); } }); }); return values; }) .then((values) => { return Promise.all(values.map((obj: Isanitize) => { return this.storage.exists(obj, index, fieldName); })); }) .then((data: any[]) => { return Promise.all(data.map((d: any) => { if (d.doesExist) { return new Promise((res) => res()); } else { if (d.key === null) { return new Promise((res) => res()); } else { return d.index.removeByPair(d.key, d.value); } } })); }) .then(resolve) .catch(reject); }); } public storageSan(fieldName: string): Promise<any> { return new Promise((resolve, reject) => { return this.getIndices() .then((indices) => indices.get(fieldName)) .then((INDEX) => { const values: any[] = []; // upgrade here as well INDEX.traverse((ind: BTT.AVLNode) => { values.push(...ind.value.filter((i) => { if (i !== undefined && i !== null && i !== false) { return i; } })); }); return values; }) .then((values): Promise<any> => { return this.storage.collectionSanitize(values); }) .then(resolve) .catch(reject); }); } public storageSanitize(): any { return new Promise((resolve, reject) => { if (this.indices.size !== 0) { const fieldNames: Array<Promise<null>> = []; this.indices.forEach((i, fieldName) => { fieldNames.push(this.storageSan(fieldName)); }); return Promise.all(fieldNames) .then(resolve) .catch(reject); } else { // resolve, you have nothing to check against. return resolve(); } }); } /** * Method used after a remove depending on the want of the user * to make sure that if an _id exists in the index that it should * exist in the storage driver saved location. If not then the * indexed item is removed from the index as to not cause lookup * errors. * @returns {Promise<any>} */ public sanitize(): Promise<any> { return new Promise((resolve, reject) => { const fieldNames: any = []; this.indices.forEach((i, fieldName) => { fieldNames.push(this.san(fieldName, i)); }); return Promise.all(fieldNames) .then(resolve) .catch(reject); }); } /** * Removes document/s by query - uses find method to retrieve ids. multi always * @param query * @returns {Promise<number>} */ public remove(query: any = {}): Promise<number> { return new Promise((resolve, reject) => { const uniqueIds: string[] = []; this.find(query) .exec() .then((docs: any[]): Promise<any[][]> | any[] => { // Array of promises for index remove if (this.indices.size !== 0) { return Promise.all(docs.map((document) => { return Promise.all(Array.from(this.indices).map(([key, value]) => { return value.remove(document); })); })); } else { return docs; } }) .then((docs: any[]) => { docs = flattenArr(docs); return rmArrObjDups(docs, "_id"); }) .then((docs: any[]) => { docs.forEach((document) => { if (uniqueIds.indexOf(document._id) === -1) { uniqueIds.push(document._id); } }); return Promise.all(uniqueIds.map((id) => { if (id && (Object.prototype.toString.call(id) === "[object String]")) { return this.storage.removeItem(id); } else { return new Promise((res) => res()); } })); }) .then((): any => { resolve(uniqueIds.length); }) .catch(reject); }); } /** * Ensure an index on the datastore * * Example: * ~~~ * return Users.ensureIndex({fieldName: "username", unique: true}); * ~~~ * @param options * @returns {Promise<null>} */ public ensureIndex(options: IindexOptions): Promise<null> { return new Promise<null>((resolve, reject) => { try { this.indices.set(options.fieldName, new Index(this, options)); } catch (e) { return reject(e); } resolve(); }); } /** * Remove index will delete the index from the Map which also * holds the Btree of the indices. If you need to remove the * index from the persisted version in from the storage driver, * call the removeIndex from the storage driver from a different source. * This method should not assume you saved the index. * @param fieldName - Field that needs index removed * @returns {Promise<null>} */ public removeIndex(fieldName: string): Promise<null> { return new Promise<null>((resolve, reject) => { try { this.indices.delete(fieldName); } catch (e) { return reject(e); } resolve(); }); } /** * Save the index currently in memory to the persisted version if need be * through the storage driver. * @param fieldName * @returns {Promise<any>} */ public saveIndex(fieldName: string): Promise<null> { return new Promise<any>((resolve, reject) => { const index = this.indices.get(fieldName); if (index) { index.toJSON() .then((res) => { return this.storage.storeIndex(fieldName, res); }) .then(resolve) .catch(reject); } else { return reject(new Error(`No index with name ${fieldName} for this datastore`)); } }); } /** * Insert a stored index into the index of this datastore * @param key - the index fieldName * @param index - the key value pair obj * @returns {Promise<null>} */ public insertIndex(key: string, index: any[]): Promise<null> { return new Promise<null>((resolve, reject) => { try { const indices = this.indices.get(key); if (indices !== undefined) { indices.insertMany(key, index) .then(resolve) .catch((err) => { return reject(err); }); } else { return reject(new Error("No Index for this key was created on this datastore.")); } } catch (e) { return reject(e); } }); } /** * Retrieve the indices of this datastore. * * Example: * ~~~ * Users.getIndices() * .then((indices) => { * let usernameIndex = indices.get("username"); * if(usernameIndex) { * return usernameIndex.toJSON(); // a method on index bTree * } * }); // no reject, will always resolve * ~~~ * @returns {Promise<any>} */ public getIndices(): Promise<any> { return new Promise<any>((resolve, reject) => { if (this.indices) { resolve(this.indices); } else { reject(`No indices found in TeDB: ${this.indices}`); } }); } /** * Get Document by ID/s * Used internally * @param options - sort limit skip options * @param ids - ID or Array of IDs * @returns {Promise<any>} */ public getDocs(options: Ioptions, ids: string | string[]): Promise<any> { return new Promise<any>((resolve, reject) => { let idsArr: string[] = (typeof ids === "string") ? [ids] : ids; if (options.skip && options.limit) { idsArr = idsArr.splice(options.skip, options.limit); } else if (options.skip && !options.limit) { idsArr.splice(0, options.skip); } else if (options.limit && !options.skip) { idsArr = idsArr.splice(0, options.limit); } return this.createIdsArray(idsArr) .then(resolve) .catch(reject); }); } /** * Search for IDs, chooses best strategy. Handles logical operators($or, $and) * Returns array of IDs * Used Internally * @param fieldName - element name or query start $or/$and * @param value - string,number,date,null - or [{ field: value }, { field: value }] * @returns {Promise<T>} */ public search(fieldName?: string, value?: any): Promise<any> { return new Promise((resolve, reject) => { if (fieldName === "$or" && value instanceof Array) { const promises: Array<Promise<any>> = []; value.forEach((query): void => { for (const field in query) { if (typeof field === "string" && query.hasOwnProperty(field)) { promises.push(this.searchField(field, query[field])); } } }); Promise.all(promises) .then((idsArr: string[][]) => flattenArr(idsArr)) .then(resolve) .catch(reject); } else if (fieldName === "$and" && value instanceof Array) { const promises: Array<Promise<any>> = []; value.forEach((query): void => { for (const field in query) { if (typeof field === "string" && query.hasOwnProperty(field)) { promises.push(this.searchField(field, query[field])); } } }); Promise.all(promises) .then((idsArr: string[][]) => saveArrDups(idsArr)) .then(resolve) .catch(reject); } else if (fieldName !== "$or" && fieldName !== "$and" && fieldName) { this.searchField(fieldName, value) .then(resolve) .catch(reject); } else if ((fieldName === undefined) && (value === undefined)) { this.searchField() .then(resolve) .catch(reject); } else { return reject(new Error("Logical operators expect an Array")); } }); } /** * Get Date from ID ... do we need this on the dataStore? * * Example: * ~~~ * let id = "UE9UQVJWd0JBQUE9cmZ4Y2MxVzNlOFk9TXV4dmJ0WU5JUFk9d0FkMW1oSHY2SWs9"; // an ID * Users.getIdDate(id); // date object -> 2017-05-26T17:14:48.252Z * ~~~ * @param id - the `_id` of the document to get date of * @returns {Date} */ public getIdDate(id: string): Date { return getDate(id); } /** * Search for IDs, chooses best strategy, preferring to search indices if they exist for the given field. * Returns array of IDs * @param fieldName * @param value * @returns {Promise<BTT.SNDBSA>} */ private searchField(fieldName?: string, value?: any): Promise<BTT.SNDBSA> { if (fieldName && (value !== undefined)) { return this.indices.has(fieldName) ? this.searchIndices(fieldName, value) : this.searchCollection(fieldName, value); } else { return this.searchCollection(); } } /** * Search indices by field * Example 1: dbName.searchIndices("fieldName", "1234"); * will return the value id of that key as an array of one element. * Example 2: dbName.searchIndices("fieldName", { $gte: 1, $lte 10, $ne: 3 } * will return an array of ids from the given range. * Returns array of IDs * @param fieldName - field to search * @param value - value to search by * @returns {Promise<BTT.SNDBSA>} */ private searchIndices(fieldName: string, value: IRange): Promise<BTT.SNDBSA> { return new Promise<BTT.SNDBSA>((resolve, reject) => { const index: Index | undefined = this.indices.get(fieldName); if (!index) { return resolve(undefined); } if (typeof value === "object") { resolve(index.searchRange(value)); } else { resolve(index.search(value)); } }); } /** * Search collection by field, essentially a collection scan * Returns array of IDs * @param fieldName - field to search * @param value - value to search by * @returns {Promise<T>} */ private searchCollection(fieldName?: string, value?: IRange): Promise<string[]> { return new Promise((resolve, reject): any => { const ids: string[] = []; if (fieldName && (value !== undefined)) { const queryObj: any = {}; let lt: any; let lte: any; let gt: any; let gte: any; let ne: any; if (value !== null && Object.prototype.toString.call(value) === "[object Object]") { lt = (value.hasOwnProperty("$lt") && value.$lt !== undefined) ? value.$lt : null; lte = (value.hasOwnProperty("$lte") && value.$lte !== undefined) ? value.$lte : null; gt = (value.hasOwnProperty("$gt") && value.$gt !== undefined) ? value.$gt : null; gte = (value.hasOwnProperty("$gte") && value.$gte !== undefined) ? value.$gte : null; ne = value.hasOwnProperty("$ne") ? value.$ne : null; } else { lt = null; lte = null; gt = null; gte = null; ne = null; } const queryArray = [{name: "lt", value: lt}, {name: "lte", value: lte}, {name: "gt", value: gt}, {name: "gte", value: gte}, {name: "ne", value: ne}]; queryArray.forEach((q) => { if (q.value !== null) { queryObj[q.name] = {value: q.value, flag: false}; } }); const allTrue = (obj: any) => { for (const o in obj) { if (obj.hasOwnProperty(o)) { if (!obj[o].flag) { return false; } } } return true; }; this.storage.iterate((v, k) => { const field: any = getObjValue(v, fieldName); if (field !== undefined) { if (lt === null && lte === null && gt === null && gte === null && ne === null && (k === value || field === value)) { ids.push(k); } else { let flag; if (Object.prototype.toString.call(value) === "[object Object]") { for (const item in queryObj) { if (queryObj.hasOwnProperty(item)) { switch (item) { case "gt": queryObj[item].flag = ((field > gt) && (gt !== null)); break; case "gte": queryObj[item].flag = ((field >= gte) && (gte !== null)); break; case "lt": queryObj[item].flag = ((field < lt) && (lt !== null)); break; case "lte": queryObj[item].flag = ((field <= lte) && (lte !== null)); break; case "ne": queryObj[item].flag = ((field !== ne) && (ne !== null)); break; } } } flag = allTrue(queryObj); } else { flag = (((field < lt) && (lt !== null)) || ((field <= lte) && (lte !== null)) || ((field > gt) && (gt !== null)) || ((field >= gte) && (gte !== null)) || ((field !== ne) && (ne !== null)) || (field === value)); } if (flag) { ids.push(k); } } } }) .then(() => { resolve(ids); }) .catch((e) => { reject(e); }); } else { // here return keys from storage driver this.storage.keys() .then(resolve) .catch(reject); } }); } /** * Actual method to update the documents and associated indices * @param docs - an array of documents to be updated * @param promises - reference to promise array to be resolved later * @param indexPromises - reference to promise array to be resolved later * @param operation - operation query from update method * @param operators - array of operators passed by reference from the update method * @param operationKeys - Each key from the query. could be less than operators array length * @param reject - passed reference to reject from update method. */ private updateDocsIndices(docs: any[], promises: Array<Promise<any[]>>, indexPromises: Array<Promise<null>>, operation: any, operators: string[], operationKeys: string[], reject: any): any { docs.forEach((doc: any) => { // each doc let mathed: number; let preMath: number; // update indices this.indices.forEach((index, field) => { // each index in datastore operationKeys.forEach((k) => { // each op key sent by user if (operationKeys.indexOf(k) !== -1) { const setKeys = Object.keys(operation[k]); switch (k) { case "$set": setKeys.forEach((sk) => { // each $set obj key if (field === sk) { // update the index value with the new // value if the index fieldname = // the $set obj key. indexPromises.push(index.updateKey(getObjValue(doc, field), operation[k][sk])); } }); break; case "$mul": setKeys.forEach((mk) => { if (field === mk) { if (mathed) { preMath = mathed; mathed = mathed * operation[k][mk]; } else { mathed = getObjValue(doc, field) * operation[k][mk]; } const indexed = preMath ? preMath : getObjValue(doc, field); indexPromises.push(index.updateKey(indexed, mathed)); } }); break; case "$inc": setKeys.forEach((ik) => { if (field === ik) { if (mathed) { preMath = mathed; mathed = mathed + operation[k][ik]; } else { mathed = getObjValue(doc, field) + operation[k][ik]; } const indexed = preMath ? preMath : getObjValue(doc, field); indexPromises.push(index.updateKey(indexed, mathed)); } }); break; case "$unset": setKeys.forEach((ik) => { if (field === ik) { // To unset a field that is indexed // remove the document. The index remove // method has this ref and knows the value indexPromises.push(index.remove(doc)); } }); break; case "$rename": setKeys.forEach((rn) => { if (field === rn) { // save current index value const indexValue = this.indices.get(field); // delete current index this.removeIndex(field) .then(() => { // create new index with old value new name if (indexValue) { this.indices.set(operation[k][rn], indexValue); } else { return reject(new Error(`Cannot rename index of ${field} that does not exist`)); } }) .catch((e) => reject(e)); } }); break; } } }); }); // Update Docs operationKeys.forEach((k) => { if (operators.indexOf(k) !== -1) { switch (k) { case "$set": promises.push($set(doc, operation[k])); break; case "$mul": promises.push($mul(doc, operation[k])); break; case "$inc": promises.push($inc(doc, operation[k])); break; case "$unset": promises.push($unset(doc, operation[k])); break; case "$rename": promises.push($rename(doc, operation[k])); break; } } }); }); } /** * Return fill provided promise array with promises from the storage driver * @param promises * @param ids */ private createIdsArray(ids: string[]): Promise<any[]> { return new Promise((resolve, reject) => { return Promise.all(ids.map((id) => { return this.storage.getItem(id); })) .then((docs) => { docs = docs.filter((doc) => !isEmpty(doc)); resolve(docs); }) .catch(reject); }); } /** * Create Unique ID that contains timestamp * @returns {string} */ private createId(): string { return getUUID(); } }
the_stack
* Copyright 2015 Dev Shop Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // notice_end import * as esp from '../../src'; import {EventEnvelope} from '../../.dist/typings/router'; import {ObservationStage} from '../../src'; describe('Router', () => { let _router; beforeEach(() => { _router = new esp.Router(); }); describe('.getEventObservable()', () => { it('throws on subscribe if arguments incorrect', () => { expect(() => {_router.getEventObservable({}, 'foo').subscribe(() => {}); }).toThrow(new Error('The modelId argument should be a string')); expect(() => {_router.getEventObservable(undefined, 'foo').subscribe(() => {}); }).toThrow(); expect(() => {_router.getEventObservable('foo', undefined).subscribe(() => {}); }).toThrow(); }); it('throws on subscribe if unknown event stage passed', () => { expect(() => {_router.getEventObservable('foo', 'eventType', 'unknownStage').subscribe(() => {}); }).toThrow(new Error('The stage argument value of [unknownStage] is incorrect. It should be ObservationStage.preview, ObservationStage.normal, ObservationStage.committed or ObservationStage.all.')); expect(() => {_router.getEventObservable('foo', 'eventType', {}).subscribe(() => {}); }).toThrow(new Error('The stage argument should be a string')); }); it('dispatches events to processors by modelid', () => { let model1ProcessorReceived = false, model2ProcessorReceived = false; _router.addModel('modelId1', {}); _router.addModel('modelId2', {}); _router.getEventObservable('modelId1', 'Event1').subscribe(() => { model1ProcessorReceived = true; }); _router.getEventObservable('modelId2', 'Event1').subscribe(() => { model2ProcessorReceived = true; }); _router.publishEvent('modelId1', 'Event1', 'theEvent'); expect(model1ProcessorReceived).toBe(true); expect(model2ProcessorReceived).toBe(false); }); it('doesn\'t dispatch to disposed update ubscribers', () => { _router.addModel('modelId1', {}); let eventReeivedCount =0; let disposable = _router.getEventObservable('modelId1', 'Event1').subscribe(() => { eventReeivedCount++; }); _router.publishEvent('modelId1', 'Event1', 'theEvent'); expect(eventReeivedCount).toBe(1); disposable.dispose(); _router.publishEvent('modelId1', 'Event1', 'theEvent'); expect(eventReeivedCount).toBe(1); }); describe('observation stages', () => { let receivedAtPreview, receivedAtNormal, receivedAtCommitted, receivedAtFinal, eventContextActions; function publishEvent() { _router.publishEvent('modelId1', 'Event1', 'theEvent'); } function actOnEventContext(eventContext, stage) { if(eventContextActions.shouldCancel && eventContextActions.cancelStage === stage) { eventContext.cancel(); } if(eventContextActions.shouldCommit && eventContextActions.commitStage === stage) { eventContext.commit(); } } function runTestSet() { it('delivers events to preview observers', () => { publishEvent(); expect(receivedAtPreview).toBe(true); }); it('doesn\'t propagate events canceled at preview stage', () => { eventContextActions.shouldCancel = true; eventContextActions.cancelStage = esp.ObservationStage.preview; publishEvent(); expect(receivedAtPreview).toBe(true); expect(receivedAtNormal).toBe(false); }); it('delivers events to normal observers', () => { publishEvent(); expect(receivedAtNormal).toBe(true); }); it('doesn\'t propagate uncommitted events to the committed stage', () => { publishEvent(); expect(receivedAtCommitted).toBe(false); }); it('propagates committed events to the committed stage', () => { eventContextActions.shouldCommit = true; eventContextActions.commitStage = esp.ObservationStage.normal; publishEvent(); expect(receivedAtCommitted).toBe(true); }); it('delivers events to final observers when committed', () => { eventContextActions.shouldCommit = true; eventContextActions.commitStage = esp.ObservationStage.normal; publishEvent(); expect(receivedAtFinal).toBe(true); }); it('delivers events to final observers even when not committed', () => { eventContextActions.shouldCommit = false; publishEvent(); expect(receivedAtFinal).toBe(true); }); it('doesn\'t propagate canceled events to the final stage', () => { eventContextActions.shouldCancel = true; eventContextActions.cancelStage = esp.ObservationStage.preview; publishEvent(); expect(receivedAtFinal).toBe(false); }); it('throws if event committed at the preview stage', () => { eventContextActions.shouldCommit = true; eventContextActions.commitStage = esp.ObservationStage.preview; expect(() => { publishEvent(); }).toThrow(); }); it('throws if event canceled at the normal stage', () => { eventContextActions.shouldCancel = true; eventContextActions.cancelStage = esp.ObservationStage.normal; expect(() => { publishEvent(); }).toThrow(); }); it('throws if event canceled at the committed stage', () => { eventContextActions.shouldCommit = true; eventContextActions.commitStage = esp.ObservationStage.normal; eventContextActions.shouldCancel = true; eventContextActions.cancelStage = esp.ObservationStage.committed; expect(() => { publishEvent(); }).toThrow(); }); it('throws if event canceled at the final stage', () => { eventContextActions.shouldCancel = true; eventContextActions.cancelStage = esp.ObservationStage.final; expect(() => { publishEvent(); }).toThrow(); }); it('throws if event committed at the committed stage', () => { eventContextActions.shouldCommit = true; eventContextActions.commitStage = esp.ObservationStage.committed; _router.getEventObservable('modelId1', 'Event1') .subscribe((envelope) => { envelope.context.commit(); }); expect(() => { publishEvent(); }).toThrow(); }); it('throws if event committed at the final stage', () => { eventContextActions.shouldCommit = true; eventContextActions.commitStage = esp.ObservationStage.final; expect(() => { publishEvent(); }).toThrow(); }); } beforeEach(() => { receivedAtPreview = false; receivedAtNormal = false; receivedAtCommitted = false; receivedAtFinal = false; eventContextActions = { shouldCommit: false, cancelStage: '', shouldCancel: false, commitStage: '' }; _router.addModel('modelId1', {}); }); describe('Separate observation stage dispatch', () => { beforeEach(() => { _router.getEventObservable('modelId1', 'Event1', esp.ObservationStage.preview) .subscribe(({event, context}) => { receivedAtPreview = true; actOnEventContext(context, esp.ObservationStage.preview); }); _router.getEventObservable('modelId1', 'Event1', esp.ObservationStage.normal) .subscribe(({event, context}) => { receivedAtNormal = true; actOnEventContext(context, esp.ObservationStage.normal); }); _router.getEventObservable('modelId1', 'Event1', esp.ObservationStage.committed) .subscribe(({event, context}) => { receivedAtCommitted = true; actOnEventContext(context, esp.ObservationStage.committed); }); _router.getEventObservable('modelId1', 'Event1', esp.ObservationStage.final) .subscribe(({event, context}) => { receivedAtFinal = true; actOnEventContext(context, esp.ObservationStage.final); }); }); runTestSet(); }); describe('Single (all) observation stage dispatch', () => { beforeEach(() => { _router.getEventObservable('modelId1', 'Event1', esp.ObservationStage.all) .subscribe((eventEnvelope: EventEnvelope<any, any>) => { if (ObservationStage.isPreview(eventEnvelope.observationStage)) { receivedAtPreview = true; } if (ObservationStage.isNormal(eventEnvelope.observationStage)) { receivedAtNormal = true; } if (ObservationStage.isCommitted(eventEnvelope.observationStage)) { receivedAtCommitted = true; } if (ObservationStage.isFinal(eventEnvelope.observationStage)) { receivedAtFinal = true; } actOnEventContext(eventEnvelope.context, eventEnvelope.observationStage); }); }); runTestSet(); }); }); }); });
the_stack
import RequestReplyManager from "../../../../main/js/joynr/dispatching/RequestReplyManager"; import * as OneWayRequest from "../../../../main/js/joynr/dispatching/types/OneWayRequest"; import * as Request from "../../../../main/js/joynr/dispatching/types/Request"; import * as Reply from "../../../../main/js/joynr/dispatching/types/Reply"; import TypeRegistrySingleton from "../../../../main/js/joynr/types/TypeRegistrySingleton"; import * as Typing from "../../../../main/js/joynr/util/Typing"; import * as UtilInternal from "../../../../main/js/joynr/util/UtilInternal"; import * as JSONSerializer from "../../../../main/js/joynr/util/JSONSerializer"; import MethodInvocationException from "../../../../main/js/joynr/exceptions/MethodInvocationException"; import Version from "../../../../main/js/generated/joynr/types/Version"; import DiscoveryEntryWithMetaInfo from "../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo"; import ProviderQos from "../../../../main/js/generated/joynr/types/ProviderQos"; import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos"; import testUtil from "../../../js/testUtil"; describe("libjoynr-js.joynr.dispatching.RequestReplyManager", () => { let dispatcherSpy: any; let requestReplyManager: RequestReplyManager; let typeRegistry: any; const ttlMs = 50; const requestReplyId = "requestReplyId"; const testResponse = ["testResponse"]; const reply = Reply.create({ requestReplyId, response: testResponse }); const replySettings = {}; let fakeTime = Date.now(); async function increaseFakeTime(timeMs: number): Promise<void> { fakeTime += timeMs; jest.advanceTimersByTime(timeMs); await testUtil.multipleSetImmediate(); } const providerDiscoveryEntry = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 0, minorVersion: 23 }), domain: "testProviderDomain", interfaceName: "interfaceName", participantId: "providerParticipantId", qos: new ProviderQos(undefined as any), lastSeenDateMs: Date.now(), expiryDateMs: Date.now() + 60000, publicKeyId: "publicKeyId", isLocal: true }); class RadioStation { public name: string; public station: any; public source: any; public checkMembers: any; public _typeName = "test.RadioStation"; public static _typeName = "test.RadioStation"; public getMemberType(): void {} public constructor(name: string, station: any, source: any) { this.name = name; this.station = station; this.source = source; Object.defineProperty(this, "checkMembers", { configurable: false, writable: false, enumerable: false, value: jest.fn() }); } } class ComplexTypeWithComplexAndSimpleProperties { public radioStation: any; public myBoolean: any; public myString: any; public checkMembers: any; public _typeName = "test.ComplexTypeWithComplexAndSimpleProperties"; public static _typeName = "test.ComplexTypeWithComplexAndSimpleProperties"; public constructor(radioStation: any, myBoolean: any, myString: any) { this.radioStation = radioStation; this.myBoolean = myBoolean; this.myString = myString; Object.defineProperty(this, "checkMembers", { configurable: false, writable: false, enumerable: false, value: jest.fn() }); } public getMemberType(): void {} } /** * Called before each test. */ beforeEach(() => { jest.useFakeTimers(); jest.spyOn(Date, "now").mockImplementation(() => { return fakeTime; }); dispatcherSpy = { sendOneWayRequest: jest.fn(), sendRequest: jest.fn() }; typeRegistry = TypeRegistrySingleton.getInstance(); typeRegistry.addType(RadioStation); typeRegistry.addType(ComplexTypeWithComplexAndSimpleProperties); requestReplyManager = new RequestReplyManager(dispatcherSpy); }); afterEach(() => { requestReplyManager.shutdown(); jest.useRealTimers(); }); it("is instantiable", () => { expect(requestReplyManager).toBeDefined(); }); const tripleJ = new RadioStation("TripleJ", "107.7", "AUSTRALIA"); const fm4 = new RadioStation("FM4", "104.0", "AUSTRIA"); const complex = new ComplexTypeWithComplexAndSimpleProperties(tripleJ, true, "hello"); Object.setPrototypeOf(complex, Object); Object.setPrototypeOf(fm4, Object); Object.setPrototypeOf(tripleJ, Object); const testData = [ { paramDatatype: ["Boolean"], params: [true] }, { paramDatatype: ["Integer"], params: [123456789] }, { paramDatatype: ["Double"], params: [-123.456789] }, { paramDatatype: ["String"], params: ["lalala"] }, { paramDatatype: ["Integer[]"], params: [[1, 2, 3, 4, 5]] }, { paramDatatype: ["joynr.vehicle.radiotypes.RadioStation[]"], params: [[fm4, tripleJ]] }, { paramDatatype: ["joynr.vehicle.radiotypes.RadioStation"], params: [tripleJ] }, { paramDatatype: ["joynr.vehicle.radiotypes.RadioStation", "String"], params: [tripleJ, "testParam"] }, { paramDatatype: ["vehicle.ComplexTypeWithComplexAndSimpleProperties"], params: [complex] } ]; async function testHandleRequestForGetterSetterMethod(attributeName: string, params: any[]) { const providerParticipantId = "providerParticipantId"; const provider = { [attributeName]: { get: jest.fn().mockReturnValue([]), set: jest.fn().mockReturnValue([]) } }; let request = Request.create({ methodName: `get${UtilInternal.firstUpper(attributeName)}`, paramDatatypes: [], params: [] }); requestReplyManager.addRequestCaller(providerParticipantId, provider); await requestReplyManager.handleRequest(providerParticipantId, request, jest.fn, {}); await testUtil.multipleSetImmediate(); request = Request.create({ methodName: `set${UtilInternal.firstUpper(attributeName)}`, paramDatatypes: [], // untype objects through serialization and deserialization params: JSON.parse(JSONSerializer.stringify(params)) }); requestReplyManager.addRequestCaller(providerParticipantId, provider); await requestReplyManager.handleRequest(providerParticipantId, request, jest.fn, {}); await testUtil.multipleSetImmediate(); expect(provider[attributeName].get).toHaveBeenCalledWith(); expect(provider[attributeName].set).toHaveBeenCalledWith(params[0]); const result = provider[attributeName].set.mock.calls[0][0]; expect(result).toEqual(params[0]); } async function testHandleRequestWithExpectedType(paramDatatypes: any, params: any[]) { const providerParticipantId = "providerParticipantId"; const provider = { testFunction: { callOperation: jest.fn() } }; provider.testFunction.callOperation.mockReturnValue([]); const request = Request.create({ methodName: "testFunction", paramDatatypes, // untype objects through serialization and deserialization params: JSON.parse(JSONSerializer.stringify(params)) }); requestReplyManager.addRequestCaller(providerParticipantId, provider); requestReplyManager.handleRequest(providerParticipantId, request, jest.fn, {}); await testUtil.multipleSetImmediate(); expect(provider.testFunction.callOperation).toHaveBeenCalled(); expect(provider.testFunction.callOperation).toHaveBeenCalledWith(params, paramDatatypes); const result = provider.testFunction.callOperation.mock.calls[0][0]; expect(result).toEqual(params); expect(Typing.getObjectType(result)).toEqual(Typing.getObjectType(params)); } it("calls registered requestCaller for attribute", async () => { await testHandleRequestForGetterSetterMethod("attributeA", ["attributeA"]); await testHandleRequestForGetterSetterMethod("AttributeWithStartingCapitalLetter", [ "AttributeWithStartingCapitalLetter" ]); }); it("calls registered requestCaller with correctly typed object", async () => { for (let i = 0; i < testData.length; ++i) { const test = testData[i]; await testHandleRequestWithExpectedType(test.paramDatatype, test.params); } }); it("calls registered replyCaller when a reply arrives", async () => { const replyCallerSpy = { callback: jest.fn(), callbackSettings: {} }; requestReplyManager.addReplyCaller(requestReplyId, replyCallerSpy, ttlMs); requestReplyManager.handleReply(reply); await testUtil.multipleSetImmediate(); expect(replyCallerSpy.callback).toHaveBeenCalled(); expect(replyCallerSpy.callback).toHaveBeenCalledWith(undefined, { response: testResponse, settings: replyCallerSpy.callbackSettings }); }); it("calls registered replyCaller fail if no reply arrives in time", async () => { const replyCallerSpy = { callback: jest.fn(), callbackSettings: {} }; requestReplyManager.addReplyCaller("requestReplyId", replyCallerSpy, ttlMs); const toleranceMs = 1500; // at least 1000 since that's the cleanup interval await increaseFakeTime(toleranceMs + ttlMs); expect(replyCallerSpy.callback).toHaveBeenCalledWith(expect.any(Error)); }); async function testHandleReplyWithExpectedType(params: any[]): Promise<void> { const replyCallerSpy = { callback: jest.fn(), callbackSettings: {} }; const reply = Reply.create({ requestReplyId, // untype object by serializing and deserializing it response: JSON.parse(JSONSerializer.stringify(params)) }); requestReplyManager.addReplyCaller("requestReplyId", replyCallerSpy, ttlMs); requestReplyManager.handleReply(reply); await testUtil.multipleSetImmediate(); expect(replyCallerSpy.callback).toHaveBeenCalled(); const result = replyCallerSpy.callback.mock.calls[0][1]; for (let i = 0; i < params.length; i++) { expect(result.response[i]).toEqual(params[i]); } } it("calls registered replyCaller with correctly typed object", async () => { for (let i = 0; i < testData.length; ++i) { const test = testData[i]; await testHandleReplyWithExpectedType(test.params); } }); function callRequestReplyManagerSync( methodName: string, testParam: any, testParamDatatype: any, useInvalidProviderParticipantId: any, callbackContext: any ) { let providerParticipantId = "providerParticipantId"; class TestProvider { public static MAJOR_VERSION = 47; public static MINOR_VERSION = 11; public attributeName = { get: jest.fn(), set: jest.fn() }; public operationName = { callOperation: jest.fn() }; public getOperationStartingWithGet = { callOperation: jest.fn() }; public getOperationHasPriority = { callOperation: jest.fn() }; public operationHasPriority = { get: jest.fn(), set: jest.fn() }; } const provider = new TestProvider(); provider.attributeName.get.mockReturnValue([testParam]); provider.attributeName.set.mockReturnValue([]); provider.operationName.callOperation.mockReturnValue([testParam]); provider.getOperationStartingWithGet.callOperation.mockReturnValue([testParam]); provider.getOperationHasPriority.callOperation.mockReturnValue([testParam]); const callbackDispatcher = jest.fn(); const request = Request.create({ methodName, paramDatatypes: [testParamDatatype], params: [testParam] }); requestReplyManager.addRequestCaller(providerParticipantId, provider); if (useInvalidProviderParticipantId) { providerParticipantId = "nonExistentProviderId"; } requestReplyManager.handleRequest(providerParticipantId, request, callbackDispatcher, callbackContext); return { provider, callbackDispatcher, request }; } async function callRequestReplyManager( methodName: string, testParam: any, testParamDatatype: any, useInvalidProviderParticipantId?: any, callbackContext?: any ) { const test = callRequestReplyManagerSync( methodName, testParam, testParamDatatype, useInvalidProviderParticipantId, callbackContext ); await testUtil.multipleSetImmediate(); return test; } const testParam = "myTestParameter"; const testParamDatatype = "String"; it("calls attribute getter correctly", async () => { const test = await callRequestReplyManager( "getAttributeName", testParam, testParamDatatype, undefined, replySettings ); expect(test.provider.attributeName.get).toHaveBeenCalled(); expect(test.provider.attributeName.get).toHaveBeenCalledWith(); expect(test.provider.attributeName.set).not.toHaveBeenCalled(); expect(test.provider.operationName.callOperation).not.toHaveBeenCalled(); expect(test.provider.getOperationStartingWithGet.callOperation).not.toHaveBeenCalled(); expect(test.provider.operationHasPriority.set).not.toHaveBeenCalled(); expect(test.provider.operationHasPriority.get).not.toHaveBeenCalled(); expect(test.provider.getOperationHasPriority.callOperation).not.toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalledWith( replySettings, Reply.create({ response: [testParam], requestReplyId: test.request.requestReplyId }) ); }); it("calls attribute setter correctly", async () => { const test = await callRequestReplyManager( "setAttributeName", testParam, testParamDatatype, undefined, replySettings ); expect(test.provider.attributeName.get).not.toHaveBeenCalled(); expect(test.provider.attributeName.set).toHaveBeenCalled(); expect(test.provider.attributeName.set).toHaveBeenCalledWith(testParam); expect(test.provider.operationName.callOperation).not.toHaveBeenCalled(); expect(test.provider.getOperationStartingWithGet.callOperation).not.toHaveBeenCalled(); expect(test.provider.operationHasPriority.set).not.toHaveBeenCalled(); expect(test.provider.operationHasPriority.get).not.toHaveBeenCalled(); expect(test.provider.getOperationHasPriority.callOperation).not.toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalledWith( replySettings, Reply.create({ response: [], requestReplyId: test.request.requestReplyId }) ); }); it("calls operation function correctly", async () => { const test = await callRequestReplyManager( "operationName", testParam, testParamDatatype, undefined, replySettings ); expect(test.provider.attributeName.set).not.toHaveBeenCalled(); expect(test.provider.attributeName.get).not.toHaveBeenCalled(); expect(test.provider.operationName.callOperation).toHaveBeenCalled(); expect(test.provider.operationName.callOperation).toHaveBeenCalledWith([testParam], [testParamDatatype]); expect(test.provider.getOperationStartingWithGet.callOperation).not.toHaveBeenCalled(); expect(test.provider.operationHasPriority.set).not.toHaveBeenCalled(); expect(test.provider.operationHasPriority.get).not.toHaveBeenCalled(); expect(test.provider.getOperationHasPriority.callOperation).not.toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalledWith( replySettings, Reply.create({ response: [testParam], requestReplyId: test.request.requestReplyId }) ); }); it("calls operation function for one-way request correctly", async () => { const providerParticipantId = "oneWayProviderParticipantId"; const provider = { fireAndForgetMethod: { callOperation: jest.fn() } }; const oneWayRequest = OneWayRequest.create({ methodName: "fireAndForgetMethod", paramDatatypes: [testParamDatatype], params: [testParam] }); requestReplyManager.addRequestCaller(providerParticipantId, provider); requestReplyManager.handleOneWayRequest(providerParticipantId, oneWayRequest); await testUtil.multipleSetImmediate(); expect(provider.fireAndForgetMethod.callOperation).toHaveBeenCalled(); expect(provider.fireAndForgetMethod.callOperation).toHaveBeenCalledWith([testParam], [testParamDatatype]); }); it('calls operation "getOperationStartingWithGet" when no attribute "operationStartingWithGet" exists', async () => { const test = await callRequestReplyManager("getOperationStartingWithGet", testParam, testParamDatatype); expect(test.provider.getOperationStartingWithGet.callOperation).toHaveBeenCalled(); expect(test.provider.getOperationStartingWithGet.callOperation).toHaveBeenCalledWith( [testParam], [testParamDatatype] ); }); it('calls operation "getOperationHasPriority" when attribute "operationHasPriority" exists', async () => { const test = await callRequestReplyManager("getOperationHasPriority", testParam, testParamDatatype); expect(test.provider.operationHasPriority.set).not.toHaveBeenCalled(); expect(test.provider.operationHasPriority.get).not.toHaveBeenCalled(); expect(test.provider.getOperationHasPriority.callOperation).toHaveBeenCalled(); expect(test.provider.getOperationHasPriority.callOperation).toHaveBeenCalledWith( [testParam], [testParamDatatype] ); }); it("delivers exception upon non-existent provider", async () => { const test = await callRequestReplyManager("testFunction", testParam, testParamDatatype, true, replySettings); expect(test.callbackDispatcher).toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalledWith( replySettings, Reply.create({ error: new MethodInvocationException({ detailMessage: `error handling request: {"methodName":"testFunction","paramDatatypes":["String"],"params":["myTestParameter"],"requestReplyId":"${ test.request.requestReplyId }","_typeName":"joynr.Request"} for providerParticipantId nonExistentProviderId` }), // {"methodName":"testFunction","paramDatatypes":["String"],"params":["myTestParameter"],"requestReplyId":"FVeNNFkkEDgfHMrslmHU__18","_typeName":"joynr.Request"} requestReplyId: test.request.requestReplyId }) ); }); it("delivers exception when calling not existing operation", async () => { const test = await callRequestReplyManager( "notExistentOperationOrAttribute", testParam, testParamDatatype, undefined, replySettings ); expect(test.callbackDispatcher).toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalledWith( replySettings, Reply.create({ error: new MethodInvocationException({ detailMessage: 'Could not find an operation "notExistentOperationOrAttribute" in the provider', providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }), requestReplyId: test.request.requestReplyId }) ); }); it("delivers exception when calling getter for not existing attribute", async () => { const test = await callRequestReplyManager( "getNotExistentOperationOrAttribute", testParam, testParamDatatype, undefined, replySettings ); expect(test.callbackDispatcher).toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalledWith( replySettings, Reply.create({ error: new MethodInvocationException({ detailMessage: 'Could not find an operation "getNotExistentOperationOrAttribute" or an attribute "NotExistentOperationOrAttribute" in the provider', providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }), requestReplyId: test.request.requestReplyId }) ); }); it("delivers exception when calling setter for not existing attribute", async () => { const test = await callRequestReplyManager( "setNotExistentOperationOrAttribute", testParam, testParamDatatype, undefined, replySettings ); expect(test.callbackDispatcher).toHaveBeenCalled(); expect(test.callbackDispatcher).toHaveBeenCalledWith( replySettings, Reply.create({ error: new MethodInvocationException({ detailMessage: 'Could not find an operation "setNotExistentOperationOrAttribute" or an attribute "NotExistentOperationOrAttribute" in the provider', providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }) }), requestReplyId: test.request.requestReplyId }) ); }); it("throws exception when called while shut down", async () => { requestReplyManager.shutdown(); expect(() => { requestReplyManager.removeRequestCaller("providerParticipantId"); }).toThrow(); const replySettings = {}; await requestReplyManager.handleRequest( "providerParticipantId", { requestReplyId } as any, (settings: any, reply: Reply.Reply) => { expect(settings).toBe(replySettings); expect(reply._typeName).toEqual("joynr.Reply"); expect(reply.error).toBeInstanceOf(MethodInvocationException); }, replySettings ); expect(() => { const replyCallerSpy = { resolve: jest.fn(), reject: jest.fn() }; requestReplyManager.addReplyCaller(requestReplyId, replyCallerSpy as any, undefined as any); }).toThrow(); expect(() => { requestReplyManager.addRequestCaller("providerParticipantId", {}); }).toThrow(); expect(() => { requestReplyManager.sendOneWayRequest({} as any); }).toThrow(); await testUtil.reversePromise(requestReplyManager.sendRequest({} as any, {})); expect(dispatcherSpy.sendRequest).not.toHaveBeenCalled(); }); it("rejects reply callers when shut down", () => { const replyCallerSpy = { callback: jest.fn() }; requestReplyManager.addReplyCaller(requestReplyId, replyCallerSpy as any, ttlMs); requestReplyManager.shutdown(); expect(replyCallerSpy.callback).toHaveBeenCalledWith(expect.any(Error)); }); it("sendOneWayRequest calls dispatcher with correct arguments", () => { const parameters = { from: "fromParticipantId", toDiscoveryEntry: providerDiscoveryEntry, messagingQos: new MessagingQos({ ttl: 1024 }), request: OneWayRequest.create({ methodName: "testMethodName" }) }; const expectedArguments: any = UtilInternal.extendDeep({}, parameters); expectedArguments.messagingQos = new MessagingQos(parameters.messagingQos); expectedArguments.toDiscoveryEntry = new DiscoveryEntryWithMetaInfo(parameters.toDiscoveryEntry); expectedArguments.request = OneWayRequest.create(parameters.request); dispatcherSpy.sendOneWayRequest.mockReturnValue(Promise.resolve()); requestReplyManager.sendOneWayRequest(parameters); expect(dispatcherSpy.sendOneWayRequest).toHaveBeenCalledWith(expectedArguments); }); });
the_stack
import { expect } from 'chai'; import { asyncFilter, asyncFind, asyncForEach, asyncMap, } from './async'; describe('async utilities', () => { describe('asyncFind', () => { it('handles empty inputs', async () => { const visitedItems: number[] = []; const finderFn = async (item: any) => { await simulateAsyncOp(); visitedItems.push(item); return true; }; // Raw array. expect(await asyncFind([], finderFn)).to.be.null; expect(visitedItems).to.be.empty; // Array wrapped in promise. expect(await asyncFind(wrapInPromise([]), finderFn)).to.be.null; expect(visitedItems).to.be.empty; }); it('finds it', async () => { let visitedItems: string[]; let visitedIndices: number[]; const finderFn = async (item: string, index: number) => { await simulateAsyncOp(); visitedItems.push(item); visitedIndices.push(index); return item.startsWith('g'); }; const input = ['alpha', 'beta', 'gamma', 'delta']; // Raw array. visitedItems = []; visitedIndices = []; expect(await asyncFind(input, finderFn)).to.equal('gamma'); expect(visitedItems).to.deep.equal(['alpha', 'beta', 'gamma']); expect(visitedIndices).to.deep.equal([0, 1, 2]); // Array wrapped in promise. visitedItems = []; visitedIndices = []; expect(await asyncFind(wrapInPromise(input), finderFn)).to.equal('gamma'); expect(visitedItems).to.deep.equal(['alpha', 'beta', 'gamma']); expect(visitedIndices).to.deep.equal([0, 1, 2]); }); it('does not find it', async () => { let visitedItems: string[]; let visitedIndices: number[]; const finderFn = async (item: string, index: number) => { await simulateAsyncOp(); visitedItems.push(item); visitedIndices.push(index); return false; // Never finds it. }; const input = ['alpha', 'beta', 'gamma', 'delta']; // Raw array. visitedItems = []; visitedIndices = []; expect(await asyncFind(input, finderFn)).to.be.null; expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1, 2, 3]); // Array wrapped in promise. visitedItems = []; visitedIndices = []; expect(await asyncFind(wrapInPromise(input), finderFn)).to.be.null; expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1, 2, 3]); }); }); describe('asyncFilter', () => { it('handles empty inputs', async () => { const visitedIndices: number[] = []; const filterFn = async (item: any, index: number) => { await simulateAsyncOp(); visitedIndices.push(index); return true; }; // Raw array. expect(await asyncFilter([], filterFn)).to.be.empty; expect(visitedIndices).to.be.empty; // Array wrapped in promise. expect(await asyncFilter(wrapInPromise([]), filterFn)).to.be.empty; expect(visitedIndices).to.be.empty; }); it('filters the input', async () => { let visitedItems: string[]; let visitedIndices: number[]; const filterFn = async (item: string, index: number) => { await simulateAsyncOp(); visitedItems.push(item); visitedIndices.push(index); return item.startsWith('a') || item.startsWith('g'); }; const input = ['alpha', 'beta', 'gamma', 'delta']; // Raw array. visitedItems = []; visitedIndices = []; expect(await asyncFilter(input, filterFn)).to.deep.equal(['alpha', 'gamma']); expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1, 2, 3]); // Array wrapped in promise. visitedItems = []; visitedIndices = []; expect(await asyncFilter(wrapInPromise(input), filterFn)).to.deep.equal(['alpha', 'gamma']); expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1, 2, 3]); }); }); describe('asyncMap', () => { it('maps empty inputs', async () => { const visitedIndices: number[] = []; const mapperFn = async (item: any, index: number) => { await simulateAsyncOp(); visitedIndices.push(index); return 'hello'; }; // Raw array. expect(await asyncMap([], mapperFn)).to.be.empty; expect(visitedIndices).to.be.empty; // Array wrapped in promise. expect(await asyncMap(wrapInPromise([]), mapperFn)).to.be.empty; expect(visitedIndices).to.be.empty; }); it('maps non-empty inputs', async () => { let visitedItems: string[]; let visitedIndices: number[]; const mapperFn = async (item: string, index: number) => { await simulateAsyncOp(); visitedItems.push(item); visitedIndices.push(index); return item.toUpperCase(); }; const input = ['hello', 'world']; // Raw array. visitedItems = []; visitedIndices = []; expect(await asyncMap(input, mapperFn)).to.deep.equal(['HELLO', 'WORLD']); expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1]); // Array wrapped in promise. visitedItems = []; visitedIndices = []; expect(await asyncMap(wrapInPromise(input), mapperFn)).to.deep.equal(['HELLO', 'WORLD']); expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1]); }); }); describe('asyncForEach', () => { it('does not iterate on empty inputs', async () => { const visitedIndices: number[] = []; const callbackFn = async (item: string, index: number) => { await simulateAsyncOp(); visitedIndices.push(index); }; // Raw array. await asyncForEach([], callbackFn); expect(visitedIndices).to.be.empty; // Array wrapped in promise. await asyncForEach(wrapInPromise([]), callbackFn); expect(visitedIndices).to.be.empty; }); it('iterates on non-empty inputs', async () => { let visitedItems: string[]; let visitedIndices: number[]; const callbackFn = async (item: string, index: number) => { await simulateAsyncOp(); visitedItems.push(item); visitedIndices.push(index); }; const input = ['alpha', 'beta', 'gamma']; // Raw array. visitedItems = []; visitedIndices = []; await asyncForEach(input, callbackFn); expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1, 2]); // Array wrapped in promise. visitedItems = []; visitedIndices = []; await asyncForEach(wrapInPromise(input), callbackFn); expect(visitedItems).to.deep.equal(input); expect(visitedIndices).to.deep.equal([0, 1, 2]); }); }); }); async function simulateAsyncOp(): Promise<void> { // Do nothing. } function wrapInPromise<T>(value: T): Promise<T> { return new Promise((resolve) => resolve(value)); } describe('examples with and without async.ts', () => { // These examples illustrate situations involving multiple async operations where async.ts can // make the code simpler. const stateCapitalsMap = new Map<string, string>([ ['Colorado', 'Denver'], ['Georgia', 'Atlanta'], ['Massachussets', 'Boston'], ['North Carolina', 'Raleigh'], ['Texas', 'Austin'], ]); const cityPopulationsMap = new Map<string, number>([ ['Atlanta', 498_715], ['Austin', 950_807], ['Boston', 684_000], ['Denver', 705_576], ['Raleigh', 464_485], ]); // Simulates an RPC operation. const getStatesRPC = (): Promise<string[]> => wrapInPromise(Array.from(stateCapitalsMap.keys())); // Simulates an RPC operation. const getStateCapitalRPC = (state: string): Promise<string> => ( wrapInPromise(stateCapitalsMap.get(state)!) ); // Simulates an RPC operation. const getCityPopulationRPC = (city: string): Promise<number> => ( wrapInPromise(cityPopulationsMap.get(city)!) ); describe('without async.ts', () => { it('fetches state capitals', async () => { const states = await getStatesRPC(); const stateCapitalPromises = states.map(getStateCapitalRPC); const stateCapitals = await Promise.all(stateCapitalPromises); expect(stateCapitals).to.have.length(5); expect(stateCapitals).to.have.members(['Atlanta', 'Austin', 'Boston', 'Denver', 'Raleigh']); }); it('fetches state capitals with population > 500k', async () => { const states = await getStatesRPC(); const stateCapitals = await Promise.all(states.map(getStateCapitalRPC)); // We can't use Array.prototype.filter because async predicates return promises, which are // truthy, and thus nothing gets filtered out. const failedAttempt = stateCapitals.filter( async (city) => (await getCityPopulationRPC(city)) > 500_000, ); expect(failedAttempt).to.have.length(5); const populousStateCapitals: string[] = []; await Promise.all(stateCapitals.map(async (city) => { const population = await getCityPopulationRPC(city); if (population > 500_000) populousStateCapitals.push(city); })); expect(populousStateCapitals).to.have.length(3); expect(populousStateCapitals).to.have.members(['Austin', 'Boston', 'Denver']); }); }); describe('with async.ts', () => { it('fetches state capitals', async () => { const stateCapitals = await asyncMap(getStatesRPC(), getStateCapitalRPC); expect(stateCapitals).to.have.length(5); expect(stateCapitals).to.have.members(['Atlanta', 'Austin', 'Boston', 'Denver', 'Raleigh']); }); it('fetches state capitals with population > 500k', async () => { const stateCapitals = asyncMap(getStatesRPC(), getStateCapitalRPC); const populousStateCapitals = await asyncFilter( stateCapitals, async (city) => (await getCityPopulationRPC(city)) > 500_000, ); expect(populousStateCapitals).to.have.length(3); expect(populousStateCapitals).to.have.members(['Austin', 'Boston', 'Denver']); }); }); });
the_stack
import assert = require("assert"); import { AutoActiveLearner } from "../../../../../src/model/supervised/classifier/auto_active_learning/AutoActiveLearner"; import { AppSoftmaxRegressionSparse } from "../../../../../src/model/supervised/classifier/neural_network/learner/AppSoftmaxRegressionSparse"; import { SoftmaxRegressionSparse } from "../../../../../src/model/supervised/classifier/neural_network/learner/SoftmaxRegressionSparse"; import { ColumnarContentEmail } from "../../../../data/ColumnarDataWithSubwordFeaturizer.test"; // import { LuContentEmail } from "../../../../data/LuDataWithSubwordFeaturizer.test"; import { ColumnarDataWithSubwordFeaturizer } from "../../../../../src/data/ColumnarDataWithSubwordFeaturizer"; // import { LuDataWithSubwordFeaturizer } from "../../../../../src/data/LuDataWithSubwordFeaturizer"; import { NgramSubwordFeaturizer } from "../../../../../src/model/language_understanding/featurizer/NgramSubwordFeaturizer"; import { Utility } from "../../../../../src/utility/Utility"; import { UnitTestHelper } from "../../../../utility/Utility.test"; export function exampleFunctionCreateAutoActiveLearner(): AutoActiveLearner { const doAutoActiveLearning: boolean = AutoActiveLearner.defaultDoAutoActiveLearning; const aalLimitInitialNumberOfInstancesPerCategory: number = AutoActiveLearner.defaultAalLimitInitialNumberOfInstancesPerCategory; const aalNumberOfInstancesPerIteration: number = AutoActiveLearner.defaultAalNumberOfInstancesPerIteration; const aalInstanceSelectionThreshold: number = AutoActiveLearner.defaultAalInstanceSelectionThreshold; const learnerParameterEpochs: number = AppSoftmaxRegressionSparse.defaultEpochs; const learnerParameterMiniBatchSize: number = AppSoftmaxRegressionSparse.defaultMiniBatchSize; const learnerParameterL1Regularization: number = AppSoftmaxRegressionSparse.defaultL1Regularization; const learnerParameterL2Regularization: number = AppSoftmaxRegressionSparse.defaultL2Regularization; const learnerParameterLossEarlyStopRatio: number = AppSoftmaxRegressionSparse.defaultLossEarlyStopRatio; const learnerParameterLearningRate: number = AppSoftmaxRegressionSparse.defaultLearningRate; const learnerParameterToCalculateOverallLossAfterEpoch: boolean = true; const autoActiveLearnerObject: AutoActiveLearner = new AutoActiveLearner( doAutoActiveLearning, aalLimitInitialNumberOfInstancesPerCategory, aalNumberOfInstancesPerIteration, aalInstanceSelectionThreshold, learnerParameterEpochs, learnerParameterMiniBatchSize, learnerParameterL1Regularization, learnerParameterL2Regularization, learnerParameterLossEarlyStopRatio, learnerParameterLearningRate, learnerParameterToCalculateOverallLossAfterEpoch); return autoActiveLearnerObject; } const autoActiveLearner: AutoActiveLearner = exampleFunctionCreateAutoActiveLearner(); describe("Test Suite - model/supervised/classifier/auto_active_learning/auto_active_learner/AutoActiveLearner", () => { it("Test.0000 constructor()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); exampleFunctionCreateAutoActiveLearner(); }); it("Test.0100 getAalLimitInitialNumberOfInstancesPerCategory()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const aalLimitInitialNumberOfInstancesPerCategory: number = autoActiveLearner.getAalLimitInitialNumberOfInstancesPerCategory(); Utility.debuggingLog( `aalLimitInitialNumberOfInstancesPerCategory=${aalLimitInitialNumberOfInstancesPerCategory}`); }); it("Test.0101 getAalNumberOfInstancesPerIteration()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const aalNumberOfInstancesPerIteration: number = autoActiveLearner.getAalNumberOfInstancesPerIteration(); Utility.debuggingLog( `aalNumberOfInstancesPerIteration=${aalNumberOfInstancesPerIteration}`); }); it("Test.0102 getAalInstanceSelectionThreshold()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const aalInstanceSelectionThreshold: number = autoActiveLearner.getAalInstanceSelectionThreshold(); Utility.debuggingLog( `aalInstanceSelectionThreshold=${aalInstanceSelectionThreshold}`); }); it("Test.0200 createLearner()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const learner: SoftmaxRegressionSparse = autoActiveLearner.createLearner( 10, 10); }); it("Test.0300 learn()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); // ----------------------------------------------------------------------- const columnarContent: string = ColumnarContentEmail; const labelColumnIndex: number = 0; const textColumnIndex: number = 2; const weightColumnIndex: number = 1; const linesToSkip: number = 1; const columnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer = ColumnarDataWithSubwordFeaturizer.createColumnarDataWithSubwordFeaturizer( columnarContent, new NgramSubwordFeaturizer(), labelColumnIndex, textColumnIndex, weightColumnIndex, linesToSkip, true); // ----------------------------------------------------------------------- const results = columnarDataWithSubwordFeaturizer.collectSmallUtteranceIndexSetCoveringAllIntentEntityLabels(); const smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels: Map<string, Set<number>> = results.smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels; const smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels: Map<string, Set<number>> = results.smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels; const smallUtteranceIndexSetCoveringAllIntentEntityLabels: Set<number> = results.smallUtteranceIndexSetCoveringAllIntentEntityLabels; const remainingUtteranceIndexSet: Set<number> = results.remainingUtteranceIndexSet; Utility.debuggingLog(`smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels=` + `${Utility.stringMapSetToJson(smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels=` + `${Utility.stringMapSetToJson(smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`smallUtteranceIndexSetCoveringAllIntentEntityLabels=` + `${Utility.setToJsonSerialization(smallUtteranceIndexSetCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`remainingUtteranceIndexSet=` + `${Utility.setToJsonSerialization(remainingUtteranceIndexSet)}`); Utility.debuggingLog(`smallUtteranceIndexSetCoveringAllIntentEntityLabels.size=` + `${smallUtteranceIndexSetCoveringAllIntentEntityLabels.size}`); Utility.debuggingLog(`remainingUtteranceIndexSet.size=` + `${remainingUtteranceIndexSet.size}`); // ------------------------------------------------------------------- const doAutoActiveLearning: boolean = true; // ---- AutoActiveLearner.defaultDoAutoActiveLearning; let aalLimitInitialNumberOfInstancesPerCategory: number = AutoActiveLearner.defaultAalLimitInitialNumberOfInstancesPerCategory; // const aalNumberOfInstancesPerIteration: number = // AutoActiveLearner.defaultAalNumberOfInstancesPerIteration; // const aalInstanceSelectionThreshold: number = // AutoActiveLearner.defaultAalInstanceSelectionThreshold; if (!doAutoActiveLearning) { aalLimitInitialNumberOfInstancesPerCategory = -1; } const resultsInitialSampling = columnarDataWithSubwordFeaturizer.collectUtteranceIndexSetSeedingIntentTrainingSet( smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels, remainingUtteranceIndexSet, aalLimitInitialNumberOfInstancesPerCategory); const seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels: Map<string, Set<number>> = resultsInitialSampling.seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels; const candidateUtteranceIndexSetSampled: Set<number> = resultsInitialSampling.candidateUtteranceIndexSetSampled; const candidateUtteranceIndexSetRemaining: Set<number> = resultsInitialSampling.candidateUtteranceIndexSetRemaining; Utility.debuggingLog(`seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels=` + `${Utility.stringMapSetToJson(seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`candidateUtteranceIndexSetSampled=` + `${Utility.setToJsonSerialization(candidateUtteranceIndexSetSampled)}`); Utility.debuggingLog(`candidateUtteranceIndexSetRemaining=` + `${Utility.setToJsonSerialization(candidateUtteranceIndexSetRemaining)}`); Utility.debuggingLog(`candidateUtteranceIndexSetSampled.size=` + `${candidateUtteranceIndexSetSampled.size}`); Utility.debuggingLog(`candidateUtteranceIndexSetRemaining.size=` + `${candidateUtteranceIndexSetRemaining.size}`); // const countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels: number = // [...seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels].reduce( // (accumulation: number, entry: [string, Set<number>]) => accumulation + entry[1].size, 0); // Utility.debuggingLog(`countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels=` + // `${countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels}`); // ------------------------------------------------------------------- const seedingUtteranceIndexArray: number[] = [...seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels].reduce( (accumulation: number[], entry: [string, Set<number>]) => accumulation.concat(Array.from(entry[1])), []); Utility.debuggingLog(`seedingUtteranceIndexArray.length=` + `${seedingUtteranceIndexArray.length}`); // ------------------------------------------------------------------- const intentLabelIndexArray: number[] = columnarDataWithSubwordFeaturizer.getIntentLabelIndexArray(); const utteranceFeatureIndexArrays: number[][] = columnarDataWithSubwordFeaturizer.getUtteranceFeatureIndexArrays(); const learned: { "seedingInstanceIndexArray": number[], "learner": SoftmaxRegressionSparse, } = autoActiveLearner.learn( columnarDataWithSubwordFeaturizer.getFeaturizerLabels(), columnarDataWithSubwordFeaturizer.getFeaturizerLabelMap(), columnarDataWithSubwordFeaturizer.getFeaturizer().getNumberLabels(), columnarDataWithSubwordFeaturizer.getFeaturizer().getNumberFeatures(), intentLabelIndexArray, utteranceFeatureIndexArrays, seedingUtteranceIndexArray, Array.from(candidateUtteranceIndexSetRemaining)); // const aalSampledInstanceIndexArray: number[] = // learned.seedingInstanceIndexArray; // const learner: SoftmaxRegressionSparse = // learned.learner; // const newColumnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer = // tslint:disable-next-line: max-line-length // ColumnarDataWithSubwordFeaturizer.createColumnarDataWithSubwordFeaturizerFromFilteringExistingColumnarDataUtterances( // columnarDataWithSubwordFeaturizer, // labelColumnIndex, // textColumnIndex, // weightColumnIndex, // linesToSkip, // new Set<number>(aalSampledInstanceIndexArray)); }); });
the_stack
import { Option, None } from "@siteimprove/alfa-option"; import { Predicate } from "@siteimprove/alfa-predicate"; import { Slice } from "@siteimprove/alfa-slice"; import * as parser from "@siteimprove/alfa-parser"; import { Expression } from "../expression"; import { Token } from "./token"; import { Lexer } from "./lexer"; const { fromCharCode } = String; const { map, either, delimited, option, pair, left, right, take, zeroOrMore, } = parser.Parser; const { equals, property } = Predicate; /** * @public */ export namespace Parser { export function parse(input: string): Option<Expression> { return parseExpression(Slice.of(Lexer.lex(input))) .map(([, expression]) => expression) .ok(); } } // Hoist the expression parser to break the recursive initialisation between its // different subparsers. let parseExpression: parser.Parser<Slice<Token>, Expression, string>; /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-IntegerLiteral} */ const parseIntegerLiteral = map(Token.parseInteger, (integer) => Expression.Integer.of(integer.value) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-DecimalLiteral} */ const parseDecimalLiteral = map(Token.parseDecimal, (decimal) => Expression.Decimal.of(decimal.value) ); /** * {@link https://www.w3.org/TR/xpath-31/#prod-xpath31-DoubleLiteral} */ const parseDoubleLiteral = map(Token.parseDouble, (double) => Expression.Double.of(double.value) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-StringLiteral} */ const parseStringLiteral = map(Token.parseString, (string) => Expression.String.of(string.value) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-NumericLiteral} */ const parseNumericLiteral = either( parseIntegerLiteral, either(parseDecimalLiteral, parseDoubleLiteral) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-Literal} */ const parseLiteral = either(parseNumericLiteral, parseStringLiteral); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ParenthesizedExpr} */ const parseParenthesizedExpression = delimited( Token.parseCharacter("("), (input) => parseExpression(input), Token.parseCharacter(")") ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ContextItemExpr} */ const parseContextItemExpression = map(Token.parseCharacter("."), () => Expression.ContextItem.of() ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-PrimaryExpr} */ const parsePrimaryExpression = either( parseLiteral, either(parseParenthesizedExpression, parseContextItemExpression) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ElementName} */ const parseElementName = map(Token.parseName(), (name) => name.value); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ElementNameOrWildcard} */ const parseElementNameOrWildcard = either( parseElementName, map(Token.parseCharacter("*"), (character) => fromCharCode(character.value)) ); /** * {@link https://www.w3.org/TR/xpath-31/#prod-xpath31-AttributeName} */ const parseAttributeName = map(Token.parseName(), (name) => name.value); /** * {@link https://www.w3.org/TR/xpath-31/#prod-xpath31-AttribNameOrWildcard} */ const parseAttributeNameOrWildcard = either( parseAttributeName, map(Token.parseCharacter("*"), (character) => fromCharCode(character.value)) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-TypeName} */ // const parseTypeName = map(Token.parseName(), (name) => name.value); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-DocumentTest} */ const parseDocumentTest = map( pair( Token.parseName("document-node"), pair(Token.parseCharacter("("), Token.parseCharacter(")")) ), () => Expression.Test.Document.of() ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ElementTest} */ const parseElementTest = map( right( Token.parseName("element"), right( Token.parseCharacter("("), left(option(parseElementNameOrWildcard), Token.parseCharacter(")")) ) ), (name) => Expression.Test.Element.of(name) ); /** * {@link https://www.w3.org/TR/xpath-31/#prod-xpath31-AttributeTest} */ const parseAttributeTest = map( right( Token.parseName("attribute"), right( Token.parseCharacter("("), left(option(parseAttributeNameOrWildcard), Token.parseCharacter(")")) ) ), (name) => Expression.Test.Attribute.of(name) ); /** * {@link https://www.w3.org/TR/xpath-31/#prod-xpath31-CommentTest} */ const parseCommentTest = map( pair( Token.parseName("comment"), pair(Token.parseCharacter("("), Token.parseCharacter(")")) ), () => Expression.Test.Comment.of() ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-TextTest} */ const parseTextTest = map( pair( Token.parseName("text"), pair(Token.parseCharacter("("), Token.parseCharacter(")")) ), () => Expression.Test.Text.of() ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-AnyKindTest} */ const parseAnyKindTest = map( pair( Token.parseName("node"), pair(Token.parseCharacter("("), Token.parseCharacter(")")) ), () => Expression.Test.Node.of() ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-KindTest} */ const parseKindTest = map( either( parseElementTest, either( parseAttributeTest, either( parseDocumentTest, either(parseCommentTest, either(parseTextTest, parseAnyKindTest)) ) ) ), (test) => Option.of(test) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-NameTest} */ const parseNameTest = either( map(Token.parseName(), (name) => Option.of(Expression.Test.Name.of(name.prefix, name.value)) ), map(Token.parseCharacter("*"), () => None as Option<Expression.Test.Name>) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-NodeTest} */ const parseNodeTest = map(either(parseKindTest, parseNameTest), (test) => test.isSome() ? Option.of(test.get()) : None ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ReverseAxis} */ const parseReverseAxis = left( map( Token.parseName( property( "value", equals( "parent", "ancestor", "preceding-sibling", "preceding", "ancestor-or-self" ) ) ), (name) => name.value as Expression.Axis.Type ), take(Token.parseCharacter(":"), 2) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-AbbrevReverseStep} */ const parseAbbreviatedReverseStep = map( take(Token.parseCharacter("."), 2), () => Expression.Axis.of("parent", Option.of(Expression.Test.Node.of())) ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ReverseStep} */ const parseReverseStep = either( map(pair(parseReverseAxis, parseNodeTest), (result) => { const [axis, test] = result; return Expression.Axis.of(axis, test); }), parseAbbreviatedReverseStep ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ForwardAxis} */ const parseForwardAxis = left( map( Token.parseName( property( "value", equals( "child", "descendant", "attribute", "self", "descendant-or-self", "following-sibling", "following", "namespace" ) ) ), (name) => name.value as Expression.Axis.Type ), take(Token.parseCharacter(":"), 2) ); /** * {@link https://www.w3.org/TR/xpath-31/#prod-xpath31-AbbrevForwardStep} */ const parseAbbreviatedForwardStep = map( pair(option(Token.parseCharacter("@")), parseNodeTest), (result) => { const [attribute, test] = result; if (attribute.isSome()) { return Expression.Axis.of("attribute", test); } if ( test.some((test) => test.type === "kind" && test.kind === "attribute") ) { return Expression.Axis.of("attribute", test); } return Expression.Axis.of("child", test); } ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-ForwardStep} */ const parseForwardStep = either( map(pair(parseForwardAxis, parseNodeTest), (result) => { const [axis, test] = result; return Expression.Axis.of(axis, test); }), parseAbbreviatedForwardStep ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-Predicate} */ const parsePredicate = delimited( Token.parseCharacter("["), (input) => parseExpression(input), Token.parseCharacter("]") ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-PredicateList} */ const parsePredicateList = zeroOrMore(parsePredicate); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-AxisStep} */ const parseAxisStep = map( pair(either(parseReverseStep, parseForwardStep), parsePredicateList), (result) => { const [axis, predicates] = result; return Expression.Axis.of(axis.axis, axis.test, Array.from(predicates)); } ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-PostfixExpr} */ const parsePostfixExpression = map( pair(parsePrimaryExpression, zeroOrMore(parsePredicate)), (result) => { const [base, [...predicates]] = result; if (predicates.length === 0) { return base; } return Expression.Filter.of(base, predicates); } ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-StepExpr} */ const parseStepExpression = either(parseAxisStep, parsePostfixExpression); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-RelativePathExpr} */ const parseRelativePathExpression = map( pair( parseStepExpression, zeroOrMore( pair( either( map(take(Token.parseCharacter("//"), 2), () => true), map(Token.parseCharacter("/"), () => false) ), parseStepExpression ) ) ), (result) => { const [left, right] = result; return [...right].reduce((left, [expand, right]) => { if (expand) { right = Expression.Path.of( Expression.Axis.of( "descendant-or-self", Option.of(Expression.Test.Node.of()) ), right ); } return Expression.Path.of(left, right); }, left); } ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-PathExpr} */ const parsePathExpression = either( either( map( right(take(Token.parseCharacter("/"), 2), parseRelativePathExpression), (right) => Expression.Path.of( Expression.FunctionCall.of(Option.of("fn"), "root", 1, [ Expression.Axis.of("self", Option.of(Expression.Test.Node.of())), ]), Expression.Path.of( Expression.Axis.of( "descendant-or-self", Option.of(Expression.Test.Node.of()) ), right ) ) ), map( right(Token.parseCharacter("/"), option(parseRelativePathExpression)), (right) => { const left = Expression.FunctionCall.of(Option.of("fn"), "root", 1, [ Expression.Axis.of("self", Option.of(Expression.Test.Node.of())), ]); if (right.isSome()) { return Expression.Path.of(left, right.get()); } return left; } ) ), parseRelativePathExpression ); /** * {@link https://www.w3.org/TR/xpath-31/#doc-xpath31-Expr} */ parseExpression = parsePathExpression;
the_stack
import * as assert from 'assert'; import * as path from 'path'; import * as ts from 'vscode-chrome-debug-core-testsupport'; import { DebugProtocol } from 'vscode-debugprotocol'; import * as utils from '../src/utils'; import * as testSetup from './testSetup'; const DATA_ROOT = testSetup.DATA_ROOT; suite('Node Debug Adapter etc', () => { let dc: ts.debugClient.ExtendedDebugClient; setup(() => { return testSetup.setup() .then(_dc => dc = _dc); }); teardown(() => { return testSetup.teardown(); }); suite('basic', () => { test('unknown request should produce error', done => { dc.send('illegal_request').then(() => { done(new Error('does not report error on unknown request')); }).catch(() => { done(); }); }); }); suite('initialize', () => { test('should return supported features', () => { return dc.initializeRequest().then(response => { assert.equal(response.body.supportsConfigurationDoneRequest, true); }); }); test('should produce error for invalid \'pathFormat\'', () => { return dc.initializeRequest({ adapterID: 'mock', linesStartAt1: true, columnsStartAt1: true, pathFormat: 'url' }).then(response => { throw new Error('does not report error on invalid \'pathFormat\' attribute'); }).catch(err => { // error expected }); }); }); suite('launch', () => { test('should run program to the end', () => { if (utils.compareSemver(process.version, 'v8.0.0') < 0) { // Skip test if the node version doesn't emit the Runtime.executionContextDestroyed event return Promise.resolve(); } const PROGRAM = path.join(DATA_ROOT, 'program.js'); return Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM }), dc.waitForEvent('terminated') ]); }); test('should stop on entry', () => { const PROGRAM = path.join(DATA_ROOT, 'program.js'); const ENTRY_LINE = 1; return Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM, stopOnEntry: true }), dc.assertStoppedLocation('entry', { path: PROGRAM, line: ENTRY_LINE } ) ]); }); test('should stop on debugger statement', () => { const PROGRAM = path.join(DATA_ROOT, 'programWithDebugger.js'); const DEBUGGER_LINE = 6; return Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM }), dc.assertStoppedLocation('debugger_statement', { path: PROGRAM, line: DEBUGGER_LINE } ) ]); }); }); suite('output events', () => { // https://github.com/Microsoft/vscode/issues/37770 test('get output events in correct order', async () => { const PROGRAM = path.join(DATA_ROOT, 'programWithConsoleLogging.js'); await Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM })]); let lastEventType: string; return new Promise((resolve, reject) => { dc.on('output', outputEvent => { const msg: string = outputEvent.body.output.trim(); if (msg.startsWith('log:') || msg.startsWith('error:')) { const type: string = outputEvent.body.category; if (type === lastEventType) { return reject(new Error(`Got two messages in a row of type ${type}`)); } else if (msg === 'error: 9') { return resolve(); } lastEventType = type; } }); }); }); // https://github.com/Microsoft/vscode-node-debug2/issues/156 test(`don't lose error output at the end of the program`, async () => { // It's possible for some Node versions to exit and never report the exception if (utils.compareSemver(process.version, 'v8.5.0') < 0) { return Promise.resolve(); } const PROGRAM = path.join(DATA_ROOT, 'programWithUncaughtException.js'); await Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM })]); let gotOutput = false; return new Promise((resolve, reject) => { dc.on('output', outputEvent => { const msg: string = outputEvent.body.output.trim(); if (msg.startsWith('Error: uncaught exception')) { gotOutput = true; resolve(); } }); dc.on('terminated', () => { if (!gotOutput) { reject(new Error('Terminated before exception output received')); } }); }); }); }); suite('eval', () => { const PROGRAM = path.join(DATA_ROOT, 'programWithFunction.js'); function start(): Promise<void> { return Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM }), dc.waitForEvent('initialized') ]).then(() => { }); } test('works for a simple case', () => { return start() .then(() => dc.evaluateRequest({ expression: '1 + 1' })) .then(response => { assert(response.success); assert.equal(response.body.result, '2'); assert.equal(response.body.variablesReference, 0); }); }); test('evaluates a global node thing', () => { return start() .then(() => dc.evaluateRequest({ expression: 'Object' })) .then(response => { assert(response.success); assert.equal(response.body.result, 'function Object() { … }'); assert(response.body.variablesReference > 0); }); }); test('returns "not available" for a reference error', () => { return start() .then(() => dc.evaluateRequest({ expression: 'notDefinedThing' })) .catch(response => { assert.equal(response.message, 'not available'); }); }); test('returns the error message for another error', () => { return start() .then(() => dc.evaluateRequest({ expression: 'throw new Error("fail")' })) .catch(response => { assert.equal(response.message, 'Error: fail'); }); }); test('Shows object previews', () => { return start() .then(() => dc.evaluateRequest({ expression: 'x = {a: 1, b: [1], c: {a: 1}}' })) .then(response => { assert(response.success); assert(response.body.result === 'Object {a: 1, b: Array(1), c: Object}' || response.body.result === 'Object {a: 1, b: Array[1], c: Object}'); assert(response.body.variablesReference > 0); }); }); test('Shows array previews', () => { return start() .then(() => dc.evaluateRequest({ expression: '[1, [1], {a: 3}]' })) .then(response => { assert(response.success); assert(response.body.result === 'Array[3] [1, Array[1], Object]' || response.body.result === 'Array(3) [1, Array(1), Object]'); assert(response.body.variablesReference > 0); }); }); }); suite('completions', () => { const PROGRAM = path.join(DATA_ROOT, 'programWithVariables.js'); function start(): Promise<void> { return Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM }), dc.waitForEvent('initialized'), dc.waitForEvent('stopped') ]).then(() => { }); } function testCompletions(text: string, column = text.length + 1, frameIdx = 0): Promise<DebugProtocol.CompletionItem[]> { return start() .then(() => dc.stackTraceRequest()) .then(stackTraceResponse => stackTraceResponse.body.stackFrames.map(frame => frame.id)) .then(frameIds => dc.send('completions', <DebugProtocol.CompletionsArguments>{ text, column, frameId: frameIds[frameIdx] })) .then((response: DebugProtocol.CompletionsResponse) => response.body.targets); } function inCompletionsList(completions: DebugProtocol.CompletionItem[], ...labels: string[]): boolean { return labels.every(label => completions.filter(target => target.label === label).length === 1); } test('returns global vars', () => { return testCompletions('') .then(completions => assert(inCompletionsList(completions, 'global'))); }); test('returns local vars', () => { return testCompletions('') .then(completions => assert(inCompletionsList(completions, 'num', 'str', 'arr', 'obj'))); }); test('returns methods', () => { return testCompletions('arr.') .then(completions => assert(inCompletionsList(completions, 'push', 'indexOf'))); }); test('returns object properties', () => { return testCompletions('obj.') .then(completions => assert(inCompletionsList(completions, 'a', 'b'))); }); test('multiple dots', () => { return testCompletions('obj.b.') .then(completions => assert(inCompletionsList(completions, 'startsWith', 'endsWith'))); }); test('returns from the correct column', () => { return testCompletions('obj.b.', /*column=*/6) .then(completions => assert(inCompletionsList(completions, 'a', 'b'))); }); test('returns from the correct frameId', () => { return testCompletions('obj', undefined, /*frameId=*/1) .then(completions => assert(!inCompletionsList(completions, 'obj'))); }); test('returns properties of string literals', () => { return testCompletions('"".') .then(completions => assert(inCompletionsList(completions, 'startsWith'))); }); }); suite('hit condition bps', () => { const PROGRAM = path.join(DATA_ROOT, 'programWithFunction.js'); function continueAndStop(line: number): Promise<any> { return dc.continueTo('breakpoint', { path: PROGRAM, line }); } test('Works for =', () => { const noCondBpLine = 15; const condBpLine = 14; const bps: DebugProtocol.SourceBreakpoint[] = [ { line: condBpLine, hitCondition: '=2' }, { line: noCondBpLine }]; return Promise.all([ ts.debugClient.setBreakpointOnStart(dc, bps, PROGRAM), dc.launch({ program: PROGRAM }), // Assert that it skips dc.assertStoppedLocation('breakpoint', { path: PROGRAM, line: noCondBpLine }) .then(() => continueAndStop(condBpLine)) .then(() => continueAndStop(noCondBpLine)) .then(() => continueAndStop(noCondBpLine)) ]); }); test('Works for %', () => { const noCondBpLine = 15; const condBpLine = 14; const bps: DebugProtocol.SourceBreakpoint[] = [ { line: condBpLine, hitCondition: '%3' }, { line: noCondBpLine }]; return Promise.all([ ts.debugClient.setBreakpointOnStart(dc, bps, PROGRAM), dc.launch({ program: PROGRAM }), // Assert that it skips dc.assertStoppedLocation('breakpoint', { path: PROGRAM, line: noCondBpLine }) .then(() => continueAndStop(noCondBpLine)) .then(() => continueAndStop(condBpLine)) .then(() => continueAndStop(noCondBpLine)) ]); }); test('Does not bind when invalid', () => { const condBpLine = 14; const bps: DebugProtocol.SourceBreakpoint[] = [ { line: condBpLine, hitCondition: 'lsdf' }]; return Promise.all([ ts.debugClient.setBreakpointOnStart(dc, bps, PROGRAM, undefined, undefined, /*expVerified=*/false), dc.launch({ program: PROGRAM }) ]); }); }); suite('get loaded scripts', () => { function assertHasSource(loadedSources: DebugProtocol.Source[], expectedPath: string): void { assert(loadedSources.find(source => source.path === expectedPath)); } test('returns all scripts', async () => { const PROGRAM = path.join(DATA_ROOT, 'simple-eval/index.js'); await dc.hitBreakpoint({ program: PROGRAM }, { path: PROGRAM, line: 3 }); const { sources } = await dc.loadedSources({ }); assert(!!sources); assert(sources.length > 10); // Has the program assertHasSource(sources, PROGRAM); // Has some node_internals script const nodeInternalsScript = '<node_internals>/timers.js'; assertHasSource(sources, nodeInternalsScript); // Has the eval script assert(sources.filter(source => source.path.match(/VM\d+/)).length >= 1); }); }); suite('async callstacks', () => { function assertAsyncLabelCount(stackTrace: DebugProtocol.StackTraceResponse, expectedAsyncLabels: number): void { assert.equal(stackTrace.body.stackFrames.filter(frame => !frame.source).length, expectedAsyncLabels); } function assertStackFrame(stackTrace: DebugProtocol.StackTraceResponse, i: number, sourcePath: string, line: number): void { const frame = stripAsyncHookFrames(stackTrace)[i]; assert(!!frame); assert.equal(frame.source && frame.source.path, sourcePath); // Before node 8.7, a stackframe before an async call is on the first line of the calling function, not the function decl line. // Same with 8.9.4 exactly. So just check for either one. assert(frame.line === line || frame.line === line - 1, `Expected line ${line} or ${line - 1}`); } /** * After node 8.7, there are two async_hooks frames to count. In 8.9.4 exactly, the async_hook frames don't show up in the stack. * Then in later versions they show up again. Easier to just remove them to use the same stack trace indexes for all versions. */ function stripAsyncHookFrames(stackTrace: DebugProtocol.StackTraceResponse): DebugProtocol.StackFrame[] { return stackTrace.body.stackFrames.filter(frame => !frame.source || frame.source.path.indexOf('async_hook') < 0); } test('shows async stacks for promise resolution', async () => { const PROGRAM = path.join(DATA_ROOT, 'promise-chain/main.js'); const breakpoints: DebugProtocol.SourceBreakpoint[] = [7, 13, 19, 25, 31].map(line => ({ line })); await dc.hitBreakpoint({ program: PROGRAM, showAsyncStacks: true }, { path: PROGRAM, line: 45}); await dc.setBreakpointsRequest({ source: { path: PROGRAM }, breakpoints }); await dc.continueAndStop(); assertAsyncLabelCount(await dc.stackTraceRequest(), 1); await dc.continueAndStop(); assertAsyncLabelCount(await dc.stackTraceRequest(), 2); await dc.continueAndStop(); assertAsyncLabelCount(await dc.stackTraceRequest(), 3); await dc.continueAndStop(); assertAsyncLabelCount(await dc.stackTraceRequest(), 4); // Hit the limit of 4 async parents await dc.continueAndStop(); assertAsyncLabelCount(await dc.stackTraceRequest(), 4); }); async function stepOverNativeAwait(fromLine: number, afterBp = false) { const toLine = fromLine + 1; if (utils.compareSemver(process.version, 'v8.0.0') < 0 || (utils.compareSemver(process.version, 'v8.4.0') >= 0 && utils.compareSemver(process.version, 'v8.7.0') < 0)) { // In pre-8, must always step twice over await lines await dc.nextTo('step', { line: fromLine }); await dc.nextTo('step', { line: fromLine }); } else if (!afterBp && utils.compareSemver(process.version, 'v8.7.0') < 0) { // In 8, must step an extra time if a BP on this line didn't cause the break await dc.nextTo('step', { line: fromLine }); } await dc.nextTo('step', { line: toLine }); } test('shows async stacks and steps correctly for native async/await, pre v10', async () => { if (utils.compareSemver(process.version, 'v7.6.0') < 0 || utils.compareSemver(process.version, 'v10.0.0') >= 0) { return Promise.resolve(); } const PROGRAM = path.join(DATA_ROOT, 'native-async-await/main.js'); await dc.hitBreakpoint({ program: PROGRAM, showAsyncStacks: true, skipFiles: ['<node_internals>/**'] }, { path: PROGRAM, line: 8 }); await stepOverNativeAwait(8, /*afterBp=*/true); let stackTrace = await dc.stepInTo('step', { line: 13 }); assertStackFrame(stackTrace, 3, PROGRAM, 8); assertStackFrame(stackTrace, 4, PROGRAM, 40); assertAsyncLabelCount(stackTrace, 1); await stepOverNativeAwait(13); stackTrace = await dc.stepInTo('step', { line: 18 }); assertStackFrame(stackTrace, 3, PROGRAM, 13); assertStackFrame(stackTrace, 4, PROGRAM, 9); assertAsyncLabelCount(stackTrace, 2); await stepOverNativeAwait(18); stackTrace = await dc.stepInTo('step', { line: 23 }); assertStackFrame(stackTrace, 3, PROGRAM, 18); assertStackFrame(stackTrace, 4, PROGRAM, 14); assertAsyncLabelCount(stackTrace, 3); await stepOverNativeAwait(23); stackTrace = await dc.stepInTo('step', { line: 28 }); assertStackFrame(stackTrace, 3, PROGRAM, 23); assertStackFrame(stackTrace, 4, PROGRAM, 19); assertAsyncLabelCount(stackTrace, 4); }); // test.only('shows async stacks and steps correctly for native async/await', async () => { // if (utils.compareSemver(process.version, 'v10.0.0') < 0) { // return Promise.resolve(); // } // const PROGRAM = path.join(DATA_ROOT, 'native-async-await/main.js'); // await dc.hitBreakpoint({ program: PROGRAM, showAsyncStacks: true, skipFiles: ['<node_internals>/**'] }, { path: PROGRAM, line: 8 }); // await stepOverNativeAwait(8, /*afterBp=*/true); // let stackTrace = await dc.stepInTo('step', { line: 13 }); // assertStackFrame(stackTrace, 3, PROGRAM, 8); // assertStackFrame(stackTrace, 4, PROGRAM, 40); // assertAsyncLabelCount(stackTrace, 1); // await stepOverNativeAwait(13); // stackTrace = await dc.stepInTo('step', { line: 18 }); // assertStackFrame(stackTrace, 3, PROGRAM, 8); // assertAsyncLabelCount(stackTrace, 2); // await stepOverNativeAwait(18); // stackTrace = await dc.stepInTo('step', { line: 23 }); // assertStackFrame(stackTrace, 3, PROGRAM, 13); // assertAsyncLabelCount(stackTrace, 3); // await stepOverNativeAwait(23); // stackTrace = await dc.stepInTo('step', { line: 28 }); // assertStackFrame(stackTrace, 3, PROGRAM, 18); // assertAsyncLabelCount(stackTrace, 4); // }); }); });
the_stack
/*@ nextSymbolId :: posint */ let nextSymbolId = 1; /*@ nextNodeId :: posint */ let nextNodeId = 1; /*@ nextMergeId :: posint */ let nextMergeId = 1; /*@ global */ let mergedSymbols: MArray<ISymbol> = []; /*@ global */ let symbolLinks: MArray<ISymbolLinks> = []; /*@ global */ let nodeLinks: MArray<INodeLinks> = []; module checker_ts { /*@ getDeclarationOfKind :: (symbol: ISymbol, kind: ts.SyntaxKind) => { ts.Declaration<Immutable> | offset(v,"kind") = kind } + undefined */ export function getDeclarationOfKind(symbol: ISymbol, kind: ts.SyntaxKind): IDeclaration { let declarations = symbol.declarations; for (let i = 0; i < declarations.length; i++) { let declaration = declarations[i]; if (declaration.kind === kind) { return declaration; } } return undefined; } /// fullTypeCheck denotes if this instance of the typechecker will be used to get semantic diagnostics. /// If fullTypeCheck === true, then the typechecker should do every possible check to produce all errors /// If fullTypeCheck === false, the typechecker can take shortcuts and skip checks that only produce errors. /// NOTE: checks that somehow affect decisions being made during typechecking should be executed in both cases. declare let program: ts.Program<Immutable>; declare let objectAllocator: cts.ObjectAllocator<Immutable>; let Symbol = objectAllocator.getSymbolConstructor(); let Type = objectAllocator.getTypeConstructor(); let Signature = objectAllocator.getSignatureConstructor(); /*@ typeCount :: nat */ let typeCount = 0; /*@ emptyArray :: <T>() => { IArray<T> | len v = 0 } */ let emptyArray = function(): any[] { return []; }; let emptySymbols: ts.SymbolTable<Immutable> = {}; let compilerOptions = program.getCompilerOptions(); /*@ readonly */ let checker: ts.TypeChecker<Immutable> = { //getProgram: () => program, //getDiagnostics: getDiagnostics, //getGlobalDiagnostics: getGlobalDiagnostics, //getNodeCount: () => sum(program.getSourceFiles(), "nodeCount"), //getIdentifierCount: () => sum(program.getSourceFiles(), "identifierCount"), //getSymbolCount: () => sum(program.getSourceFiles(), "symbolCount"), //getTypeCount: () => typeCount, //checkProgram: checkProgram, //emitFiles: invokeEmitter, //getParentOfSymbol: getParentOfSymbol, //getTypeOfSymbol: getTypeOfSymbol, //getPropertiesOfType: getPropertiesOfType, //getPropertyOfType: getPropertyOfType, //getSignaturesOfType: getSignaturesOfType, //getIndexTypeOfType: getIndexTypeOfType, //getReturnTypeOfSignature: getReturnTypeOfSignature, //getSymbolsInScope: getSymbolsInScope, //getSymbolInfo: getSymbolInfo, //getTypeOfNode: getTypeOfNode, //getApparentType: getApparentType, //typeToString: typeToString, //symbolToString: symbolToString, //getAugmentedPropertiesOfApparentType: getAugmentedPropertiesOfApparentType, //getRootSymbol: getRootSymbol, //getContextualType: getContextualType }; /*@ createSymbol :: <M extends ReadOnly>(flags: bitvector32, name: string) => ts.Symbol<M> */ /*@ createSymbol :: <M extends ReadOnly>(flags: number , name: string) => ts.Symbol<M> */ declare function createSymbol<M extends ReadOnly>(flags: ts.SymbolFlags, name: string): ts.Symbol<M> /*@ getExcludedSymbolFlags :: (flags: ts.SymbolFlags) => bitvector32 */ export function getExcludedSymbolFlags(flags: ts.SymbolFlags): ts.SymbolFlags { let result = 0x00000000; // 0; //TODO: undefined below //if (flags & SymbolFlags.Variable) result = result | SymbolFlags.VariableExcludes; //if (flags & SymbolFlags.Property) result = result | SymbolFlags.PropertyExcludes; //if (flags & SymbolFlags.EnumMember) result = result | SymbolFlags.EnumMemberExcludes; //if (flags & SymbolFlags.Function) result = result | SymbolFlags.FunctionExcludes; //if (flags & SymbolFlags.Class) result = result | SymbolFlags.ClassExcludes; //if (flags & SymbolFlags.Interface) result = result | SymbolFlags.InterfaceExcludes; //if (flags & SymbolFlags.Enum) result = result | SymbolFlags.EnumExcludes; //if (flags & SymbolFlags.ValueModule) result = result | SymbolFlags.ValueModuleExcludes; //if (flags & SymbolFlags.Method) result = result | SymbolFlags.MethodExcludes; //if (flags & SymbolFlags.GetAccessor) result = result | SymbolFlags.GetAccessorExcludes; //if (flags & SymbolFlags.SetAccessor) result = result | SymbolFlags.SetAccessorExcludes; //if (flags & SymbolFlags.TypeParameter) result = result | SymbolFlags.TypeParameterExcludes; //if (flags & SymbolFlags.Import) result = result | SymbolFlags.ImportExcludes; return result ; } export let recordMergedSymbol = function(target: ISymbol, source: ISymbol): void { if (!source.mergeId) source.mergeId = nextMergeId++; mergedSymbols[source.mergeId] = target; } export let getSymbolLinks = function(symbol: ISymbol): ISymbolLinks { if (symbol.flags & ts.SymbolFlags.Transient) { return <ts.TransientSymbol<Immutable>>symbol; } if (!symbol.id) symbol.id = nextSymbolId++; let s = symbolLinks[symbol.id]; if(s) { return s; } else { let o: ISymbolLinks = {}; symbolLinks[symbol.id] = o; return o; } } export function getNodeLinks(node: INode): INodeLinks { let node_id = node.id; if (!node_id) { node_id = nextNodeId++; node.id = node_id; /*@ local node_id_0 :: number + undefined */ let node_id_0 = node_id; node_id = node_id_0; } let n = nodeLinks[<number>node_id]; if(n) { return n; } else { let o: INodeLinks = {}; nodeLinks[<number>node_id] = o; return o; } } // /* @ getAncestor :: (node: INode + undefined, kind: ts.SyntaxKind) => undefined + { INode | offset v "kind" = kind } */ // // export declare let getAncestor: (node: INode, kind: ts.SyntaxKind) => INode; // export let getAncestor = function(node: INode, kind: ts.SyntaxKind): INode { // if (kind === ts.SyntaxKind.ClassDeclaration) { // while (typeof node !== "undefined") { // if (node.kind === ts.SyntaxKind.ClassDeclaration) { // //return <ClassDeclaration>node; // return <INode>node; // } // else if (kind === ts.SyntaxKind.EnumDeclaration || // kind === ts.SyntaxKind.InterfaceDeclaration || // kind === ts.SyntaxKind.ModuleDeclaration || // kind === ts.SyntaxKind.ImportDeclaration) { // // early exit cases - declarations cannot be nested in classes // return undefined; // } // else { // node = node.parent; // } // } // } // else { // while (node) { // if (node.kind === kind) { // return <INode>node; // } // else { // node = node.parent; // } // } // } // // return undefined; // } // /* @ getSourceFile :: (node: INode + undefined) => undefined + ts.SourceFile<Immutable> */ // export let getSourceFile = function(node: INode): ts.SourceFile<Immutable> { // let ancestor = getAncestor(node, ts.SyntaxKind.SourceFile); // if (ancestor) { // return <ts.SourceFile<Immutable>> (<ts.Node<Immutable>>ancestor); // } else { // return undefined; // } // } /*@ createType :: (flags: bitvector32) => { ts.Type<Unique> | type_flags flags v } */ let createType = function(flags: ts.TypeFlags): ts.Type<Unique> { /* result :: ts.Type<Unique> */ let result = cts.newType(checker, flags); result.id = typeCount++; return result; } // /* @ createObjectType :: ( kind: { bitvector32 | mask_typeflags_anonymous(v) || mask_typeflags_reference(v) } // , symbol: ISymbol + undefined // ) => { ts.ObjectType<Unique> | type_flags kind v } */ // let createObjectType = function<M extends ReadOnly>(kind: ts.TypeFlags, symbol?: ISymbol): ts.ObjectType<M> { // let type = <ts.ObjectType<Unique>>createType(kind); // // TODO // // type.symbol = symbol; // return type; // } // // export declare function resolveObjectTypeMembers(type: ts.ObjectType<Immutable>): ts.ResolvedObjectType<Immutable>; // export let getPropertiesOfType = function(type: IType): IArray<ISymbol> { // if (type.flags & ts.TypeFlags.ObjectType) { // return resolveObjectTypeMembers(<ts.ObjectType<Immutable>>type).properties; // } // return emptyArray(); // } // // export declare function getTypeListId(types: IArray<IType>): number; // // export let createTypeReference = function(target: ts.GenericType<Immutable>, typeArguments: IArray<IType>): ts.TypeReference<Immutable> { // let id = getTypeListId(typeArguments); // let type = target.instantiations[id.toString()]; // if (!type) { // assume(target.symbol); // TODO: Remove this assumption // let type1 = <ts.TypeReference<Unique>>createObjectType(ts.TypeFlags.Reference, target.symbol); // let tmp = target.instantiations; // // tmp[id] = type1; // TODO: Cannot assign a Unique variable // type1.target = target; // type1.typeArguments = typeArguments; // return type1; // } // return type; // } export function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode: ts.TypeReferenceNode<Immutable>, typeParameterSymbol: ISymbol): boolean { let links = getNodeLinks(typeReferenceNode); let links_isIllegalTypeReferenceInConstraint_tmp = links.isIllegalTypeReferenceInConstraint; // if (links.isIllegalTypeReferenceInConstraint !== undefined) { if (typeof links_isIllegalTypeReferenceInConstraint_tmp !== "undefined") { return links_isIllegalTypeReferenceInConstraint_tmp; } assert(false); // bubble up to the declaration /*@ global */ let currentNode: INode = typeReferenceNode; // forEach === exists let _check: (d: IDeclaration) => boolean = function(d) { return d.parent === currentNode.parent } let cnt = true; // PV: adding explicit check while (cnt && !cts.forEach(typeParameterSymbol.declarations, _check)) { let cp = currentNode.parent; if (cp) { currentNode = <INode>cp; } else { cnt = false; } } // if last step was made from the type parameter this means that path has started somewhere in constraint which is illegal links_isIllegalTypeReferenceInConstraint_tmp = currentNode.kind === ts.SyntaxKind.TypeParameter; links.isIllegalTypeReferenceInConstraint = links_isIllegalTypeReferenceInConstraint_tmp; return links_isIllegalTypeReferenceInConstraint_tmp; } // export function instantiateList<T>(items: IArray<T>, // mapper: ts.TypeMapper<Immutable>, // instantiator: (item: T, mapper: ts.TypeMapper<Immutable>) => T): MArray<T> { // if (items && items.length) { // /* @ result :: MArray<T> */ // let result: MArray<T> = []; // for (let i = 0; i < items.length; i++) { // result.push(instantiator(items[i], mapper)); // } // return result; // } // /* @ result :: MArray<T> */ // let result: MArray<T> = []; // return result; // // return items; // PV: replacing the original // } }
the_stack
* @module OrbitGT */ // package orbitgt.pointcloud.format.opc; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { Bounds } from "../../../spatial/geom/Bounds"; import { Coordinate } from "../../../spatial/geom/Coordinate"; import { ABuffer } from "../../../system/buffer/ABuffer"; import { Uint16Buffer } from "../../../system/buffer/Uint16Buffer"; import { Uint8Buffer } from "../../../system/buffer/Uint8Buffer"; import { AList } from "../../../system/collection/AList"; import { ALong } from "../../../system/runtime/ALong"; import { ASystem } from "../../../system/runtime/ASystem"; import { Message } from "../../../system/runtime/Message"; import { Strings } from "../../../system/runtime/Strings"; import { ContentLoader } from "../../../system/storage/ContentLoader"; import { FileStorage } from "../../../system/storage/FileStorage"; import { AttributeValue } from "../../model/AttributeValue"; import { BlockIndex } from "../../model/BlockIndex"; import { CloudPoint } from "../../model/CloudPoint"; import { Grid } from "../../model/Grid"; import { PointAttribute } from "../../model/PointAttribute"; import { PointCloudReader } from "../../model/PointCloudReader"; import { PointData } from "../../model/PointData"; import { PointDataRaw } from "../../model/PointDataRaw"; import { ReadRequest } from "../../model/ReadRequest"; import { StandardAttributes } from "../../model/StandardAttributes"; import { TileIndex } from "../../model/TileIndex"; import { AttributeMask } from "./AttributeMask"; import { AttributeReader } from "./AttributeReader"; import { DirectoryReader } from "./DirectoryReader"; import { FileReader } from "./FileReader"; import { PointReader } from "./PointReader"; import { TileReadBuffer } from "./TileReadBuffer"; /** * Class OPCReader reads pointcloud files. * * @version 1.0 January 2014 */ /** @internal */ export class OPCReader extends PointCloudReader { /** The file reader */ private _fileReader: FileReader; /** The index of the first level */ private _levelOffset: int32; /** The number of levels */ private _levelCount: int32; /** * Create a new reader for a file. * @param fileName the name of the file. * @param lazyLoading avoid early loading of all block indexes to keep a low memory profile? Lazy loading only loads the block indexes of the top 6 levels (see CLOUD-1152 issue) * @return the reader. */ public static async openFile(fileStorage: FileStorage, fileName: string, lazyLoading: boolean): Promise<OPCReader> { /* Open the file */ const fileReader: FileReader = await FileReader.openFile(fileStorage, fileName, lazyLoading); /* Create the reader */ return new OPCReader(fileReader, 0, fileReader.getLevelCount()); } /** * Create a new reader. */ private constructor(fileReader: FileReader, levelOffset: int32, levelCount: int32) { super(); this._fileReader = fileReader; this._levelOffset = levelOffset; this._levelCount = levelCount; } /** * Get the file reader. * @return the file reader. */ public getFileReader(): FileReader { return this._fileReader; } /** * PointCloudReader method. * @see PointCloudReader#close */ public override close(): void { if (this._fileReader != null) this._fileReader.close(); this._fileReader = null; } /** * PointCloudReader method. * @see PointCloudReader#getProperty */ public override getProperty(propertyName: string): Object { if (propertyName == null) return null; if (Strings.equalsIgnoreCase(propertyName, "metricCellSize")) return new Coordinate(this._fileReader.getFileRecord().getMetricCellSize(), 0.0, 0.0); return null; } /** * PointCloudReader method. * @see PointCloudReader#getFileStorage */ public override getFileStorage(): FileStorage { return this._fileReader.getFileStorage(); } /** * PointCloudReader method. * @see PointCloudReader#getFileName */ public override getFileName(): string { return this._fileReader.getFileName(); } /** * PointCloudReader method. * @see PointCloudReader#getFileCRS */ public override getFileCRS(): string { return this._fileReader.getFileRecord().getCRS(); } /** * PointCloudReader method. * @see PointCloudReader#getFileBounds */ public override getFileBounds(): Bounds { return this._fileReader.getGeometryReader(0).getGeometryRecord().getBounds(); } /** * PointCloudReader method. * @see PointCloudReader#getPointAttributes */ public override getPointAttributes(): Array<PointAttribute> { return this._fileReader.getAttributes(); } /** * PointCloudReader method. * @see PointCloudReader#getMinAttributeValue */ public override getMinAttributeValue(attribute: PointAttribute): AttributeValue { for (const reader of this._fileReader.getAttributeReaders()) if (reader.getAttribute().hasName(attribute.getName())) return reader.getMinimumValue(); return null; } /** * PointCloudReader method. * @see PointCloudReader#getMaxAttributeValue */ public override getMaxAttributeValue(attribute: PointAttribute): AttributeValue { for (const reader of this._fileReader.getAttributeReaders()) if (reader.getAttribute().hasName(attribute.getName())) return reader.getMaximumValue(); return null; } /** * PointCloudReader method. * @see PointCloudReader#getLevelCount */ public override getLevelCount(): int32 { return this._fileReader.getLevelCount(); } /** * PointCloudReader method. * @see PointCloudReader#getLevelPointCount */ public override getLevelPointCount(level: int32): ALong { return this._fileReader.getDirectoryReader(level).getDirectoryRecord().getPointCount(); } /** * PointCloudReader method. * @see PointCloudReader#getLevelPointBounds */ public override getLevelPointBounds(level: int32): Bounds { return this._fileReader.getGeometryReader(level).getGeometryRecord().getBounds(); } /** * PointCloudReader method. * @see PointCloudReader#getLevelBlockGrid */ public override getLevelBlockGrid(level: int32): Grid { return this.getLevelTileGrid(level).scale(this._fileReader.getFileRecord().getBlockSize()); } /** * PointCloudReader method. * @see PointCloudReader#getLevelTileGrid */ public override getLevelTileGrid(level: int32): Grid { return this._fileReader.getGeometryReader(level).getGeometryRecord().getTileGrid(); } /** * PointCloudReader method. * @see PointCloudReader#peekBlockIndexes */ public override peekBlockIndexes(level: int32): Array<BlockIndex> { return this._fileReader.getDirectoryReader(level).getBlocks(); } /** * PointCloudReader method. * @see PointCloudReader#readBlockIndexes */ public override readBlockIndexes(level: int32, fileContents: ContentLoader): Array<BlockIndex> { /* Get the directory reader */ const directoryReader: DirectoryReader = this._fileReader.getDirectoryReader(level); /* Already read all blocks? */ const blocks: Array<BlockIndex> = directoryReader.getBlocks(); if (blocks.length > 0) return blocks; /* Delegate to the directory reader */ return directoryReader.readBlocks(this._fileReader.getFileRecord(), fileContents); } /** * PointCloudReader method. * @see PointCloudReader#readTileIndexes */ public override readTileIndexes(block: BlockIndex, fileContents: ContentLoader): Array<TileIndex> { return this._fileReader.getDirectoryReader(block.level).readTiles2(block, fileContents); } /** * Get the attribute mask to use for reading. * @param parameters the read parameters. * @return the attribute mask. */ private getAttributeMask(parameters: ReadRequest): AttributeMask { /* Make a list of readers */ const readers: AList<AttributeReader> = new AList<AttributeReader>(); /* Should we read all attributes? */ if (parameters.readAllExtraAttributes()) { /* Read all attributes */ for (const reader of this._fileReader.getAttributeReaders()) readers.add(reader); } else { /* Read color? */ if (parameters.readColor()) { const reader: AttributeReader = this._fileReader.findAttributeReader(StandardAttributes.COLOR.getName()); if (reader != null) readers.add(reader); } /* Read intensity? */ if (parameters.readIntensity()) { const reader: AttributeReader = this._fileReader.findAttributeReader(StandardAttributes.INTENSITY.getName()); if (reader != null) readers.add(reader); } /* Read the extra attributes */ const extraAttributes: AList<string> = parameters.getExtraAttributes(); for (let i: number = 0; i < extraAttributes.size(); i++) { /* Get the name of the extra attribute */ const extraAttribute: string = extraAttributes.get(i); /* Did we already add the color? */ if (parameters.readColor() && Strings.equalsIgnoreCase(extraAttribute, StandardAttributes.COLOR.getName())) continue; /* Did we already add the intensity? */ if (parameters.readIntensity() && Strings.equalsIgnoreCase(extraAttribute, StandardAttributes.INTENSITY.getName())) continue; /* Find the attribute reader */ const reader: AttributeReader = this._fileReader.findAttributeReader(extraAttribute); /* Add the reader */ if (reader != null) readers.add(reader); } } /* Create the mask */ return new AttributeMask(readers); } /** * PointCloudReader interface method. * @see PointCloudReader#readPoints */ public override readPoints(tileIndex: TileIndex, readRequest: ReadRequest, fileContents: ContentLoader): AList<CloudPoint> { /* Create the attribute mask */ const attributeMask: AttributeMask = this.getAttributeMask(readRequest); /* Create the read buffer */ const tileBuffer: TileReadBuffer = new TileReadBuffer(attributeMask.attributes.length); /* Read the points in the tile */ const pointOffset: int32 = 0; const pointCount: int32 = tileIndex.pointCount; return PointReader.readTilePoints(this.getFileReader(), readRequest, attributeMask, tileIndex.level, tileIndex, pointOffset, pointCount, tileBuffer, fileContents); } /** * PointCloudReader interface method. * @see PointCloudReader#readPointData */ public override readPointData(tileIndex: TileIndex, dataFormat: int32, accessTime: float64, fileContents: ContentLoader): PointData { /* 16-bit XYZ geometry and 8-bit RGB colors? */ if (dataFormat == PointDataRaw.TYPE) { /* Create the attribute mask */ const readRequest: ReadRequest = ReadRequest.READ_GEOMETRY_AND_COLOR; const readers: AList<AttributeReader> = new AList<AttributeReader>(); const colorReader: AttributeReader = this._fileReader.findAttributeReader(StandardAttributes.COLOR.getName()); if (colorReader != null) readers.add(colorReader); const attributeMask: AttributeMask = new AttributeMask(readers); /* Has the data been loaded? */ let tileBuffer: TileReadBuffer = null; let pointData: PointDataRaw = null; if (fileContents.isAvailable()) { /* Create the read buffer */ tileBuffer = new TileReadBuffer(attributeMask.attributes.length); /* Create the point data buffer */ const tileGrid: Grid = this._fileReader.getGeometryReader(tileIndex.level).getGeometryRecord().getTileGrid(); const tileBounds: Bounds = tileGrid.getCellBounds(tileIndex.gridIndex); pointData = new PointDataRaw(tileIndex, tileBounds, null, null, null); } /* Fill the point data buffer */ PointReader.readTilePointsRaw(this.getFileReader(), readRequest, attributeMask, tileIndex, tileBuffer, pointData, fileContents); /* Missing color channel after data load? */ if (fileContents.isAvailable() && (pointData.colors == null)) { /* Define the default RGB color (0xE6C60D) */ const defaultR: int32 = 230; const defaultG: int32 = 198; const defaultB: int32 = 13; /* Create a default color buffer (BGR sample sequence) */ pointData.colors = Uint8Buffer.wrap(new ABuffer(3 * tileIndex.pointCount)); for (let i: number = 0; i < tileIndex.pointCount; i++) { pointData.colors.set(3 * i + 0, defaultB); pointData.colors.set(3 * i + 1, defaultG); pointData.colors.set(3 * i + 2, defaultR); } } return pointData; } /* Unknown format */ return null; } /** * PointCloudReader interface method. * @see PointCloudReader#clipToLevelRange */ public override clipToLevelRange(levelOffset: int32, levelCount: int32): PointCloudReader { /* Check the parameters */ ASystem.assert0(levelOffset >= 0, `Invalid level offset ${levelOffset}`); ASystem.assert0(levelCount > 0, `Invalid level count ${levelCount}`); ASystem.assert0(levelOffset + levelCount <= this._levelCount, `Level range ${levelOffset}+${levelCount} not possible in ${this._levelCount} levels`); /* Create a new reader */ return new OPCReader(this._fileReader, this._levelOffset + levelOffset, levelCount); } }
the_stack
function id(d: any[]): any { return d[0]; } interface NearleyToken { value: any; [key: string]: any; } interface NearleyLexer { reset: (chunk: string, info: any) => void; next: () => NearleyToken | undefined; save: () => any; formatError: (token: NearleyToken) => string; has: (tokenType: string) => boolean; } interface NearleyRule { name: string; symbols: NearleySymbol[]; postprocess?: (d: any[], loc?: number, reject?: {}) => any; } type NearleySymbol = | string | { literal: any } | { test: (token: any) => boolean }; interface Grammar { Lexer: NearleyLexer | undefined; ParserRules: NearleyRule[]; ParserStart: string; } const grammar: Grammar = { Lexer: undefined, ParserRules: [ { name: "_$ebnf$1", symbols: [] }, { name: "_$ebnf$1", symbols: ["_$ebnf$1", "wschar"], postprocess: (d) => d[0].concat([d[1]]), }, { name: "_", symbols: ["_$ebnf$1"], postprocess(d) { return null; }, }, { name: "__$ebnf$1", symbols: ["wschar"] }, { name: "__$ebnf$1", symbols: ["__$ebnf$1", "wschar"], postprocess: (d) => d[0].concat([d[1]]), }, { name: "__", symbols: ["__$ebnf$1"], postprocess(d) { return null; }, }, { name: "wschar", symbols: [/[ \t\n\v\f]/], postprocess: id }, { name: "clause_database_or_schema$subexpression$1", symbols: [/[dD]/, /[aA]/, /[tT]/, /[aA]/, /[bB]/, /[aA]/, /[sS]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "clause_database_or_schema", symbols: ["clause_database_or_schema$subexpression$1", "__"], }, { name: "clause_database_or_schema$subexpression$2", symbols: [/[sS]/, /[cC]/, /[hH]/, /[eE]/, /[mM]/, /[aA]/], postprocess(d) { return d.join(""); }, }, { name: "clause_database_or_schema", symbols: ["clause_database_or_schema$subexpression$2", "__"], }, { name: "clause_if_exists", symbols: [] }, { name: "clause_if_exists$subexpression$1", symbols: [/[iI]/, /[fF]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_exists$subexpression$2", symbols: [/[eE]/, /[xX]/, /[iI]/, /[sS]/, /[tT]/, /[sS]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_exists", symbols: [ "clause_if_exists$subexpression$1", "__", "clause_if_exists$subexpression$2", "__", ], }, { name: "clause_if_not_exists", symbols: [] }, { name: "clause_if_not_exists$subexpression$1", symbols: [/[iI]/, /[fF]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_not_exists$subexpression$2", symbols: [/[nN]/, /[oO]/, /[tT]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_not_exists$subexpression$3", symbols: [/[eE]/, /[xX]/, /[iI]/, /[sS]/, /[tT]/, /[sS]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_not_exists", symbols: [ "clause_if_not_exists$subexpression$1", "__", "clause_if_not_exists$subexpression$2", "__", "clause_if_not_exists$subexpression$3", "__", ], }, { name: "name$ebnf$1", symbols: [/[a-z]/] }, { name: "name$ebnf$1", symbols: ["name$ebnf$1", /[a-z]/], postprocess: (d) => d[0].concat([d[1]]), }, { name: "name", symbols: ["name$ebnf$1"] }, { name: "name_list", symbols: ["name"] }, { name: "name_list", symbols: ["name_list", "__", { literal: "," }, "name_list", "_"], }, { name: "terminator", symbols: [{ literal: ";" }] }, { name: "equals", symbols: [{ literal: "=" }] }, { name: "yes", symbols: [{ literal: "Y" }] }, { name: "no", symbols: [{ literal: "N" }] }, { name: "yes_or_no", symbols: ["yes"] }, { name: "yes_or_no", symbols: ["no"] }, { name: "statement", symbols: ["create_statements", "_", "terminator"] }, { name: "create_statements", symbols: ["create_database"] }, { name: "create_view", symbols: [ "keyword", "clause_or_replace", "clause_algorithm", "_", "clause_definer", "_", "clause_view", ], }, { name: "create_index$string$1", symbols: [ { literal: "I" }, { literal: "N" }, { literal: "D" }, { literal: "E" }, { literal: "X" }, ], postprocess: (d) => d.join(""), }, { name: "create_index$ebnf$1", symbols: [/[A-z]/] }, { name: "create_index$ebnf$1", symbols: ["create_index$ebnf$1", /[A-z]/], postprocess: (d) => d[0].concat([d[1]]), }, { name: "create_index", symbols: [ "keyword", "clause_index", "_", "create_index$string$1", "_", "create_index$ebnf$1", "_", "clause_index_type", ], }, { name: "create_database", symbols: [ "keyword", "clause_database_or_schema", "clause_if_not_exists", "name", "__", "option_create_option", ], }, { name: "keyword$subexpression$1", symbols: [/[cC]/, /[rR]/, /[eE]/, /[aA]/, /[tT]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "keyword", symbols: ["keyword$subexpression$1", "__"], postprocess: (word) => word.join(""), }, { name: "default$subexpression$1", symbols: [/[dD]/, /[eE]/, /[fF]/, /[aA]/, /[uU]/, /[lL]/, /[tT]/], postprocess(d) { return d.join(""); }, }, { name: "default", symbols: ["default$subexpression$1", "__"] }, { name: "character_set$subexpression$1", symbols: [ /[cC]/, /[hH]/, /[aA]/, /[rR]/, /[aA]/, /[cC]/, /[tT]/, /[eE]/, /[rR]/, ], postprocess(d) { return d.join(""); }, }, { name: "character_set$subexpression$2", symbols: [/[sS]/, /[eE]/, /[tT]/], postprocess(d) { return d.join(""); }, }, { name: "character_set", symbols: [ "character_set$subexpression$1", "__", "character_set$subexpression$2", "_", ], }, { name: "collate$subexpression$1", symbols: [/[cC]/, /[oO]/, /[lL]/, /[lL]/, /[aA]/, /[tT]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "collate", symbols: ["collate$subexpression$1", "__"] }, { name: "encryption$subexpression$1", symbols: [ /[eE]/, /[nN]/, /[cC]/, /[rR]/, /[yY]/, /[pP]/, /[tT]/, /[iI]/, /[oO]/, /[nN]/, ], postprocess(d) { return d.join(""); }, }, { name: "encryption", symbols: ["encryption$subexpression$1", "__"] }, { name: "character_set_choice$subexpression$1", symbols: [] }, { name: "character_set_choice$subexpression$1", symbols: ["default"] }, { name: "character_set_choice$subexpression$2", symbols: [] }, { name: "character_set_choice$subexpression$2", symbols: ["equals"] }, { name: "character_set_choice", symbols: [ "character_set_choice$subexpression$1", "character_set", "character_set_choice$subexpression$2", "name", ], }, { name: "collate_choice$subexpression$1", symbols: [] }, { name: "collate_choice$subexpression$1", symbols: ["default"] }, { name: "collate_choice$subexpression$2", symbols: [] }, { name: "collate_choice$subexpression$2", symbols: ["equals"] }, { name: "collate_choice", symbols: [ "collate_choice$subexpression$1", "collate", "collate_choice$subexpression$2", "name", ], }, { name: "encryption_choice$subexpression$1", symbols: [] }, { name: "encryption_choice$subexpression$1", symbols: ["default"] }, { name: "encryption_choice$subexpression$2", symbols: [] }, { name: "encryption_choice$subexpression$2", symbols: ["equals"] }, { name: "encryption_choice", symbols: [ "encryption_choice$subexpression$1", "encryption", "encryption_choice$subexpression$2", "yes_or_no", ], }, { name: "option_create_option", symbols: [] }, { name: "option_create_option$subexpression$1", symbols: ["character_set_choice"], }, { name: "option_create_option$subexpression$1", symbols: ["collate_choice"], }, { name: "option_create_option$subexpression$1", symbols: ["encryption_choice"], }, { name: "option_create_option", symbols: ["option_create_option$subexpression$1"], }, { name: "clause_algorithm$string$1", symbols: [ { literal: "U" }, { literal: "N" }, { literal: "D" }, { literal: "E" }, { literal: "F" }, { literal: "I" }, { literal: "N" }, { literal: "E" }, { literal: "D" }, ], postprocess: (d) => d.join(""), }, { name: "clause_algorithm", symbols: ["clause_algorithm$string$1"] }, { name: "clause_algorithm$string$2", symbols: [ { literal: "M" }, { literal: "E" }, { literal: "R" }, { literal: "G" }, { literal: "E" }, ], postprocess: (d) => d.join(""), }, { name: "clause_algorithm", symbols: ["clause_algorithm$string$2"] }, { name: "clause_algorithm$string$3", symbols: [ { literal: "T" }, { literal: "E" }, { literal: "M" }, { literal: "P" }, { literal: "T" }, { literal: "A" }, { literal: "B" }, { literal: "L" }, { literal: "E" }, ], postprocess: (d) => d.join(""), }, { name: "clause_algorithm", symbols: ["clause_algorithm$string$3"] }, { name: "clause_algorithm", symbols: [] }, { name: "clause_definer$string$1", symbols: [ { literal: "u" }, { literal: "s" }, { literal: "e" }, { literal: "r" }, ], postprocess: (d) => d.join(""), }, { name: "clause_definer", symbols: ["clause_definer$string$1"] }, { name: "clause_definer", symbols: [] }, { name: "clause_index$string$1", symbols: [ { literal: "U" }, { literal: "N" }, { literal: "I" }, { literal: "Q" }, { literal: "U" }, { literal: "E" }, ], postprocess: (d) => d.join(""), }, { name: "clause_index", symbols: ["clause_index$string$1"] }, { name: "clause_index$string$2", symbols: [ { literal: "F" }, { literal: "U" }, { literal: "L" }, { literal: "L" }, { literal: "T" }, { literal: "E" }, { literal: "X" }, { literal: "T" }, ], postprocess: (d) => d.join(""), }, { name: "clause_index", symbols: ["clause_index$string$2"] }, { name: "clause_index$string$3", symbols: [ { literal: "S" }, { literal: "P" }, { literal: "A" }, { literal: "T" }, { literal: "I" }, { literal: "A" }, { literal: "L" }, ], postprocess: (d) => d.join(""), }, { name: "clause_index", symbols: ["clause_index$string$3"] }, { name: "clause_index", symbols: [] }, { name: "clause_index_type$string$1", symbols: [ { literal: "U" }, { literal: "S" }, { literal: "I" }, { literal: "N" }, { literal: "G" }, { literal: " " }, { literal: "B" }, { literal: "T" }, { literal: "R" }, { literal: "E" }, { literal: "E" }, ], postprocess: (d) => d.join(""), }, { name: "clause_index_type", symbols: ["clause_index_type$string$1"] }, { name: "clause_index_type$string$2", symbols: [ { literal: "U" }, { literal: "S" }, { literal: "I" }, { literal: "N" }, { literal: "G" }, { literal: " " }, { literal: "H" }, { literal: "A" }, { literal: "S" }, { literal: "H" }, ], postprocess: (d) => d.join(""), }, { name: "clause_index_type", symbols: ["clause_index_type$string$2"] }, { name: "clause_index_type", symbols: [] }, { name: "clause_or_replace", symbols: [] }, { name: "clause_or_replace$string$1", symbols: [ { literal: "O" }, { literal: "R" }, { literal: " " }, { literal: "R" }, { literal: "E" }, { literal: "P" }, { literal: "L" }, { literal: "A" }, { literal: "C" }, { literal: "E" }, ], postprocess: (d) => d.join(""), }, { name: "clause_or_replace", symbols: ["clause_or_replace$string$1", "__"], }, { name: "clause_view$string$1", symbols: [ { literal: "V" }, { literal: "I" }, { literal: "E" }, { literal: "W" }, ], postprocess: (d) => d.join(""), }, { name: "clause_view$ebnf$1", symbols: [/[A-z]/] }, { name: "clause_view$ebnf$1", symbols: ["clause_view$ebnf$1", /[A-z]/], postprocess: (d) => d[0].concat([d[1]]), }, { name: "clause_view", symbols: ["clause_view$string$1", "clause_view$ebnf$1"], }, ], ParserStart: "statement", }; export default grammar;
the_stack
import { getLatestSnapshot } from '@/core/contextmenu/export.menu'; import { createSnapshot } from '@/core/file'; import { Bus } from '@/core/helper/eventBus.helper'; import { Constraints, Dialect, Operation, ParserCallback, translate, } from '@/core/parser/helper'; import { Column, IndexColumn, Statement } from '@/core/parser/index'; import { createJson } from '@/core/parser/ParserToJson'; import { zoomCanvas } from '@/engine/command/canvas.cmd.helper'; import { initLoadJson$ } from '@/engine/command/editor.cmd.helper.gen'; import { IERDEditorContext } from '@/internal-types/ERDEditorContext'; import { LiquibaseFile } from '@@types/core/liquibaseParser'; const dialectTo: Dialect = 'postgresql'; const defaultDialect: Dialect = 'postgresql'; /** * Parser for Liquibase XML file * @param input Entire XML file * @param dialect Dialect that the result will have datataypes in * @returns List of Statements to execute */ export const LiquibaseParser = ( context: IERDEditorContext, files: LiquibaseFile[], dialect: Dialect = defaultDialect, rootFile?: LiquibaseFile ) => { const { store, eventBus, helper } = context; const zoom = JSON.parse(JSON.stringify(store.canvasState.zoomLevel)); store.dispatchSync(zoomCanvas(0.7)); store.canvasState.zoomLevel = 0.7; createSnapshot(context, { filename: rootFile?.path || '', type: rootFile?.path ? 'before-import' : 'user', }); setTimeout(async () => { async function parseFile(file: LiquibaseFile) { eventBus.emit(Bus.Liquibase.progress, file.path); // workaround so code is non-blocking await new Promise(resolve => setTimeout(resolve, 0)); var parser = new DOMParser(); var xmlDoc = parser.parseFromString(file.value, 'text/xml'); const databaseChangeLog = xmlDoc.querySelector('databaseChangeLog'); if (!databaseChangeLog) return; console.log(file.path, databaseChangeLog.children); for (const element of databaseChangeLog.children) { if (element.tagName === 'changeSet') { handleChangeSetParsing(element, file); } else if (element.tagName === 'include') { await handleImportParsing(element, file); } } } async function handleImportParsing(include: Element, file: LiquibaseFile) { const fileName = include.getAttribute('file'); var myDirectory = file.path.split('/').slice(0, -1).join('/'); if (myDirectory) myDirectory += '/'; const dstDirectory = `${myDirectory}${fileName}`; const dstFile = files.find(file => file.path === dstDirectory); if (dstFile) await parseFile(dstFile); } function handleChangeSetParsing(element: Element, file: LiquibaseFile) { const dbms: string = element.getAttribute('dbms') || ''; if (dbms === '' || dbms == dialect) { var statements: Statement[] = []; if (parseChangeSet(element, statements, dialect)) { createSnapshot(context, { filename: file.path, type: 'before-import', statements: statements, }); applyStatements(context, statements); } } } if (rootFile) { await parseFile(rootFile); } else { for (const file of files) { await parseFile(file); } } eventBus.emit(Bus.Liquibase.progressEnd); setTimeout(async () => { store.dispatchSync(zoomCanvas(zoom)); createSnapshot(context, { filename: rootFile?.path || '', type: 'after-import', }); console.log('SNAPSHOTS', context.snapshots); }, 0); }, 10); }; export const applyStatements = ( context: IERDEditorContext, statements: Statement[] ) => { var { store, helper } = context; const json = createJson( statements, helper, store.canvasState.database, getLatestSnapshot(context).data ); store.dispatchSync(initLoadJson$(json)); }; export const parseChangeSet = ( changeSet: Element, statements: Statement[], dialect: Dialect ): boolean => { if (!checkPreConditions(changeSet, dialect)) return false; function parse(operation: Operation) { parseElement(operation, changeSet, statements, parsers[operation], dialect); } parse('createTable'); parse('createIndex'); parse('addForeignKeyConstraint'); parse('addPrimaryKey'); parse('addColumn'); parse('dropColumn'); parse('dropTable'); parse('dropForeignKeyConstraint'); parse('addUniqueConstraint'); return true; }; export const checkPreConditions = ( changeSet: Element, dialect: Dialect ): boolean => { const preConditions = changeSet.getElementsByTagName('preConditions')[0]; if (!preConditions) return true; const preConditionsOr = preConditions.getElementsByTagName('or')[0]; var preConditionsDbms: HTMLCollectionOf<Element>; if (preConditionsOr) { preConditionsDbms = preConditionsOr.getElementsByTagName('dbms'); } else { preConditionsDbms = preConditions.getElementsByTagName('dbms'); } for (const dbms of preConditionsDbms) { if (dbms.getAttribute('type') === dialect) { return true; } } return false; }; export const parseElement = ( type: Operation, element: Element, statements: Statement[], parser: ParserCallback, dialect?: Dialect ) => { const elements = element.getElementsByTagName(type); for (let i = 0; i < elements.length; i++) { parser(elements[i], statements, dialect); } }; export const parseCreateTable = ( createTable: Element, statements: Statement[], dialect: Dialect = defaultDialect ) => { var columns: Column[] = parseColumns(createTable, dialect); statements.push({ type: 'create.table', name: createTable.getAttribute('tableName') || '', comment: createTable.getAttribute('remarks') || '', columns: columns, indexes: [], foreignKeys: [], }); }; const parseColumns = (element: Element, dialect: Dialect): Column[] => { var columns: Column[] = []; const cols = element.getElementsByTagName('column'); for (let i = 0; i < cols.length; i++) { columns.push(parseSingleColumn(cols[i], dialect)); } return columns; }; export const parseSingleColumn = ( column: Element, dialect: Dialect ): Column => { const constr = column.getElementsByTagName('constraints')[0]; var constraints: Constraints; if (constr) { constraints = { primaryKey: constr.getAttribute('primaryKey') === 'true', nullable: !(constr.getAttribute('nullable') === 'true'), unique: constr.getAttribute('unique') === 'true', }; } else { constraints = { primaryKey: false, nullable: true, unique: false, }; } var dataType = translate( dialect, dialectTo, column.getAttribute('type') || '' ); return { name: column.getAttribute('name') || '', dataType: dataType, default: column.getAttribute('defaultValue') || '', comment: column.getAttribute('remarks') || '', primaryKey: constraints.primaryKey, autoIncrement: column.getAttribute('autoIncrement') === 'true', unique: constraints.unique, nullable: constraints.nullable, }; }; export const parseSingleIndexColumn = (column: Element): IndexColumn => { return { name: column.getAttribute('name') || '', sort: column.getAttribute('descending') ? 'DESC' : 'ASC', }; }; export const parseCreateIndex = ( createIndex: Element, statements: Statement[] ) => { var indexColumns: IndexColumn[] = []; const cols = createIndex.getElementsByTagName('column'); for (let i = 0; i < cols.length; i++) { indexColumns.push(parseSingleIndexColumn(cols[i])); } statements.push({ type: 'create.index', name: createIndex.getAttribute('indexName') || '', unique: createIndex.getAttribute('unique') === 'true', tableName: createIndex.getAttribute('tableName') || '', columns: indexColumns, }); }; export const parseAddForeignKeyConstraint = ( addForeignKey: Element, statements: Statement[] ) => { var refColumnNames: string[] = addForeignKey .getAttribute('referencedColumnNames') ?.split(',') .map(item => item.trim()) || []; var columnNames: string[] = addForeignKey .getAttribute('baseColumnNames') ?.split(',') .map(item => item.trim()) || []; statements.push({ type: 'alter.table.add.foreignKey', name: addForeignKey.getAttribute('baseTableName') || '', columnNames: columnNames, refTableName: addForeignKey.getAttribute('referencedTableName') || '', refColumnNames: refColumnNames, constraintName: addForeignKey.getAttribute('constraintName') || '', }); }; export const parseAddPrimaryKey = ( addPrimaryKey: Element, statements: Statement[] ) => { var columnNames: string[] = addPrimaryKey .getAttribute('columnNames') ?.split(',') .map(item => item.trim()) || []; statements.push({ type: 'alter.table.add.primaryKey', name: addPrimaryKey.getAttribute('tableName') || '', columnNames: columnNames, }); }; export const parseAddColumn = ( addColumn: Element, statements: Statement[], dialect: Dialect = defaultDialect ) => { const tableName: string = addColumn.getAttribute('tableName') || ''; statements.push({ type: 'alter.table.add.column', name: tableName, columns: parseColumns(addColumn, dialect), }); }; export const parseDropColumn = ( dropColumn: Element, statements: Statement[], dialect: Dialect = defaultDialect ) => { const tableName: string = dropColumn.getAttribute('tableName') || ''; const column: Column = { name: dropColumn.getAttribute('columnName') || '', dataType: '', default: '', comment: '', primaryKey: false, autoIncrement: false, unique: false, nullable: false, }; statements.push({ type: 'alter.table.drop.column', name: tableName, columns: [column, ...parseColumns(dropColumn, dialect)], }); }; export const parseDropTable = (dropTable: Element, statements: Statement[]) => { const tableName: string = dropTable.getAttribute('tableName') || ''; statements.push({ type: 'drop.table', name: tableName, }); }; export const parseDropForeignKeyConstraint = ( dropFk: Element, statements: Statement[] ) => { statements.push({ type: 'alter.table.drop.foreignKey', name: dropFk.getAttribute('constraintName') || '', baseTableName: dropFk.getAttribute('baseTableName') || '', }); }; export const parseAddUniqueConstraint = ( addUniqueConstraint: Element, statements: Statement[] ) => { const columnNames = addUniqueConstraint.getAttribute('columnNames'); if (!columnNames) return; const columns: string[] = columnNames.split(',').map(col => col.trim()); statements.push({ type: 'alter.table.add.unique', name: addUniqueConstraint.getAttribute('tableName') || '', columnNames: columns, }); }; export const parsers: Record<Operation, ParserCallback> = { createTable: parseCreateTable, createIndex: parseCreateIndex, addForeignKeyConstraint: parseAddForeignKeyConstraint, addPrimaryKey: parseAddPrimaryKey, addColumn: parseAddColumn, dropColumn: parseDropColumn, dropTable: parseDropTable, dropForeignKeyConstraint: parseDropForeignKeyConstraint, addUniqueConstraint: parseAddUniqueConstraint, };
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormOpportunity_AI_for_Sales { interface Header extends DevKit.Controls.IHeader { /** Enter the expected closing date of the opportunity to help make accurate revenue forecasts. */ EstimatedCloseDate: DevKit.Controls.Date; /** Type the estimated revenue amount to indicate the potential sale or value of the opportunity for revenue forecasting. This field can be either system-populated or editable based on the selection in the Revenue field. */ EstimatedValue: DevKit.Controls.Money; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select the opportunity's status. */ StatusCode: DevKit.Controls.OptionSet; } interface tab_Product_Line_Items_Sections { DynamicProperties: DevKit.Controls.Section; opportunityproducts: DevKit.Controls.Section; suggestionsection: DevKit.Controls.Section; totals: DevKit.Controls.Section; } interface tab_QUOTES_Sections { opportunityquotes: DevKit.Controls.Section; } interface tab_Summary_Sections { Notes_pane: DevKit.Controls.Section; Opportunity_details: DevKit.Controls.Section; opportunity_information: DevKit.Controls.Section; Social_pane: DevKit.Controls.Section; Summary_section_6: DevKit.Controls.Section; } interface tab_Product_Line_Items extends DevKit.Controls.ITab { Section: tab_Product_Line_Items_Sections; } interface tab_QUOTES extends DevKit.Controls.ITab { Section: tab_QUOTES_Sections; } interface tab_Summary extends DevKit.Controls.ITab { Section: tab_Summary_Sections; } interface Tabs { Product_Line_Items: tab_Product_Line_Items; QUOTES: tab_QUOTES; Summary: tab_Summary; } interface Body { Tab: Tabs; ActionCards: DevKit.Controls.ActionCards; /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.Controls.Money; /** Type notes about the company or organization associated with the opportunity. */ CurrentSituation: DevKit.Controls.String; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.Controls.String; /** Type additional information to describe the opportunity, such as possible products to sell or past purchases from the customer. */ Description: DevKit.Controls.String; /** Type the discount amount for the opportunity if the customer is eligible for special savings. */ DiscountAmount: DevKit.Controls.Money; /** Type the discount rate that should be applied to the Product Totals field to include additional savings for the customer in the opportunity. */ DiscountPercentage: DevKit.Controls.Decimal; /** Type the cost of freight or shipping for the products included in the opportunity for use in calculating the Total Amount field. */ FreightAmount: DevKit.Controls.Money; /** Select whether the estimated revenue for the opportunity is calculated automatically based on the products entered or entered manually by a user. */ IsRevenueSystemCalculated: DevKit.Controls.Boolean; /** Internal use only. */ msdyn_OrderType: DevKit.Controls.OptionSet; /** Type a subject or descriptive name, such as the expected order or company name, for the opportunity. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.Controls.Lookup; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.Controls.Lookup; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.Controls.Lookup; /** Type notes about the proposed solution for the opportunity. */ ProposedSolution: DevKit.Controls.String; /** Choose whether an individual or a committee will be involved in the purchase process for the lead. */ PurchaseProcess: DevKit.Controls.OptionSet; /** Choose how long the lead will likely take to make the purchase. */ PurchaseTimeframe: DevKit.Controls.OptionSet; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the opportunity. */ TotalAmount: DevKit.Controls.Money; /** Shows the total product amount for the opportunity, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount of the opportunity. */ TotalAmountLessFreight: DevKit.Controls.Money; /** Shows the sum of all existing and write-in products included on the opportunity, based on the specified price list and quantities. */ TotalLineItemAmount: DevKit.Controls.Money; /** Shows the total of the Tax amounts specified on all products included in the opportunity, included in the Total Amount field calculation for the opportunity. */ TotalTax: DevKit.Controls.Money; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { navActivities: DevKit.Controls.NavigationItem, navAsyncOperations: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navComp: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navInvoices: DevKit.Controls.NavigationItem, navOrders: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem, navRelationship: DevKit.Controls.NavigationItem } interface ProcessOpportunity_Sales_Process { /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.Controls.Money; /** Select whether a final proposal has been completed for the opportunity. */ CompleteFinalProposal: DevKit.Controls.Boolean; /** Select whether an internal review has been completed for this opportunity. */ CompleteInternalReview: DevKit.Controls.Boolean; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.Controls.String; /** Select whether your notes include information about who makes the purchase decisions at the lead's company. */ DecisionMaker: DevKit.Controls.Boolean; /** Type additional information to describe the opportunity, such as possible products to sell or past purchases from the customer. */ Description: DevKit.Controls.String; /** Select whether a proposal has been developed for the opportunity. */ DevelopProposal: DevKit.Controls.Boolean; /** Choose whether the sales team has recorded detailed notes on the proposals and the account's responses. */ FileDebrief: DevKit.Controls.Boolean; /** Enter the date and time when the final decision of the opportunity was made. */ FinalDecisionDate: DevKit.Controls.Date; /** Select whether information about competitors is included. */ IdentifyCompetitors: DevKit.Controls.Boolean; /** Select whether the customer contacts for this opportunity have been identified. */ IdentifyCustomerContacts: DevKit.Controls.Boolean; /** Choose whether you have recorded who will pursue the opportunity. */ IdentifyPursuitTeam: DevKit.Controls.Boolean; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.Controls.Lookup; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.Controls.Lookup; /** Select whether the final proposal has been presented to the account. */ PresentFinalProposal: DevKit.Controls.Boolean; /** Select whether a proposal for the opportunity has been presented to the account. */ PresentProposal: DevKit.Controls.Boolean; /** Type notes about the proposed solution for the opportunity. */ ProposedSolution: DevKit.Controls.String; /** Choose whether an individual or a committee will be involved in the purchase process for the lead. */ PurchaseProcess: DevKit.Controls.OptionSet; /** Choose how long the lead will likely take to make the purchase. */ PurchaseTimeframe: DevKit.Controls.OptionSet; /** Select whether a thank you note has been sent to the account for considering the proposal. */ SendThankYouNote: DevKit.Controls.Boolean; } interface Process extends DevKit.Controls.IProcess { Opportunity_Sales_Process: ProcessOpportunity_Sales_Process; } interface Grid { Stakeholders: DevKit.Controls.Grid; Pursuit_Team: DevKit.Controls.Grid; Competitors: DevKit.Controls.Grid; opportunityproductsGrid: DevKit.Controls.Grid; quote: DevKit.Controls.Grid; } } class FormOpportunity_AI_for_Sales extends DevKit.IForm { /** * DynamicsCrm.DevKit form Opportunity_AI_for_Sales * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Opportunity_AI_for_Sales */ Body: DevKit.FormOpportunity_AI_for_Sales.Body; /** The Header section of form Opportunity_AI_for_Sales */ Header: DevKit.FormOpportunity_AI_for_Sales.Header; /** The Navigation of form Opportunity_AI_for_Sales */ Navigation: DevKit.FormOpportunity_AI_for_Sales.Navigation; /** The Process of form Opportunity_AI_for_Sales */ Process: DevKit.FormOpportunity_AI_for_Sales.Process; /** The Grid of form Opportunity_AI_for_Sales */ Grid: DevKit.FormOpportunity_AI_for_Sales.Grid; } namespace FormOpportunity_Field_Service_Information { interface Header extends DevKit.Controls.IHeader { /** Enter the expected closing date of the opportunity to help make accurate revenue forecasts. */ EstimatedCloseDate: DevKit.Controls.Date; /** Type the estimated revenue amount to indicate the potential sale or value of the opportunity for revenue forecasting. This field can be either system-populated or editable based on the selection in the Revenue field. */ EstimatedValue: DevKit.Controls.Money; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select the opportunity's status. */ StatusCode: DevKit.Controls.OptionSet; } interface tab_opportunity_line_items_Sections { opportunityproducts: DevKit.Controls.Section; ServiceMaintenanceLines: DevKit.Controls.Section; totals: DevKit.Controls.Section; } interface tab_QUOTES_Sections { opportunityquotes: DevKit.Controls.Section; QUOTES_section_2: DevKit.Controls.Section; } interface tab_Summary_Sections { Notes_pane: DevKit.Controls.Section; Opportunity_details: DevKit.Controls.Section; opportunity_information: DevKit.Controls.Section; Social_pane: DevKit.Controls.Section; } interface tab_tab_4_Sections { tab_4_section_2: DevKit.Controls.Section; } interface tab_opportunity_line_items extends DevKit.Controls.ITab { Section: tab_opportunity_line_items_Sections; } interface tab_QUOTES extends DevKit.Controls.ITab { Section: tab_QUOTES_Sections; } interface tab_Summary extends DevKit.Controls.ITab { Section: tab_Summary_Sections; } interface tab_tab_4 extends DevKit.Controls.ITab { Section: tab_tab_4_Sections; } interface Tabs { opportunity_line_items: tab_opportunity_line_items; QUOTES: tab_QUOTES; Summary: tab_Summary; tab_4: tab_tab_4; } interface Body { Tab: Tabs; /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.Controls.Money; /** Type a number from 0 to 100 that represents the likelihood of closing the opportunity. This can aid the sales team in their efforts to convert the opportunity in a sale. */ CloseProbability: DevKit.Controls.Integer; /** Type notes about the company or organization associated with the opportunity. */ CurrentSituation: DevKit.Controls.String; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.Controls.String; /** Type additional information to describe the opportunity, such as possible products to sell or past purchases from the customer. */ Description: DevKit.Controls.String; /** Type the discount amount for the opportunity if the customer is eligible for special savings. */ DiscountAmount: DevKit.Controls.Money; /** Type the discount rate that should be applied to the Product Totals field to include additional savings for the customer in the opportunity. */ DiscountPercentage: DevKit.Controls.Decimal; /** Type the cost of freight or shipping for the products included in the opportunity for use in calculating the Total Amount field. */ FreightAmount: DevKit.Controls.Money; /** Select whether the estimated revenue for the opportunity is calculated automatically based on the products entered or entered manually by a user. */ IsRevenueSystemCalculated: DevKit.Controls.Boolean; /** Internal use only. */ msdyn_OrderType: DevKit.Controls.OptionSet; /** Unique identifier for Work Order Type associated with Opportunity. */ msdyn_WorkOrderType: DevKit.Controls.Lookup; /** Type a subject or descriptive name, such as the expected order or company name, for the opportunity. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Select the expected value or priority of the opportunity based on revenue, customer status, or closing probability. */ OpportunityRatingCode: DevKit.Controls.OptionSet; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.Controls.Lookup; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.Controls.Lookup; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.Controls.Lookup; /** Type notes about the proposed solution for the opportunity. */ ProposedSolution: DevKit.Controls.String; /** Choose whether an individual or a committee will be involved in the purchase process for the lead. */ PurchaseProcess: DevKit.Controls.OptionSet; /** Choose how long the lead will likely take to make the purchase. */ PurchaseTimeframe: DevKit.Controls.OptionSet; /** Select the sales process stage for the opportunity to indicate the probability of closing the opportunity. */ SalesStageCode: DevKit.Controls.OptionSet; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the opportunity. */ TotalAmount: DevKit.Controls.Money; /** Shows the total product amount for the opportunity, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount of the opportunity. */ TotalAmountLessFreight: DevKit.Controls.Money; /** Shows the sum of all existing and write-in products included on the opportunity, based on the specified price list and quantities. */ TotalLineItemAmount: DevKit.Controls.Money; /** Shows the total of the Tax amounts specified on all products included in the opportunity, included in the Total Amount field calculation for the opportunity. */ TotalTax: DevKit.Controls.Money; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_opportunity_msdyn_workorder: DevKit.Controls.NavigationItem, navActivities: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navComp: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navInvoices: DevKit.Controls.NavigationItem, navOrders: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem, navRelationship: DevKit.Controls.NavigationItem } interface ProcessOpportunity_Sales_Process { /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.Controls.Money; /** Select whether a final proposal has been completed for the opportunity. */ CompleteFinalProposal: DevKit.Controls.Boolean; /** Select whether an internal review has been completed for this opportunity. */ CompleteInternalReview: DevKit.Controls.Boolean; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.Controls.String; /** Select whether your notes include information about who makes the purchase decisions at the lead's company. */ DecisionMaker: DevKit.Controls.Boolean; /** Type additional information to describe the opportunity, such as possible products to sell or past purchases from the customer. */ Description: DevKit.Controls.String; /** Select whether a proposal has been developed for the opportunity. */ DevelopProposal: DevKit.Controls.Boolean; /** Choose whether the sales team has recorded detailed notes on the proposals and the account's responses. */ FileDebrief: DevKit.Controls.Boolean; /** Enter the date and time when the final decision of the opportunity was made. */ FinalDecisionDate: DevKit.Controls.Date; /** Select whether information about competitors is included. */ IdentifyCompetitors: DevKit.Controls.Boolean; /** Select whether the customer contacts for this opportunity have been identified. */ IdentifyCustomerContacts: DevKit.Controls.Boolean; /** Choose whether you have recorded who will pursue the opportunity. */ IdentifyPursuitTeam: DevKit.Controls.Boolean; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.Controls.Lookup; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.Controls.Lookup; /** Select whether the final proposal has been presented to the account. */ PresentFinalProposal: DevKit.Controls.Boolean; /** Select whether a proposal for the opportunity has been presented to the account. */ PresentProposal: DevKit.Controls.Boolean; /** Type notes about the proposed solution for the opportunity. */ ProposedSolution: DevKit.Controls.String; /** Choose whether an individual or a committee will be involved in the purchase process for the lead. */ PurchaseProcess: DevKit.Controls.OptionSet; /** Choose how long the lead will likely take to make the purchase. */ PurchaseTimeframe: DevKit.Controls.OptionSet; /** Select whether a thank you note has been sent to the account for considering the proposal. */ SendThankYouNote: DevKit.Controls.Boolean; } interface Process extends DevKit.Controls.IProcess { Opportunity_Sales_Process: ProcessOpportunity_Sales_Process; } interface Grid { Stakeholders: DevKit.Controls.Grid; Pursuit_Team: DevKit.Controls.Grid; Competitors: DevKit.Controls.Grid; opportunityproductsGrid: DevKit.Controls.Grid; OpportunityServicesGrid: DevKit.Controls.Grid; quote: DevKit.Controls.Grid; } } class FormOpportunity_Field_Service_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Opportunity_Field_Service_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Opportunity_Field_Service_Information */ Body: DevKit.FormOpportunity_Field_Service_Information.Body; /** The Header section of form Opportunity_Field_Service_Information */ Header: DevKit.FormOpportunity_Field_Service_Information.Header; /** The Navigation of form Opportunity_Field_Service_Information */ Navigation: DevKit.FormOpportunity_Field_Service_Information.Navigation; /** The Process of form Opportunity_Field_Service_Information */ Process: DevKit.FormOpportunity_Field_Service_Information.Process; /** The Grid of form Opportunity_Field_Service_Information */ Grid: DevKit.FormOpportunity_Field_Service_Information.Grid; } namespace FormOpportunity_Project_Information { interface Header extends DevKit.Controls.IHeader { /** Enter the expected closing date of the opportunity to help make accurate revenue forecasts. */ EstimatedCloseDate: DevKit.Controls.Date; /** Type the estimated revenue amount to indicate the potential sale or value of the opportunity for revenue forecasting. This field can be either system-populated or editable based on the selection in the Revenue field. */ EstimatedValue: DevKit.Controls.Money; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select the opportunity's status. */ StatusCode: DevKit.Controls.OptionSet; } interface tab_OpportunityLinesTab_Sections { OpportunityLinesSection: DevKit.Controls.Section; OpportunityLinesTab_section_3: DevKit.Controls.Section; totals: DevKit.Controls.Section; } interface tab_Product_Line_Items_Sections { DynamicProperties: DevKit.Controls.Section; opportunityproducts: DevKit.Controls.Section; suggestionsection: DevKit.Controls.Section; } interface tab_QUOTES_Sections { opportunityquotes: DevKit.Controls.Section; } interface tab_Summary_Sections { Notes_pane: DevKit.Controls.Section; Opportunity_details: DevKit.Controls.Section; opportunity_information: DevKit.Controls.Section; Social_pane: DevKit.Controls.Section; } interface tab_OpportunityLinesTab extends DevKit.Controls.ITab { Section: tab_OpportunityLinesTab_Sections; } interface tab_Product_Line_Items extends DevKit.Controls.ITab { Section: tab_Product_Line_Items_Sections; } interface tab_QUOTES extends DevKit.Controls.ITab { Section: tab_QUOTES_Sections; } interface tab_Summary extends DevKit.Controls.ITab { Section: tab_Summary_Sections; } interface Tabs { OpportunityLinesTab: tab_OpportunityLinesTab; Product_Line_Items: tab_Product_Line_Items; QUOTES: tab_QUOTES; Summary: tab_Summary; } interface Body { Tab: Tabs; /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.Controls.Money; /** Type a number from 0 to 100 that represents the likelihood of closing the opportunity. This can aid the sales team in their efforts to convert the opportunity in a sale. */ CloseProbability: DevKit.Controls.Integer; /** Type notes about the company or organization associated with the opportunity. */ CurrentSituation: DevKit.Controls.String; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.Controls.String; /** Type additional information to describe the opportunity, such as possible products to sell or past purchases from the customer. */ Description: DevKit.Controls.String; /** Type the discount amount for the opportunity if the customer is eligible for special savings. */ DiscountAmount: DevKit.Controls.Money; /** Type the discount rate that should be applied to the Product Totals field to include additional savings for the customer in the opportunity. */ DiscountPercentage: DevKit.Controls.Decimal; /** Type the cost of freight or shipping for the products included in the opportunity for use in calculating the Total Amount field. */ FreightAmount: DevKit.Controls.Money; /** Select whether the estimated revenue for the opportunity is calculated automatically based on the products entered or entered manually by a user. */ IsRevenueSystemCalculated: DevKit.Controls.Boolean; /** The account manager responsible for the opportunity. */ msdyn_AccountManagerId: DevKit.Controls.Lookup; /** The organizational unit in charge of the opportunity. */ msdyn_ContractOrganizationalUnitId: DevKit.Controls.Lookup; /** Internal use only. */ msdyn_OrderType: DevKit.Controls.OptionSet; /** Type a subject or descriptive name, such as the expected order or company name, for the opportunity. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Select the expected value or priority of the opportunity based on revenue, customer status, or closing probability. */ OpportunityRatingCode: DevKit.Controls.OptionSet; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.Controls.Lookup; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.Controls.Lookup; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.Controls.Lookup; /** Type notes about the proposed solution for the opportunity. */ ProposedSolution: DevKit.Controls.String; /** Choose whether an individual or a committee will be involved in the purchase process for the lead. */ PurchaseProcess: DevKit.Controls.OptionSet; /** Choose how long the lead will likely take to make the purchase. */ PurchaseTimeframe: DevKit.Controls.OptionSet; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the opportunity. */ TotalAmount: DevKit.Controls.Money; /** Shows the total product amount for the opportunity, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount of the opportunity. */ TotalAmountLessFreight: DevKit.Controls.Money; /** Shows the sum of all existing and write-in products included on the opportunity, based on the specified price list and quantities. */ TotalLineItemAmount: DevKit.Controls.Money; /** Shows the total of the Tax amounts specified on all products included in the opportunity, included in the Total Amount field calculation for the opportunity. */ TotalTax: DevKit.Controls.Money; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_opportunity_msdyn_opportunitypricelist_Opportunity: DevKit.Controls.NavigationItem, navActivities: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navComp: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navInvoices: DevKit.Controls.NavigationItem, navOrders: DevKit.Controls.NavigationItem, navProducts: DevKit.Controls.NavigationItem, navRelationship: DevKit.Controls.NavigationItem } interface ProcessOpportunity_Sales_Process { /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.Controls.Money; /** Select whether a final proposal has been completed for the opportunity. */ CompleteFinalProposal: DevKit.Controls.Boolean; /** Select whether an internal review has been completed for this opportunity. */ CompleteInternalReview: DevKit.Controls.Boolean; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.Controls.String; /** Select whether your notes include information about who makes the purchase decisions at the lead's company. */ DecisionMaker: DevKit.Controls.Boolean; /** Type additional information to describe the opportunity, such as possible products to sell or past purchases from the customer. */ Description: DevKit.Controls.String; /** Select whether a proposal has been developed for the opportunity. */ DevelopProposal: DevKit.Controls.Boolean; /** Choose whether the sales team has recorded detailed notes on the proposals and the account's responses. */ FileDebrief: DevKit.Controls.Boolean; /** Enter the date and time when the final decision of the opportunity was made. */ FinalDecisionDate: DevKit.Controls.Date; /** Select whether information about competitors is included. */ IdentifyCompetitors: DevKit.Controls.Boolean; /** Select whether the customer contacts for this opportunity have been identified. */ IdentifyCustomerContacts: DevKit.Controls.Boolean; /** Choose whether you have recorded who will pursue the opportunity. */ IdentifyPursuitTeam: DevKit.Controls.Boolean; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.Controls.Lookup; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.Controls.Lookup; /** Select whether the final proposal has been presented to the account. */ PresentFinalProposal: DevKit.Controls.Boolean; /** Select whether a proposal for the opportunity has been presented to the account. */ PresentProposal: DevKit.Controls.Boolean; /** Type notes about the proposed solution for the opportunity. */ ProposedSolution: DevKit.Controls.String; /** Choose whether an individual or a committee will be involved in the purchase process for the lead. */ PurchaseProcess: DevKit.Controls.OptionSet; /** Choose how long the lead will likely take to make the purchase. */ PurchaseTimeframe: DevKit.Controls.OptionSet; /** Select whether a thank you note has been sent to the account for considering the proposal. */ SendThankYouNote: DevKit.Controls.Boolean; } interface Process extends DevKit.Controls.IProcess { Opportunity_Sales_Process: ProcessOpportunity_Sales_Process; } interface Grid { Stakeholders: DevKit.Controls.Grid; Pursuit_Team: DevKit.Controls.Grid; Competitors: DevKit.Controls.Grid; ProjectLinesGrid: DevKit.Controls.Grid; opportunityproductsGrid: DevKit.Controls.Grid; quote: DevKit.Controls.Grid; } } class FormOpportunity_Project_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Opportunity_Project_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Opportunity_Project_Information */ Body: DevKit.FormOpportunity_Project_Information.Body; /** The Header section of form Opportunity_Project_Information */ Header: DevKit.FormOpportunity_Project_Information.Header; /** The Navigation of form Opportunity_Project_Information */ Navigation: DevKit.FormOpportunity_Project_Information.Navigation; /** The Process of form Opportunity_Project_Information */ Process: DevKit.FormOpportunity_Project_Information.Process; /** The Grid of form Opportunity_Project_Information */ Grid: DevKit.FormOpportunity_Project_Information.Grid; } namespace FormOpportunity { interface tab_newOpportunity_Sections { quickOpportunity_column1: DevKit.Controls.Section; quickOpportunity_column2: DevKit.Controls.Section; quickOpportunity_column3: DevKit.Controls.Section; } interface tab_newOpportunity extends DevKit.Controls.ITab { Section: tab_newOpportunity_Sections; } interface Tabs { newOpportunity: tab_newOpportunity; } interface Body { Tab: Tabs; /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.Controls.Money; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.Controls.String; /** Enter the expected closing date of the opportunity to help make accurate revenue forecasts. */ EstimatedCloseDate: DevKit.Controls.Date; /** Type the estimated revenue amount to indicate the potential sale or value of the opportunity for revenue forecasting. This field can be either system-populated or editable based on the selection in the Revenue field. */ EstimatedValue: DevKit.Controls.Money; /** The organizational unit in charge of the opportunity. */ msdyn_ContractOrganizationalUnitId: DevKit.Controls.Lookup; /** Internal use only. */ msdyn_OrderType: DevKit.Controls.OptionSet; /** Type a subject or descriptive name, such as the expected order or company name, for the opportunity. */ Name: DevKit.Controls.String; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.Controls.Lookup; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.Controls.Lookup; } } class FormOpportunity extends DevKit.IForm { /** * DynamicsCrm.DevKit form Opportunity * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Opportunity */ Body: DevKit.FormOpportunity.Body; } class OpportunityApi { /** * DynamicsCrm.DevKit OpportunityApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the account with which the opportunity is associated. */ AccountId: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the opportunity was closed or canceled. */ ActualCloseDate_DateOnly: DevKit.WebApi.DateOnlyValue; /** Type the actual revenue amount for the opportunity for reporting and analysis of estimated versus actual sales. Field defaults to the Est. Revenue value when an opportunity is won. */ ActualValue: DevKit.WebApi.MoneyValue; /** Value of the Actual Revenue in base currency. */ ActualValue_Base: DevKit.WebApi.MoneyValueReadonly; /** Type a value between 0 and 1,000,000,000,000 to indicate the lead's potential available budget. */ BudgetAmount: DevKit.WebApi.MoneyValue; /** Value of the Budget Amount in base currency. */ BudgetAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the likely budget status for the lead's company. This may help determine the lead rating or your sales approach. */ BudgetStatus: DevKit.WebApi.OptionSetValue; /** Shows the campaign that the opportunity was created from. The ID is used for tracking the success of the campaign. */ CampaignId: DevKit.WebApi.LookupValue; /** Choose whether the proposal feedback has been captured for the opportunity. */ CaptureProposalFeedback: DevKit.WebApi.BooleanValue; /** Type a number from 0 to 100 that represents the likelihood of closing the opportunity. This can aid the sales team in their efforts to convert the opportunity in a sale. */ CloseProbability: DevKit.WebApi.IntegerValue; /** Select whether a final proposal has been completed for the opportunity. */ CompleteFinalProposal: DevKit.WebApi.BooleanValue; /** Select whether an internal review has been completed for this opportunity. */ CompleteInternalReview: DevKit.WebApi.BooleanValue; /** Select whether the lead confirmed interest in your offerings. This helps in determining the lead quality and the probability of it turning into an opportunity. */ ConfirmInterest: DevKit.WebApi.BooleanValue; /** Unique identifier of the contact associated with the opportunity. */ ContactId: DevKit.WebApi.LookupValueReadonly; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type notes about the company or organization associated with the opportunity. */ CurrentSituation: DevKit.WebApi.StringValue; customerid_account: DevKit.WebApi.LookupValue; customerid_contact: DevKit.WebApi.LookupValue; /** Type some notes about the customer's requirements, to help the sales team identify products and services that could meet their requirements. */ CustomerNeed: DevKit.WebApi.StringValue; /** Type notes about the customer's pain points to help the sales team identify products and services that could address these pain points. */ CustomerPainPoints: DevKit.WebApi.StringValue; /** Select whether your notes include information about who makes the purchase decisions at the lead's company. */ DecisionMaker: DevKit.WebApi.BooleanValue; /** Type additional information to describe the opportunity, such as possible products to sell or past purchases from the customer. */ Description: DevKit.WebApi.StringValue; /** Select whether a proposal has been developed for the opportunity. */ DevelopProposal: DevKit.WebApi.BooleanValue; /** Type the discount amount for the opportunity if the customer is eligible for special savings. */ DiscountAmount: DevKit.WebApi.MoneyValue; /** Value of the Opportunity Discount Amount in base currency. */ DiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Type the discount rate that should be applied to the Product Totals field to include additional savings for the customer in the opportunity. */ DiscountPercentage: DevKit.WebApi.DecimalValue; /** The primary email address for the entity. */ EmailAddress: DevKit.WebApi.StringValue; /** Enter the expected closing date of the opportunity to help make accurate revenue forecasts. */ EstimatedCloseDate_DateOnly: DevKit.WebApi.DateOnlyValue; /** Type the estimated revenue amount to indicate the potential sale or value of the opportunity for revenue forecasting. This field can be either system-populated or editable based on the selection in the Revenue field. */ EstimatedValue: DevKit.WebApi.MoneyValue; /** Value of the Est. Revenue in base currency. */ EstimatedValue_Base: DevKit.WebApi.MoneyValueReadonly; /** Select whether the fit between the lead's requirements and your offerings was evaluated. */ EvaluateFit: DevKit.WebApi.BooleanValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Choose whether the sales team has recorded detailed notes on the proposals and the account's responses. */ FileDebrief: DevKit.WebApi.BooleanValue; /** Enter the date and time when the final decision of the opportunity was made. */ FinalDecisionDate_DateOnly: DevKit.WebApi.DateOnlyValue; /** Type the cost of freight or shipping for the products included in the opportunity for use in calculating the Total Amount field. */ FreightAmount: DevKit.WebApi.MoneyValue; /** Value of the Freight Amount in base currency. */ FreightAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Select whether information about competitors is included. */ IdentifyCompetitors: DevKit.WebApi.BooleanValue; /** Select whether the customer contacts for this opportunity have been identified. */ IdentifyCustomerContacts: DevKit.WebApi.BooleanValue; /** Choose whether you have recorded who will pursue the opportunity. */ IdentifyPursuitTeam: DevKit.WebApi.BooleanValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Choose whether someone from the sales team contacted this lead earlier. */ InitialCommunication: DevKit.WebApi.OptionSetValue; /** Shows the forecasted revenue for an Opportunity. */ int_Forecast: DevKit.WebApi.MoneyValue; /** Value of the Forecast in base currency. */ int_forecast_Base: DevKit.WebApi.MoneyValueReadonly; /** Indicates whether the opportunity is private or visible to the entire organization. */ IsPrivate: DevKit.WebApi.BooleanValueReadonly; /** Select whether the estimated revenue for the opportunity is calculated automatically based on the products entered or entered manually by a user. */ IsRevenueSystemCalculated: DevKit.WebApi.BooleanValue; /** Contains the date time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** The account manager responsible for the opportunity. */ msdyn_AccountManagerId: DevKit.WebApi.LookupValue; /** The organizational unit in charge of the opportunity. */ msdyn_ContractOrganizationalUnitId: DevKit.WebApi.LookupValue; /** Categories used for forecasting. */ msdyn_forecastcategory: DevKit.WebApi.OptionSetValue; /** Internal use only. */ msdyn_OrderType: DevKit.WebApi.OptionSetValue; /** Unique identifier for Work Order Type associated with Opportunity. */ msdyn_WorkOrderType: DevKit.WebApi.LookupValue; /** Type a subject or descriptive name, such as the expected order or company name, for the opportunity. */ Name: DevKit.WebApi.StringValue; /** Choose how high the level of need is for the lead's company. */ Need: DevKit.WebApi.OptionSetValue; /** Shows the duration in minutes for which the opportunity was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier of the opportunity. */ OpportunityId: DevKit.WebApi.GuidValue; /** Select the expected value or priority of the opportunity based on revenue, customer status, or closing probability. */ OpportunityRatingCode: DevKit.WebApi.OptionSetValue; /** Choose the lead that the opportunity was created from for reporting and analytics. The field is read-only after the opportunity is created and defaults to the correct lead when an opportunity is created from a converted lead. */ OriginatingLeadId: DevKit.WebApi.LookupValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Choose an account to connect this opportunity to, so that the relationship is visible in reports and analytics, and to provide a quick link to additional details, such as financial information and activities. */ ParentAccountId: DevKit.WebApi.LookupValue; /** Choose a contact to connect this opportunity to, so that the relationship is visible in reports and analytics. */ ParentContactId: DevKit.WebApi.LookupValue; /** Information about whether the opportunity participates in workflow rules. */ ParticipatesInWorkflow: DevKit.WebApi.BooleanValue; /** Select whether the final proposal has been presented to the account. */ PresentFinalProposal: DevKit.WebApi.BooleanValue; /** Select whether a proposal for the opportunity has been presented to the account. */ PresentProposal: DevKit.WebApi.BooleanValue; /** Choose the price list associated with this record to make sure the products associated with the campaign are offered at the correct prices. */ PriceLevelId: DevKit.WebApi.LookupValue; /** Pricing error for the opportunity. */ PricingErrorCode: DevKit.WebApi.OptionSetValue; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Contains the id of the process associated with the entity. */ ProcessId: DevKit.WebApi.GuidValue; /** Type notes about the proposed solution for the opportunity. */ ProposedSolution: DevKit.WebApi.StringValue; /** Choose whether an individual or a committee will be involved in the purchase process for the lead. */ PurchaseProcess: DevKit.WebApi.OptionSetValue; /** Choose how long the lead will likely take to make the purchase. */ PurchaseTimeframe: DevKit.WebApi.OptionSetValue; /** Select whether the decision about pursuing the opportunity has been made. */ PursuitDecision: DevKit.WebApi.BooleanValue; /** Type comments about the qualification or scoring of the lead. */ QualificationComments: DevKit.WebApi.StringValue; /** Type comments about the quotes associated with the opportunity. */ QuoteComments: DevKit.WebApi.StringValue; /** Choose whether the proposal feedback has been captured and resolved for the opportunity. */ ResolveFeedback: DevKit.WebApi.BooleanValue; /** Select the sales stage of this opportunity to aid the sales team in their efforts to win this opportunity. */ SalesStage: DevKit.WebApi.OptionSetValue; /** Select the sales process stage for the opportunity to indicate the probability of closing the opportunity. */ SalesStageCode: DevKit.WebApi.OptionSetValue; /** Enter the date and time of the prospecting follow-up meeting with the lead. */ ScheduleFollowup_Prospect_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the date and time of the qualifying follow-up meeting with the lead. */ ScheduleFollowup_Qualify_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the date and time of the proposal meeting for the opportunity. */ ScheduleProposalMeeting_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Select whether a thank you note has been sent to the account for considering the proposal. */ SendThankYouNote: DevKit.WebApi.BooleanValue; /** Skip Price Calculation (For Internal Use) */ SkipPriceCalculation: DevKit.WebApi.OptionSetValue; /** Choose the service level agreement (SLA) that you want to apply to the opportunity record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this opportunity. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the opportunity is open, won, or lost. Won and lost opportunities are read-only and can't be edited until they are reactivated. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the opportunity's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Shows the ID of the workflow step. */ StepId: DevKit.WebApi.GuidValue; /** Shows the current phase in the sales pipeline for the opportunity. This is updated by a workflow. */ StepName: DevKit.WebApi.StringValue; /** Number of users or conversations followed the record */ TeamsFollowed: DevKit.WebApi.IntegerValue; /** Select when the opportunity is likely to be closed. */ TimeLine: DevKit.WebApi.OptionSetValue; /** Total time spent for emails (read and write) and meetings by me in relation to the opportunity record. */ TimeSpentByMeOnEmailAndMeetings: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the total amount due, calculated as the sum of the products, discounts, freight, and taxes for the opportunity. */ TotalAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Amount in base currency. */ TotalAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total product amount for the opportunity, minus any discounts. This value is added to freight and tax amounts in the calculation for the total amount of the opportunity. */ TotalAmountLessFreight: DevKit.WebApi.MoneyValue; /** Value of the Total Pre-Freight Amount in base currency. */ TotalAmountLessFreight_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total discount amount, based on the discount price and rate entered on the opportunity. */ TotalDiscountAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Discount Amount in base currency. */ TotalDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the sum of all existing and write-in products included on the opportunity, based on the specified price list and quantities. */ TotalLineItemAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Detail Amount in base currency. */ TotalLineItemAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total of the Manual Discount amounts specified on all products included in the opportunity. This value is reflected in the Total Detail Amount field on the opportunity and is added to any discount amount or rate specified on the opportunity. */ TotalLineItemDiscountAmount: DevKit.WebApi.MoneyValue; /** Value of the Total Line Item Discount Amount in base currency. */ TotalLineItemDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total of the Tax amounts specified on all products included in the opportunity, included in the Total Amount field calculation for the opportunity. */ TotalTax: DevKit.WebApi.MoneyValue; /** Value of the Total Tax in base currency. */ TotalTax_Base: DevKit.WebApi.MoneyValueReadonly; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Opportunity { enum BudgetStatus { /** 2 */ Can_Buy, /** 1 */ May_Buy, /** 0 */ No_Committed_Budget, /** 3 */ Will_Buy } enum InitialCommunication { /** 0 */ Contacted, /** 1 */ Not_Contacted } enum msdyn_forecastcategory { /** 100000002 */ Best_case, /** 100000003 */ Committed, /** 100000006 */ Lost, /** 100000004 */ Omitted, /** 100000001 */ Pipeline, /** 100000005 */ Won } enum msdyn_OrderType { /** 192350000 */ Item_based, /** 690970002 */ Service_Maintenance_Based, /** 192350001 */ Work_based } enum Need { /** 2 */ Good_to_have, /** 0 */ Must_have, /** 3 */ No_need, /** 1 */ Should_have } enum OpportunityRatingCode { /** 3 */ Cold, /** 1 */ Hot, /** 2 */ Warm } enum PricingErrorCode { /** 36 */ Base_Currency_Attribute_Overflow, /** 37 */ Base_Currency_Attribute_Underflow, /** 1 */ Detail_Error, /** 27 */ Discount_Type_Invalid_State, /** 33 */ Inactive_Discount_Type, /** 3 */ Inactive_Price_Level, /** 20 */ Invalid_Current_Cost, /** 28 */ Invalid_Discount, /** 26 */ Invalid_Discount_Type, /** 19 */ Invalid_Price, /** 17 */ Invalid_Price_Level_Amount, /** 34 */ Invalid_Price_Level_Currency, /** 18 */ Invalid_Price_Level_Percentage, /** 9 */ Invalid_Pricing_Code, /** 30 */ Invalid_Pricing_Precision, /** 7 */ Invalid_Product, /** 29 */ Invalid_Quantity, /** 24 */ Invalid_Rounding_Amount, /** 23 */ Invalid_Rounding_Option, /** 22 */ Invalid_Rounding_Policy, /** 21 */ Invalid_Standard_Cost, /** 15 */ Missing_Current_Cost, /** 14 */ Missing_Price, /** 2 */ Missing_Price_Level, /** 12 */ Missing_Price_Level_Amount, /** 13 */ Missing_Price_Level_Percentage, /** 8 */ Missing_Pricing_Code, /** 6 */ Missing_Product, /** 31 */ Missing_Product_Default_UOM, /** 32 */ Missing_Product_UOM_Schedule_, /** 4 */ Missing_Quantity, /** 16 */ Missing_Standard_Cost, /** 5 */ Missing_Unit_Price, /** 10 */ Missing_UOM, /** 0 */ None, /** 35 */ Price_Attribute_Out_Of_Range, /** 25 */ Price_Calculation_Error, /** 11 */ Product_Not_In_Price_Level, /** 38 */ Transaction_currency_is_not_set_for_the_product_price_list_item } enum PriorityCode { /** 1 */ Default_Value } enum PurchaseProcess { /** 1 */ Committee, /** 0 */ Individual, /** 2 */ Unknown } enum PurchaseTimeframe { /** 0 */ Immediate, /** 2 */ Next_Quarter, /** 1 */ This_Quarter, /** 3 */ This_Year, /** 4 */ Unknown } enum SalesStage { /** 3 */ Close, /** 1 */ Develop, /** 2 */ Propose, /** 0 */ Qualify } enum SalesStageCode { /** 1 */ Default_Value } enum SkipPriceCalculation { /** 0 */ DoPriceCalcAlways, /** 1 */ SkipPriceCalcOnRetrieve } enum StateCode { /** 2 */ Lost, /** 0 */ Open, /** 1 */ Won } enum StatusCode { /** 4 */ Canceled, /** 1 */ In_Progress, /** 2 */ On_Hold, /** 5 */ Out_Sold, /** 3 */ Won } enum TimeLine { /** 0 */ Immediate, /** 2 */ Next_Quarter, /** 4 */ Not_known, /** 1 */ This_Quarter, /** 3 */ This_Year } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['AI for Sales','Field Service Information','Opportunity','Project Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import test from 'ava'; import {JsonTypeName} from '../src/decorators/JsonTypeName'; import {JsonSubTypes} from '../src/decorators/JsonSubTypes'; import {JsonTypeInfo, JsonTypeInfoAs, JsonTypeInfoId} from '../src/decorators/JsonTypeInfo'; import {ObjectMapper} from '../src/databind/ObjectMapper'; import {JsonTypeId} from '../src/decorators/JsonTypeId'; import {JacksonError} from '../src/core/JacksonError'; import {JsonClassType} from '../src/decorators/JsonClassType'; import {JsonProperty} from '../src/decorators/JsonProperty'; import { ClassType, JsonParserTransformerContext, JsonStringifierTransformerContext, TypeIdResolver } from '../src/@types'; import {JsonTypeIdResolver} from '../src/decorators/JsonTypeIdResolver'; import {JsonGetter} from '../src/decorators/JsonGetter'; import {JsonSetter} from '../src/decorators/JsonSetter'; test('@JsonTypeInfo and @JsonSubTypes at class level with JsonTypeInfoAs.PROPERTY without subtypes name', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog}, {class: () => Cat}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { } class Cat extends Animal { } const dog = new Dog('Arthur'); const cat = new Cat('Merlin'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]); t.deepEqual(JSON.parse(jsonData), JSON.parse('[{"name":"Arthur","@type":"Dog"},{"name":"Merlin","@type":"Cat"}]')); const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]}); t.assert(animals instanceof Array); t.is(animals.length, 2); t.assert(animals[0] instanceof Dog); t.is(animals[0].name, 'Arthur'); t.assert(animals[1] instanceof Cat); t.is(animals[1].name, 'Merlin'); }); test('@JsonTypeInfo at class level with JsonTypeInfoAs.PROPERTY without subtypes name and using a custom @JsonTypeIdResolver', t => { class CustomTypeIdResolver implements TypeIdResolver { idFromValue(obj: any, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): string { if (obj instanceof Dog) { return 'animalDogType'; } else if (obj instanceof Cat) { return 'animalCatType'; } return null; } typeFromId(id: string, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): ClassType<any> { switch (id) { case 'animalDogType': return Dog; case 'animalCatType': return Cat; } return null; }; } @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonTypeIdResolver({resolver: new CustomTypeIdResolver()}) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { } class Cat extends Animal { } const dog = new Dog('Arthur'); const cat = new Cat('Merlin'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]); t.deepEqual(JSON.parse(jsonData), JSON.parse('[{"name":"Arthur","@type":"animalDogType"},{"name":"Merlin","@type":"animalCatType"}]')); const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]}); t.assert(animals instanceof Array); t.is(animals.length, 2); t.assert(animals[0] instanceof Dog); t.is(animals[0].name, 'Arthur'); t.assert(animals[1] instanceof Cat); t.is(animals[1].name, 'Merlin'); }); test('@JsonTypeInfo and @JsonSubTypes at property level with JsonTypeInfoAs.PROPERTY without subtypes name', t => { class Zoo { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog}, {class: () => Cat}, ] }) @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { @JsonProperty() @JsonClassType({type: () => [Dog]}) father: Dog; @JsonProperty() @JsonClassType({type: () => [Dog]}) mother: Dog; } class Cat extends Animal { } const zoo = new Zoo(); const dog = new Dog('Arthur'); const fatherDog = new Dog('Buddy'); const motherDog = new Dog('Coco'); dog.father = fatherDog; dog.mother = motherDog; const cat = new Cat('Merlin'); zoo.animals.push(dog, cat); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Zoo>(zoo); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"animals":[{"name":"Arthur","father":{"name":"Buddy"},"mother":{"name":"Coco"},"@type":"Dog"},{"name":"Merlin","@type":"Cat"}]}')); const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert((zooParsed.animals[0] as Dog).father instanceof Dog); t.is((zooParsed.animals[0] as Dog).father.name, 'Buddy'); t.assert((zooParsed.animals[0] as Dog).mother instanceof Dog); t.is((zooParsed.animals[0] as Dog).mother.name, 'Coco'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); test('@JsonTypeInfo and @JsonSubTypes at method level with JsonTypeInfoAs.PROPERTY without subtypes name', t => { class Zoo { @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; @JsonGetter() @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog}, {class: () => Cat}, ] }) @JsonClassType({type: () => [Array, [Animal]]}) getAnimals(): Animal[] { return this.animals; } @JsonSetter() @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog}, {class: () => Cat}, ] }) setAnimals(@JsonClassType({type: () => [Array, [Animal]]}) animals) { this.animals = animals; } } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { } class Cat extends Animal { } const zoo = new Zoo(); const dog = new Dog('Arthur'); const cat = new Cat('Merlin'); zoo.animals.push(dog, cat); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Zoo>(zoo); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"animals":[{"name":"Arthur","@type":"Dog"},{"name":"Merlin","@type":"Cat"}]}')); const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); test('@JsonTypeInfo at property level with JsonTypeInfoAs.PROPERTY without subtypes name and using a custom @JsonTypeIdResolver', t => { class CustomTypeIdResolver implements TypeIdResolver { idFromValue(obj: any, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): string { if (obj instanceof Dog) { return 'animalDogType'; } else if (obj instanceof Cat) { return 'animalCatType'; } return null; } typeFromId(id: string, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): ClassType<any> { switch (id) { case 'animalDogType': return Dog; case 'animalCatType': return Cat; } return null; }; } class Zoo { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonTypeIdResolver({resolver: new CustomTypeIdResolver()}) @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { @JsonProperty() @JsonClassType({type: () => [Dog]}) father: Dog; @JsonProperty() @JsonClassType({type: () => [Dog]}) mother: Dog; } class Cat extends Animal { } const zoo = new Zoo(); const dog = new Dog('Arthur'); const fatherDog = new Dog('Buddy'); const motherDog = new Dog('Coco'); dog.father = fatherDog; dog.mother = motherDog; const cat = new Cat('Merlin'); zoo.animals.push(dog, cat); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Zoo>(zoo); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"animals":[{"name":"Arthur","father":{"name":"Buddy"},"mother":{"name":"Coco"},"@type":"animalDogType"},{"name":"Merlin","@type":"animalCatType"}]}')); const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert((zooParsed.animals[0] as Dog).father instanceof Dog); t.is((zooParsed.animals[0] as Dog).father.name, 'Buddy'); t.assert((zooParsed.animals[0] as Dog).mother instanceof Dog); t.is((zooParsed.animals[0] as Dog).mother.name, 'Coco'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); test('@JsonTypeInfo at method level with JsonTypeInfoAs.PROPERTY without subtypes name and using a custom @JsonTypeIdResolver', t => { class CustomTypeIdResolver implements TypeIdResolver { idFromValue(obj: any, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): string { if (obj instanceof Dog) { return 'animalDogType'; } else if (obj instanceof Cat) { return 'animalCatType'; } return null; } typeFromId(id: string, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): ClassType<any> { switch (id) { case 'animalDogType': return Dog; case 'animalCatType': return Cat; } return null; }; } class Zoo { @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; @JsonGetter() @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonTypeIdResolver({resolver: new CustomTypeIdResolver()}) @JsonClassType({type: () => [Array, [Animal]]}) getAnimals(): Animal[] { return this.animals; } @JsonSetter() @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonTypeIdResolver({resolver: new CustomTypeIdResolver()}) setAnimals(@JsonClassType({type: () => [Array, [Animal]]}) animals) { this.animals = animals; } } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { @JsonProperty() @JsonClassType({type: () => [Dog]}) father: Dog; @JsonProperty() @JsonClassType({type: () => [Dog]}) mother: Dog; } class Cat extends Animal { } const zoo = new Zoo(); const dog = new Dog('Arthur'); const fatherDog = new Dog('Buddy'); const motherDog = new Dog('Coco'); dog.father = fatherDog; dog.mother = motherDog; const cat = new Cat('Merlin'); zoo.animals.push(dog, cat); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Zoo>(zoo); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"animals":[{"name":"Arthur","father":{"name":"Buddy"},"mother":{"name":"Coco"},"@type":"animalDogType"},{"name":"Merlin","@type":"animalCatType"}]}')); const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert((zooParsed.animals[0] as Dog).father instanceof Dog); t.is((zooParsed.animals[0] as Dog).father.name, 'Buddy'); t.assert((zooParsed.animals[0] as Dog).mother instanceof Dog); t.is((zooParsed.animals[0] as Dog).mother.name, 'Coco'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); test('@JsonTypeInfo and @JsonSubTypes at parameter level with JsonTypeInfoAs.PROPERTY without subtypes name', t => { class Zoo { @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; constructor( @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog}, {class: () => Cat}, ] }) @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[]) { this.animals = animals; } } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { @JsonProperty() @JsonClassType({type: () => [Dog]}) father: Dog; @JsonProperty() @JsonClassType({type: () => [Dog]}) mother: Dog; } class Cat extends Animal { } const objectMapper = new ObjectMapper(); // eslint-disable-next-line max-len const jsonData = '{"animals":[{"name":"Arthur","father":{"name":"Buddy"},"mother":{"name":"Coco"},"@type":"Dog"},{"name":"Merlin","@type":"Cat"}]}'; const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert((zooParsed.animals[0] as Dog).father instanceof Dog); t.is((zooParsed.animals[0] as Dog).father.name, 'Buddy'); t.assert((zooParsed.animals[0] as Dog).mother instanceof Dog); t.is((zooParsed.animals[0] as Dog).mother.name, 'Coco'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); test('@JsonTypeInfo at parameter level with JsonTypeInfoAs.PROPERTY without subtypes name and using a custom @JsonTypeIdResolver', t => { class CustomTypeIdResolver implements TypeIdResolver { idFromValue(obj: any, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): string { if (obj instanceof Dog) { return 'animalDogType'; } else if (obj instanceof Cat) { return 'animalCatType'; } return null; } typeFromId(id: string, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): ClassType<any> { switch (id) { case 'animalDogType': return Dog; case 'animalCatType': return Cat; } return null; }; } class Zoo { @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; constructor( @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonTypeIdResolver({resolver: new CustomTypeIdResolver()}) @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[]) { this.animals = animals; } } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { @JsonProperty() @JsonClassType({type: () => [Dog]}) father: Dog; @JsonProperty() @JsonClassType({type: () => [Dog]}) mother: Dog; } class Cat extends Animal { } const objectMapper = new ObjectMapper(); // eslint-disable-next-line max-len const jsonData = '{"animals":[{"name":"Arthur","father":{"name":"Buddy"},"mother":{"name":"Coco"},"@type":"animalDogType"},{"name":"Merlin","@type":"animalCatType"}]}'; const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert((zooParsed.animals[0] as Dog).father instanceof Dog); t.is((zooParsed.animals[0] as Dog).father.name, 'Buddy'); t.assert((zooParsed.animals[0] as Dog).mother instanceof Dog); t.is((zooParsed.animals[0] as Dog).mother.name, 'Coco'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); test('@JsonTypeInfo at parameter level (inside @JsonClass) with JsonTypeInfoAs.PROPERTY without subtypes name', t => { class Zoo { @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; constructor( @JsonClassType({type: () => [Array, [ () => ({ target: Animal, decorators: [ { name: 'JsonTypeInfo', options: { use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY, property: '@type' } }, { name: 'JsonSubTypes', options: { types: [ {class: () => Dog}, {class: () => Cat}, ] } } ] }) ]]}) animals: Animal[]) { this.animals = animals; } } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { @JsonProperty() @JsonClassType({type: () => [Dog]}) father: Dog; @JsonProperty() @JsonClassType({type: () => [Dog]}) mother: Dog; } class Cat extends Animal { } const objectMapper = new ObjectMapper(); // eslint-disable-next-line max-len const jsonData = '{"animals":[{"name":"Arthur","father":{"name":"Buddy"},"mother":{"name":"Coco"},"@type":"Dog"},{"name":"Merlin","@type":"Cat"}]}'; const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert((zooParsed.animals[0] as Dog).father instanceof Dog); t.is((zooParsed.animals[0] as Dog).father.name, 'Buddy'); t.assert((zooParsed.animals[0] as Dog).mother instanceof Dog); t.is((zooParsed.animals[0] as Dog).mother.name, 'Coco'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); // eslint-disable-next-line max-len test('@JsonTypeInfo at parameter level (inside @JsonClass) with JsonTypeInfoAs.PROPERTY without subtypes name and using a custom @JsonTypeIdResolver', t => { class CustomTypeIdResolver implements TypeIdResolver { idFromValue(obj: any, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): string { if (obj instanceof Dog) { return 'animalDogType'; } else if (obj instanceof Cat) { return 'animalCatType'; } return null; } typeFromId(id: string, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): ClassType<any> { switch (id) { case 'animalDogType': return Dog; case 'animalCatType': return Cat; } return null; }; } class Zoo { @JsonProperty() @JsonClassType({type: () => [Array, [Animal]]}) animals: Animal[] = []; constructor( @JsonClassType({type: () => [Array, [ () => ({ target: Animal, decorators: [ { name: 'JsonTypeInfo', options: { use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY, property: '@type' } }, { name: 'JsonTypeIdResolver', options: { resolver: new CustomTypeIdResolver() } } ] }) ]]}) animals: Animal[]) { this.animals = animals; } } class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { @JsonProperty() @JsonClassType({type: () => [Dog]}) father: Dog; @JsonProperty() @JsonClassType({type: () => [Dog]}) mother: Dog; } class Cat extends Animal { } const objectMapper = new ObjectMapper(); // eslint-disable-next-line max-len const jsonData = '{"animals":[{"name":"Arthur","father":{"name":"Buddy"},"mother":{"name":"Coco"},"@type":"animalDogType"},{"name":"Merlin","@type":"animalCatType"}]}'; const zooParsed = objectMapper.parse<Zoo>(jsonData, {mainCreator: () => [Zoo]}); t.assert(zooParsed instanceof Zoo); t.is(zooParsed.animals.length, 2); t.assert(zooParsed.animals[0] instanceof Dog); t.is(zooParsed.animals[0].name, 'Arthur'); t.assert((zooParsed.animals[0] as Dog).father instanceof Dog); t.is((zooParsed.animals[0] as Dog).father.name, 'Buddy'); t.assert((zooParsed.animals[0] as Dog).mother instanceof Dog); t.is((zooParsed.animals[0] as Dog).mother.name, 'Coco'); t.assert(zooParsed.animals[1] instanceof Cat); t.is(zooParsed.animals[1].name, 'Merlin'); }); test('@JsonTypeInfo with JsonTypeInfoAs.PROPERTY with subtypes name', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog, name: 'dog'}, {class: () => Cat, name: 'cat'}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } @JsonTypeName({value: 'dog'}) class Dog extends Animal { } @JsonTypeName({value: 'cat'}) class Cat extends Animal { } const dog = new Dog('Arthur'); const cat = new Cat('Merlin'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]); t.deepEqual(JSON.parse(jsonData), JSON.parse('[{"name":"Arthur","@type":"dog"},{"name":"Merlin","@type":"cat"}]')); const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]}); t.assert(animals instanceof Array); t.is(animals.length, 2); t.assert(animals[0] instanceof Dog); t.is(animals[0].name, 'Arthur'); t.assert(animals[1] instanceof Cat); t.is(animals[1].name, 'Merlin'); }); test('@JsonTypeInfo with JsonTypeInfoAs.PROPERTY with @JsonTypeId', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.WRAPPER_OBJECT }) @JsonSubTypes({ types: [ {class: () => Dog, name: 'dog'}, {class: () => Cat, name: 'cat'}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } @JsonTypeName({value: 'dog'}) class Dog extends Animal { @JsonTypeId() @JsonClassType({type: () => [String]}) typeId: string; } @JsonTypeName({value: 'cat'}) class Cat extends Animal { @JsonTypeId() getTypeId(): string { return 'CatTypeId'; } } const dog = new Dog('Arthur'); dog.typeId = 'DogTypeId'; const cat = new Cat('Merlin'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]); t.deepEqual(JSON.parse(jsonData), JSON.parse('[{"DogTypeId":{"name":"Arthur"}},{"CatTypeId":{"name":"Merlin"}}]')); const err1 = t.throws<JacksonError>(() => { objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]}); }); t.assert(err1 instanceof JacksonError); const err2 = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<Array<Animal>>('[{"dog":{"name":"Arthur"}},{"CatTypeId":{"name":"Merlin"}}]', {mainCreator: () => [Array, [Animal]]}); }); t.assert(err2 instanceof JacksonError); const err3 = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<Array<Animal>>('[{"DogTypeId":{"name":"Arthur"}},{"cat":{"name":"Merlin"}}]', {mainCreator: () => [Array, [Animal]]}); }); t.assert(err3 instanceof JacksonError); // eslint-disable-next-line max-len const animals = objectMapper.parse<Array<Animal>>('[{"dog":{"name":"Arthur"}},{"cat":{"name":"Merlin"}}]', {mainCreator: () => [Array, [Animal]]}); t.assert(animals instanceof Array); t.is(animals.length, 2); t.assert(animals[0] instanceof Dog); t.is(animals[0].name, 'Arthur'); t.assert(animals[1] instanceof Cat); t.is(animals[1].name, 'Merlin'); }); test('@JsonTypeInfo with JsonTypeInfoAs.PROPERTY and custom property value', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY, property: 'myType' }) @JsonSubTypes({ types: [ {class: () => Dog, name: 'dog'}, {class: () => Cat, name: 'cat'}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } @JsonTypeName({value: 'dog'}) class Dog extends Animal { } @JsonTypeName({value: 'cat'}) class Cat extends Animal { } const dog = new Dog('Arthur'); const cat = new Cat('Merlin'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]); t.deepEqual(JSON.parse(jsonData), JSON.parse('[{"name":"Arthur","myType":"dog"},{"name":"Merlin","myType":"cat"}]')); const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]}); t.assert(animals instanceof Array); t.is(animals.length, 2); t.assert(animals[0] instanceof Dog); t.is(animals[0].name, 'Arthur'); t.assert(animals[1] instanceof Cat); t.is(animals[1].name, 'Merlin'); }); test('@JsonTypeInfo with JsonTypeInfoAs.WRAPPER_OBJECT', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.WRAPPER_OBJECT }) @JsonSubTypes({ types: [ {class: () => Dog, name: 'dog'}, {class: () => Cat, name: 'cat'}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } @JsonTypeName({value: 'dog'}) class Dog extends Animal { } @JsonTypeName({value: 'cat'}) class Cat extends Animal { } const dog = new Dog('Arthur'); const cat = new Cat('Merlin'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]); t.deepEqual(JSON.parse(jsonData), JSON.parse('[{"dog":{"name":"Arthur"}},{"cat":{"name":"Merlin"}}]')); const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]}); t.assert(animals instanceof Array); t.is(animals.length, 2); t.assert(animals[0] instanceof Dog); t.is(animals[0].name, 'Arthur'); t.assert(animals[1] instanceof Cat); t.is(animals[1].name, 'Merlin'); }); test('@JsonTypeInfo with JsonTypeInfoAs.WRAPPER_ARRAY', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.WRAPPER_ARRAY }) @JsonSubTypes({ types: [ {class: () => Dog, name: 'dog'}, {class: () => Cat, name: 'cat'}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } @JsonTypeName({value: 'dog'}) class Dog extends Animal { } @JsonTypeName({value: 'cat'}) class Cat extends Animal { } const dog = new Dog('Arthur'); const cat = new Cat('Merlin'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]); t.deepEqual(JSON.parse(jsonData), JSON.parse('[["dog",{"name":"Arthur"}],["cat",{"name":"Merlin"}]]')); const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]}); t.assert(animals instanceof Array); t.is(animals.length, 2); t.assert(animals[0] instanceof Dog); t.is(animals[0].name, 'Arthur'); t.assert(animals[1] instanceof Cat); t.is(animals[1].name, 'Merlin'); });
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Controllers * __NOTE__: An instance of this class is automatically created for an * instance of the DevSpacesManagementClient. */ export interface Controllers { /** * @summary Gets an Azure Dev Spaces Controller. * * Gets the properties for an Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Controller>>; /** * @summary Gets an Azure Dev Spaces Controller. * * Gets the properties for an Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Controller} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Controller} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Controller>; get(resourceGroupName: string, name: string, callback: ServiceCallback<models.Controller>): void; get(resourceGroupName: string, name: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Controller>): void; /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, name: string, controller: models.Controller, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Controller>>; /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Controller} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Controller} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, name: string, controller: models.Controller, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Controller>; create(resourceGroupName: string, name: string, controller: models.Controller, callback: ServiceCallback<models.Controller>): void; create(resourceGroupName: string, name: string, controller: models.Controller, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Controller>): void; /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, name: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, name: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Updates an Azure Dev Spaces Controller. * * Updates the properties of an existing Azure Dev Spaces Controller with the * specified update parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controllerUpdateParameters * * @param {object} [controllerUpdateParameters.tags] Tags for the Azure Dev * Spaces Controller. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, name: string, controllerUpdateParameters: models.ControllerUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Controller>>; /** * @summary Updates an Azure Dev Spaces Controller. * * Updates the properties of an existing Azure Dev Spaces Controller with the * specified update parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controllerUpdateParameters * * @param {object} [controllerUpdateParameters.tags] Tags for the Azure Dev * Spaces Controller. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Controller} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Controller} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, name: string, controllerUpdateParameters: models.ControllerUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Controller>; update(resourceGroupName: string, name: string, controllerUpdateParameters: models.ControllerUpdateParameters, callback: ServiceCallback<models.Controller>): void; update(resourceGroupName: string, name: string, controllerUpdateParameters: models.ControllerUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Controller>): void; /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ControllerList>>; /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ControllerList} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ControllerList>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.ControllerList>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ControllerList>): void; /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ControllerList>>; /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ControllerList} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ControllerList>; list(callback: ServiceCallback<models.ControllerList>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ControllerList>): void; /** * @summary Lists connection details for an Azure Dev Spaces Controller. * * Lists connection details for the underlying container resources of an Azure * Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerConnectionDetailsList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listConnectionDetailsWithHttpOperationResponse(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ControllerConnectionDetailsList>>; /** * @summary Lists connection details for an Azure Dev Spaces Controller. * * Lists connection details for the underlying container resources of an Azure * Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ControllerConnectionDetailsList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ControllerConnectionDetailsList} [result] - The deserialized result object if an error did not occur. * See {@link ControllerConnectionDetailsList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listConnectionDetails(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ControllerConnectionDetailsList>; listConnectionDetails(resourceGroupName: string, name: string, callback: ServiceCallback<models.ControllerConnectionDetailsList>): void; listConnectionDetails(resourceGroupName: string, name: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ControllerConnectionDetailsList>): void; /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Controller>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName: string, name: string, controller: models.Controller, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Controller>>; /** * @summary Creates an Azure Dev Spaces Controller. * * Creates an Azure Dev Spaces Controller with the specified create parameters. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} controller Controller create parameters. * * @param {string} controller.hostSuffix DNS suffix for public endpoints * running in the Azure Dev Spaces Controller. * * @param {string} controller.targetContainerHostResourceId Resource ID of the * target container host * * @param {string} controller.targetContainerHostCredentialsBase64 Credentials * of the target container host (base64). * * @param {object} controller.sku * * @param {string} [controller.sku.tier] The tier of the SKU for Azure Dev * Spaces Controller. Possible values include: 'Standard' * * @param {object} [controller.tags] Tags for the Azure resource. * * @param {string} [controller.location] Region where the Azure resource is * located. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Controller} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Controller} [result] - The deserialized result object if an error did not occur. * See {@link Controller} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName: string, name: string, controller: models.Controller, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Controller>; beginCreate(resourceGroupName: string, name: string, controller: models.Controller, callback: ServiceCallback<models.Controller>): void; beginCreate(resourceGroupName: string, name: string, controller: models.Controller, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Controller>): void; /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes an Azure Dev Spaces Controller. * * Deletes an existing Azure Dev Spaces Controller. * * @param {string} resourceGroupName Resource group to which the resource * belongs. * * @param {string} name Name of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, name: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, name: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, name: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ControllerList>>; /** * @summary Lists the Azure Dev Spaces Controllers in a resource group. * * Lists all the Azure Dev Spaces Controllers with their properties in the * specified resource group and subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ControllerList} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ControllerList>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.ControllerList>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ControllerList>): void; /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ControllerList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ControllerList>>; /** * @summary Lists the Azure Dev Spaces Controllers in a subscription. * * Lists all the Azure Dev Spaces Controllers with their properties in the * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ControllerList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ControllerList} [result] - The deserialized result object if an error did not occur. * See {@link ControllerList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ControllerList>; listNext(nextPageLink: string, callback: ServiceCallback<models.ControllerList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ControllerList>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the DevSpacesManagementClient. */ export interface Operations { /** * @summary Lists operations for the resource provider. * * Lists all the supported operations by the Microsoft.DevSpaces resource * provider along with their description. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceProviderOperationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceProviderOperationList>>; /** * @summary Lists operations for the resource provider. * * Lists all the supported operations by the Microsoft.DevSpaces resource * provider along with their description. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResourceProviderOperationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResourceProviderOperationList} [result] - The deserialized result object if an error did not occur. * See {@link ResourceProviderOperationList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceProviderOperationList>; list(callback: ServiceCallback<models.ResourceProviderOperationList>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceProviderOperationList>): void; /** * @summary Lists operations for the resource provider. * * Lists all the supported operations by the Microsoft.DevSpaces resource * provider along with their description. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceProviderOperationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResourceProviderOperationList>>; /** * @summary Lists operations for the resource provider. * * Lists all the supported operations by the Microsoft.DevSpaces resource * provider along with their description. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResourceProviderOperationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResourceProviderOperationList} [result] - The deserialized result object if an error did not occur. * See {@link ResourceProviderOperationList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResourceProviderOperationList>; listNext(nextPageLink: string, callback: ServiceCallback<models.ResourceProviderOperationList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceProviderOperationList>): void; }
the_stack
import { observableArray, isObservableArray, observable, isObservable, subscribable } from '../dist' describe('Observable Array', function () { var testObservableArray, notifiedValues, beforeNotifiedValues beforeEach(function () { testObservableArray = observableArray([1, 2, 3]) notifiedValues = [] testObservableArray.subscribe(function (value) { notifiedValues.push(value ? value.slice(0) : value) }) beforeNotifiedValues = [] testObservableArray.subscribe(function (value) { beforeNotifiedValues.push(value ? value.slice(0) : value) }, null, 'beforeChange') }) it('Should be observable', function () { expect(isObservable(testObservableArray)).toEqual(true) }) it('Should advertise as observable array', function () { expect(isObservableArray(observableArray())).toEqual(true) }) it('isObservableArray should return false for non-observable array values', function () { const types = [ undefined, null, 'x', {}, function () {}, observable([]) ] types.forEach(value => expect(isObservableArray(value)).toEqual(false)) }) it('should be iterable', function () { expect(Array.from(testObservableArray)).toEqual([1, 2, 3]) }) it('Should initialize to empty array if you pass no args to constructor', function () { var instance = observableArray() expect(instance().length).toEqual(0) }) it('Should require constructor arg, if given, to be array-like or null or undefined', function () { // Try non-array-like args expect(function () { observableArray(1) }).toThrow() expect(function () { observableArray({}) }).toThrow() // Try allowed args expect((observableArray([1, 2, 3]))().length).toEqual(3) expect((observableArray(null))().length).toEqual(0) expect((observableArray(undefined))().length).toEqual(0) }) it('Should be able to write values to it', function () { testObservableArray(['X', 'Y']) expect(notifiedValues.length).toEqual(1) expect(notifiedValues[0][0]).toEqual('X') expect(notifiedValues[0][1]).toEqual('Y') }) it('Should be able to mark single items as destroyed', function () { var x = {}, y = {} testObservableArray([x, y]) testObservableArray.destroy(y) expect(testObservableArray().length).toEqual(2) expect(x._destroy).toEqual(undefined) expect(y._destroy).toEqual(true) }) it('Should be able to mark multiple items as destroyed', function () { var x = {}, y = {}, z = {} testObservableArray([x, y, z]) testObservableArray.destroyAll([x, z]) expect(testObservableArray().length).toEqual(3) expect(x._destroy).toEqual(true) expect(y._destroy).toEqual(undefined) expect(z._destroy).toEqual(true) }) it('Should be able to mark observable items as destroyed', function () { var x = observable(), y = observable() testObservableArray([x, y]) testObservableArray.destroy(y) expect(testObservableArray().length).toEqual(2) expect(x._destroy).toEqual(undefined) expect(y._destroy).toEqual(true) }) it('Should be able to mark all items as destroyed by passing no args to destroyAll()', function () { var x = {}, y = {}, z = {} testObservableArray([x, y, z]) testObservableArray.destroyAll() expect(testObservableArray().length).toEqual(3) expect(x._destroy).toEqual(true) expect(y._destroy).toEqual(true) expect(z._destroy).toEqual(true) }) it('Should notify subscribers on push', function () { testObservableArray.push('Some new value') expect(notifiedValues).toEqual([[1, 2, 3, 'Some new value']]) }) it('Should notify "beforeChange" subscribers before push', function () { testObservableArray.push('Some new value') expect(beforeNotifiedValues).toEqual([[1, 2, 3]]) }) it('Should notify subscribers on pop', function () { var popped = testObservableArray.pop() expect(popped).toEqual(3) expect(notifiedValues).toEqual([[1, 2]]) }) it('Should notify "beforeChange" subscribers before pop', function () { var popped = testObservableArray.pop() expect(popped).toEqual(3) expect(beforeNotifiedValues).toEqual([[1, 2, 3]]) }) it('Should notify subscribers on splice', function () { var spliced = testObservableArray.splice(1, 1) expect(spliced).toEqual([2]) expect(notifiedValues).toEqual([[1, 3]]) }) it('Should notify "beforeChange" subscribers before splice', function () { var spliced = testObservableArray.splice(1, 1) expect(spliced).toEqual([2]) expect(beforeNotifiedValues).toEqual([[1, 2, 3]]) }) it('Should notify subscribers on remove by value', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) notifiedValues = [] var removed = testObservableArray.remove('Beta') expect(removed).toEqual(['Beta']) expect(notifiedValues).toEqual([['Alpha', 'Gamma']]) }) it('Should notify subscribers on remove by predicate', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) notifiedValues = [] var removed = testObservableArray.remove(function (value) { return value == 'Beta' }) expect(removed).toEqual(['Beta']) expect(notifiedValues).toEqual([['Alpha', 'Gamma']]) }) it('Should notify subscribers on remove multiple by value', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) notifiedValues = [] var removed = testObservableArray.removeAll(['Gamma', 'Alpha']) expect(removed).toEqual(['Alpha', 'Gamma']) expect(notifiedValues).toEqual([['Beta']]) }) it('Should clear observable array entirely if you pass no args to removeAll()', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) notifiedValues = [] var removed = testObservableArray.removeAll() expect(removed).toEqual(['Alpha', 'Beta', 'Gamma']) expect(notifiedValues).toEqual([[]]) }) it('Should notify "beforeChange" subscribers before remove', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) beforeNotifiedValues = [] var removed = testObservableArray.remove('Beta') expect(removed).toEqual(['Beta']) expect(beforeNotifiedValues).toEqual([['Alpha', 'Beta', 'Gamma']]) }) it('Should not notify subscribers on remove by value with no match', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) notifiedValues = [] var removed = testObservableArray.remove('Delta') expect(removed).toEqual([]) expect(notifiedValues).toEqual([]) }) it('Should not notify "beforeChange" subscribers before remove by value with no match', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) beforeNotifiedValues = [] var removed = testObservableArray.remove('Delta') expect(removed).toEqual([]) expect(beforeNotifiedValues).toEqual([]) }) it('Should modify original array on remove', function () { var originalArray = ['Alpha', 'Beta', 'Gamma'] testObservableArray(originalArray) notifiedValues = [] testObservableArray.remove('Beta') expect(originalArray).toEqual(['Alpha', 'Gamma']) }) it('Should modify original array on removeAll', function () { var originalArray = ['Alpha', 'Beta', 'Gamma'] testObservableArray(originalArray) notifiedValues = [] testObservableArray.removeAll() expect(originalArray).toEqual([]) }) it('Should remove matching observable items', function () { var x = observable(), y = observable() testObservableArray([x, y]) notifiedValues = [] var removed = testObservableArray.remove(y) expect(testObservableArray()).toEqual([x]) expect(removed).toEqual([y]) expect(notifiedValues).toEqual([[x]]) }) it('Should throw an exception if matching array item moved or removed during "remove"', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) notifiedValues = [] expect(function () { testObservableArray.remove(function (value) { if (value === 'Beta') { testObservableArray.splice(0, 1) return true } }) }).toThrow() expect(testObservableArray()).toEqual(['Beta', 'Gamma']) }) it('Should notify subscribers on replace', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) notifiedValues = [] testObservableArray.replace('Beta', 'Delta') expect(notifiedValues).toEqual([['Alpha', 'Delta', 'Gamma']]) }) it('Should notify "beforeChange" subscribers before replace', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) beforeNotifiedValues = [] testObservableArray.replace('Beta', 'Delta') expect(beforeNotifiedValues).toEqual([['Alpha', 'Beta', 'Gamma']]) }) it('Should notify subscribers after marking items as destroyed', function () { var x = {}, y = {}, didNotify = false testObservableArray([x, y]) testObservableArray.subscribe(function (/* value */) { expect(x._destroy).toEqual(undefined) expect(y._destroy).toEqual(true) didNotify = true }) testObservableArray.destroy(y) expect(didNotify).toEqual(true) }) it('Should notify "beforeChange" subscribers before marking items as destroyed', function () { var x = {}, y = {}, didNotify = false testObservableArray([x, y]) testObservableArray.subscribe(function (/* value */) { expect(x._destroy).toEqual(undefined) expect(y._destroy).toEqual(undefined) didNotify = true }, null, 'beforeChange') testObservableArray.destroy(y) expect(didNotify).toEqual(true) }) it('Should be able to return first index of item', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) expect(testObservableArray.indexOf('Beta')).toEqual(1) expect(testObservableArray.indexOf('Gamma')).toEqual(2) expect(testObservableArray.indexOf('Alpha')).toEqual(0) expect(testObservableArray.indexOf('fake')).toEqual(-1) }) it('Should return the correct myArray.length, and via myArray().length', function () { testObservableArray(['Alpha', 'Beta', 'Gamma']) expect(testObservableArray.length).toEqual(3) expect(testObservableArray().length).toEqual(3) }) it('Should return the observableArray reference from "sort" and "reverse"', function () { expect(testObservableArray.reverse()).toBe(testObservableArray) expect(testObservableArray.sort()).toBe(testObservableArray) // Verify that reverse and sort notified their changes expect(notifiedValues).toEqual([ [3, 2, 1], [1, 2, 3] ]) }) it('Should return a new sorted array from "sorted"', function () { // set some unsorted values so we can see that the new array is sorted testObservableArray([ 5, 7, 3, 1 ]) notifiedValues = [] var newArray = testObservableArray.sorted() expect(newArray).toEqual([ 1, 3, 5, 7 ]) expect(newArray).not.toBe(testObservableArray()) const newArray2 = testObservableArray.sorted((a, b) => b - a) expect(newArray2).toEqual([ 7, 5, 3, 1 ]) expect(newArray2).not.toBe(testObservableArray()) expect(newArray2).not.toBe(newArray) expect(notifiedValues).toEqual([]) }) it('Should return a new reversed array from "reversed"', function () { var newArray = testObservableArray.reversed() expect(newArray).toEqual([ 3, 2, 1 ]) expect(newArray).not.toBe(testObservableArray()) expect(notifiedValues).toEqual([]) }) it('Should inherit any properties defined on subscribable.fn, observable.fn, or observableArray.fn', function () { this.after(function () { delete subscribable.fn.subscribableProp // Will be able to reach this delete subscribable.fn.customProp // Overridden on observable.fn delete subscribable.fn.customFunc // Overridden on observableArray.fn delete observable.fn.customProp // Overridden on observableArray.fn delete observable.fn.customFunc // Will be able to reach this delete observableArray.fn.customProp // Will be able to reach this }) subscribable.fn.subscribableProp = 'subscribable value' subscribable.fn.customProp = 'subscribable value - will be overridden' subscribable.fn.customFunc = function () { throw new Error('Shouldn\'t be reachable') } observable.fn.customProp = 'observable prop value - will be overridden' observable.fn.customFunc = function () { return this() } observableArray.fn.customProp = 'observableArray value' var instance = observableArray([123]) expect(instance.subscribableProp).toEqual('subscribable value') expect(instance.customProp).toEqual('observableArray value') expect(instance.customFunc()).toEqual([123]) }) it('Should have access to functions added to "fn" on existing instances on supported browsers', function () { // On unsupported browsers, there's nothing to test if (!jasmine.browserSupportsProtoAssignment) { return } this.after(function () { delete observable.fn.customFunction1 delete observableArray.fn.customFunction2 }) const obsArr = observableArray() var customFunction1 = function () {} var customFunction2 = function () {} observable.fn.customFunction1 = customFunction1 observableArray.fn.customFunction2 = customFunction2 expect(obsArr.customFunction1).toBe(customFunction1) expect(obsArr.customFunction2).toBe(customFunction2) }) })
the_stack
import { camelCaseify, pluralize } from '../../../lib/vulcan-lib'; import type { SchemaGraphQLFieldDescription, SchemaGraphQLFieldArgument } from './initGraphQL'; const convertToGraphQL = (fields: SchemaGraphQLFieldDescription[], indentation: string) => { return fields.length > 0 ? fields.map(f => fieldTemplate(f, indentation)).join('\n') : ''; }; export const arrayToGraphQL = (fields: SchemaGraphQLFieldArgument[]) => fields.map(f => `${f.name}: ${f.type}`).join(', '); /* For backwards-compatibility reasons, args can either be a string or an array of objects */ const getArguments = (args: string|SchemaGraphQLFieldArgument[]|null|undefined) => { if (Array.isArray(args) && args.length > 0) { return `(${arrayToGraphQL(args)})`; } else if (typeof args === 'string') { return `(${args})`; } else { return ''; } }; /* ------------------------------------- Generic Field Template ------------------------------------- */ // export const fieldTemplate = ({ name, type, args, directive, description, required }, indentation = '') => // `${description ? `${indentation}# ${description}\n` : ''}${indentation}${name}${getArguments(args)}: ${type}${required ? '!' : ''} ${directive ? directive : ''}`; // version that does not make any fields required const fieldTemplate = ({ name, type, args, directive, description, required }: SchemaGraphQLFieldDescription, indentation = '') => `${description ? `${indentation}# ${description}\n` : ''}${indentation}${name}${getArguments(args)}: ${type} ${directive ? directive : ''}`; /* ------------------------------------- Main Type ------------------------------------- */ /* The main type type Movie{ _id: String title: String description: String createdAt: Date } */ export const mainTypeTemplate = ({ typeName, description, interfaces, fields }: { typeName: string, description?: string, interfaces: string[], fields: SchemaGraphQLFieldDescription[], }) => `# ${description} type ${typeName} ${interfaces.length ? `implements ${interfaces.join(', ')} ` : ''}{ ${convertToGraphQL(fields, ' ')} } `; /* ------------------------------------- Selector Types ------------------------------------- */ /* The selector type is used to query for one or more documents type MovieSelectorInput { AND: [MovieSelectorInput] OR: [MovieSelectorInput] id: String id_not: String id_in: [String!] id_not_in: [String!] ... name: String name_not: String name_in: [String!] name_not_in: [String!] ... } see https://www.opencrud.org/#sec-Data-types */ export const selectorInputTemplate = ({ typeName, fields }: { typeName: string, fields: SchemaGraphQLFieldDescription[] }) => `input ${typeName}SelectorInput { AND: [${typeName}SelectorInput] OR: [${typeName}SelectorInput] ${convertToGraphQL(fields, ' ')} }`; /* The unique selector type is used to query for exactly one document type MovieSelectorUniqueInput { _id: String slug: String } */ export const selectorUniqueInputTemplate = ({ typeName, fields }: { typeName: string, fields: SchemaGraphQLFieldDescription[] }) => `input ${typeName}SelectorUniqueInput { _id: String documentId: String # OpenCRUD backwards compatibility slug: String ${convertToGraphQL(fields, ' ')} }`; /* The orderBy type defines which fields a query can be ordered by enum MovieOrderByInput { title createdAt } */ export const orderByInputTemplate = ({ typeName, fields }: { typeName: string, fields: SchemaGraphQLFieldDescription[] }) => `enum ${typeName}OrderByInput { foobar ${fields.join('\n ')} }`; /* ------------------------------------- Query Types ------------------------------------- */ /* A query for a single document movie(input: SingleMovieInput) : SingleMovieOutput */ export const singleQueryTemplate = ({ typeName }: {typeName: string}) => `${camelCaseify(typeName)}(input: Single${typeName}Input): Single${typeName}Output`; /* A query for multiple documents movies(input: MultiMovieInput) : MultiMovieOutput */ export const multiQueryTemplate = ({ typeName }: {typeName: string}) => `${camelCaseify(pluralize(typeName))}(input: Multi${typeName}Input): Multi${typeName}Output`; /* ------------------------------------- Query Input Types ------------------------------------- */ /* The argument type when querying for a single document type SingleMovieInput { selector { documentId: String # or `_id: String` # or `slug: String` } enableCache: Boolean } */ export const singleInputTemplate = ({ typeName }: {typeName: string}) => `input Single${typeName}Input { selector: ${typeName}SelectorUniqueInput # Whether to enable caching for this query enableCache: Boolean # Return null instead of throwing MissingDocumentError allowNull: Boolean }`; /* The argument type when querying for multiple documents type MultiMovieInput { terms: JSON offset: Int limit: Int enableCache: Boolean } */ export const multiInputTemplate = ({ typeName }: {typeName: string}) => `input Multi${typeName}Input { # A JSON object that contains the query terms used to fetch data terms: JSON, # How much to offset the results by offset: Int, # A limit for the query limit: Int, # Whether to enable caching for this query enableCache: Boolean # Whether to calculate totalCount for this query enableTotal: Boolean # OpenCRUD fields where: ${typeName}SelectorInput orderBy: ${typeName}OrderByInput skip: Int after: String before: String first: Int last: Int }`; /* ------------------------------------- Query Output Types ------------------------------------- */ /* The type for the return value when querying for a single document type SingleMovieOuput{ result: Movie } */ export const singleOutputTemplate = ({ typeName }: {typeName: string}) => `type Single${typeName}Output{ result: ${typeName} }`; /* The type for the return value when querying for multiple documents type MultiMovieOuput{ results: [Movie] totalCount: Int } */ export const multiOutputTemplate = ({ typeName }: {typeName: string}) => `type Multi${typeName}Output{ results: [${typeName}] totalCount: Int }`; /* ------------------------------------- Mutation Types ------------------------------------- */ /* Mutation for creating a new document createMovie(input: CreateMovieInput) : MovieOutput */ export const createMutationTemplate = ({ typeName }: {typeName: string}) => `create${typeName}(data: Create${typeName}DataInput!) : ${typeName}Output`; /* Mutation for updating an existing document updateMovie(input: UpdateMovieInput) : MovieOutput */ export const updateMutationTemplate = ({ typeName }: {typeName: string}) => `update${typeName}(selector: ${typeName}SelectorUniqueInput!, data: Update${typeName}DataInput! ) : ${typeName}Output`; /* Mutation for updating an existing document; or creating it if it doesn't exist yet upsertMovie(input: UpsertMovieInput) : MovieOutput */ export const upsertMutationTemplate = ({ typeName }: {typeName: string}) => `upsert${typeName}(selector: ${typeName}SelectorUniqueInput!, data: Update${typeName}DataInput! ) : ${typeName}Output`; /* Mutation for deleting an existing document deleteMovie(input: DeleteMovieInput) : MovieOutput */ export const deleteMutationTemplate = ({ typeName }: {typeName: string}) => `delete${typeName}(selector: ${typeName}SelectorUniqueInput!) : ${typeName}Output`; /* ------------------------------------- Mutation Input Types ------------------------------------- */ // note: not currently used /* Type for create mutation input argument type CreateMovieInput { data: CreateMovieDataInput! } */ export const createInputTemplate = ({ typeName }: {typeName: string}) => `input Create${typeName}Input{ data: Create${typeName}DataInput! }`; /* Type for update mutation input argument type UpdateMovieInput { selector: MovieSelectorUniqueInput! data: UpdateMovieDataInput! } */ export const updateInputTemplate = ({ typeName }: {typeName: string}) => `input Update${typeName}Input{ selector: ${typeName}SelectorUniqueInput! data: Update${typeName}DataInput! }`; /* Type for upsert mutation input argument Note: upsertInputTemplate uses same data type as updateInputTemplate type UpsertMovieInput { selector: MovieSelectorUniqueInput! data: UpdateMovieDataInput! } */ export const upsertInputTemplate = ({ typeName }: {typeName: string}) => `input Upsert${typeName}Input{ selector: ${typeName}SelectorUniqueInput! data: Update${typeName}DataInput! }`; /* Type for delete mutation input argument type DeleteMovieInput { selector: MovieSelectorUniqueInput! } */ export const deleteInputTemplate = ({ typeName }: {typeName: string}) => `input Delete${typeName}Input{ selector: ${typeName}SelectorUniqueInput! }`; /* Type for the create mutation input argument's data property type CreateMovieDataInput { title: String description: String } */ export const createDataInputTemplate = ({ typeName, fields }: { typeName: string, fields: SchemaGraphQLFieldDescription[] }) => `input Create${typeName}DataInput { ${convertToGraphQL(fields, ' ')} }`; /* Type for the update mutation input argument's data property type UpdateMovieDataInput { title: String description: String } */ export const updateDataInputTemplate = ({ typeName, fields }: { typeName: string, fields: SchemaGraphQLFieldDescription[] }) => `input Update${typeName}DataInput { ${convertToGraphQL(fields, ' ')} }`; /* ------------------------------------- Mutation Output Type ------------------------------------- */ /* Type for the return value of all mutations type MovieOutput { data: Movie } */ export const mutationOutputTemplate = ({ typeName }: {typeName: string}) => `type ${typeName}Output{ data: ${typeName} }`; /* ------------------------------------- Mutation Queries ------------------------------------- */ /* Upsert mutation query used on the client mutation upsertMovie($selector: MovieSelectorUniqueInput!, $data: UpdateMovieDataInput!) { upsertMovie(selector: $selector, data: $data) { data { _id name __typename } __typename } } */ export const upsertClientTemplate = ({ typeName, fragmentName, extraVariablesString }: { typeName: string, fragmentName: string, extraVariablesString?: string, }) => `mutation upsert${typeName}($selector: ${typeName}SelectorUniqueInput!, $data: Update${typeName}DataInput!, ${extraVariablesString || ''}) { upsert${typeName}(selector: $selector, data: $data) { data { ...${fragmentName} } } }`;
the_stack
* This file was automatically 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 **/ gapi.load('client', () => { /** now we can use gapi.client */ gapi.client.load('dfareporting', 'v2.8', () => { /** now we can use gapi.client.dfareporting */ /** don't forget to authenticate your client before sending any request to resources: */ /** declare client_id registered in Google Developers Console */ const client_id = '<<PUT YOUR CLIENT ID HERE>>'; const scope = [ /** Manage DoubleClick Digital Marketing conversions */ 'https://www.googleapis.com/auth/ddmconversions', /** View and manage DoubleClick for Advertisers reports */ 'https://www.googleapis.com/auth/dfareporting', /** View and manage your DoubleClick Campaign Manager's (DCM) display ad campaigns */ 'https://www.googleapis.com/auth/dfatrafficking', ]; const immediate = true; gapi.auth.authorize({ client_id, scope, immediate }, authResult => { if (authResult && !authResult.error) { /** handle succesfull authorization */ run(); } else { /** handle authorization error */ } }); run(); }); async function run() { /** Gets the account's active ad summary by account ID. */ await gapi.client.accountActiveAdSummaries.get({ profileId: "profileId", summaryAccountId: "summaryAccountId", }); /** Gets one account permission group by ID. */ await gapi.client.accountPermissionGroups.get({ id: "id", profileId: "profileId", }); /** Retrieves the list of account permission groups. */ await gapi.client.accountPermissionGroups.list({ profileId: "profileId", }); /** Gets one account permission by ID. */ await gapi.client.accountPermissions.get({ id: "id", profileId: "profileId", }); /** Retrieves the list of account permissions. */ await gapi.client.accountPermissions.list({ profileId: "profileId", }); /** Gets one account user profile by ID. */ await gapi.client.accountUserProfiles.get({ id: "id", profileId: "profileId", }); /** Inserts a new account user profile. */ await gapi.client.accountUserProfiles.insert({ profileId: "profileId", }); /** Retrieves a list of account user profiles, possibly filtered. This method supports paging. */ await gapi.client.accountUserProfiles.list({ active: true, ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", subaccountId: "subaccountId", userRoleId: "userRoleId", }); /** Updates an existing account user profile. This method supports patch semantics. */ await gapi.client.accountUserProfiles.patch({ id: "id", profileId: "profileId", }); /** Updates an existing account user profile. */ await gapi.client.accountUserProfiles.update({ profileId: "profileId", }); /** Gets one account by ID. */ await gapi.client.accounts.get({ id: "id", profileId: "profileId", }); /** Retrieves the list of accounts, possibly filtered. This method supports paging. */ await gapi.client.accounts.list({ active: true, ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing account. This method supports patch semantics. */ await gapi.client.accounts.patch({ id: "id", profileId: "profileId", }); /** Updates an existing account. */ await gapi.client.accounts.update({ profileId: "profileId", }); /** Gets one ad by ID. */ await gapi.client.ads.get({ id: "id", profileId: "profileId", }); /** Inserts a new ad. */ await gapi.client.ads.insert({ profileId: "profileId", }); /** Retrieves a list of ads, possibly filtered. This method supports paging. */ await gapi.client.ads.list({ active: true, advertiserId: "advertiserId", archived: true, audienceSegmentIds: "audienceSegmentIds", campaignIds: "campaignIds", compatibility: "compatibility", creativeIds: "creativeIds", creativeOptimizationConfigurationIds: "creativeOptimizationConfigurationIds", dynamicClickTracker: true, ids: "ids", landingPageIds: "landingPageIds", maxResults: 12, overriddenEventTagId: "overriddenEventTagId", pageToken: "pageToken", placementIds: "placementIds", profileId: "profileId", remarketingListIds: "remarketingListIds", searchString: "searchString", sizeIds: "sizeIds", sortField: "sortField", sortOrder: "sortOrder", sslCompliant: true, sslRequired: true, type: "type", }); /** Updates an existing ad. This method supports patch semantics. */ await gapi.client.ads.patch({ id: "id", profileId: "profileId", }); /** Updates an existing ad. */ await gapi.client.ads.update({ profileId: "profileId", }); /** Deletes an existing advertiser group. */ await gapi.client.advertiserGroups.delete({ id: "id", profileId: "profileId", }); /** Gets one advertiser group by ID. */ await gapi.client.advertiserGroups.get({ id: "id", profileId: "profileId", }); /** Inserts a new advertiser group. */ await gapi.client.advertiserGroups.insert({ profileId: "profileId", }); /** Retrieves a list of advertiser groups, possibly filtered. This method supports paging. */ await gapi.client.advertiserGroups.list({ ids: "ids", maxResults: 2, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing advertiser group. This method supports patch semantics. */ await gapi.client.advertiserGroups.patch({ id: "id", profileId: "profileId", }); /** Updates an existing advertiser group. */ await gapi.client.advertiserGroups.update({ profileId: "profileId", }); /** Gets one advertiser by ID. */ await gapi.client.advertisers.get({ id: "id", profileId: "profileId", }); /** Inserts a new advertiser. */ await gapi.client.advertisers.insert({ profileId: "profileId", }); /** Retrieves a list of advertisers, possibly filtered. This method supports paging. */ await gapi.client.advertisers.list({ advertiserGroupIds: "advertiserGroupIds", floodlightConfigurationIds: "floodlightConfigurationIds", ids: "ids", includeAdvertisersWithoutGroupsOnly: true, maxResults: 5, onlyParent: true, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", status: "status", subaccountId: "subaccountId", }); /** Updates an existing advertiser. This method supports patch semantics. */ await gapi.client.advertisers.patch({ id: "id", profileId: "profileId", }); /** Updates an existing advertiser. */ await gapi.client.advertisers.update({ profileId: "profileId", }); /** Retrieves a list of browsers. */ await gapi.client.browsers.list({ profileId: "profileId", }); /** * Associates a creative with the specified campaign. This method creates a default ad with dimensions matching the creative in the campaign if such a * default ad does not exist already. */ await gapi.client.campaignCreativeAssociations.insert({ campaignId: "campaignId", profileId: "profileId", }); /** Retrieves the list of creative IDs associated with the specified campaign. This method supports paging. */ await gapi.client.campaignCreativeAssociations.list({ campaignId: "campaignId", maxResults: 2, pageToken: "pageToken", profileId: "profileId", sortOrder: "sortOrder", }); /** Gets one campaign by ID. */ await gapi.client.campaigns.get({ id: "id", profileId: "profileId", }); /** Inserts a new campaign. */ await gapi.client.campaigns.insert({ defaultLandingPageName: "defaultLandingPageName", defaultLandingPageUrl: "defaultLandingPageUrl", profileId: "profileId", }); /** Retrieves a list of campaigns, possibly filtered. This method supports paging. */ await gapi.client.campaigns.list({ advertiserGroupIds: "advertiserGroupIds", advertiserIds: "advertiserIds", archived: true, atLeastOneOptimizationActivity: true, excludedIds: "excludedIds", ids: "ids", maxResults: 7, overriddenEventTagId: "overriddenEventTagId", pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", subaccountId: "subaccountId", }); /** Updates an existing campaign. This method supports patch semantics. */ await gapi.client.campaigns.patch({ id: "id", profileId: "profileId", }); /** Updates an existing campaign. */ await gapi.client.campaigns.update({ profileId: "profileId", }); /** Gets one change log by ID. */ await gapi.client.changeLogs.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of change logs. This method supports paging. */ await gapi.client.changeLogs.list({ action: "action", ids: "ids", maxChangeTime: "maxChangeTime", maxResults: 4, minChangeTime: "minChangeTime", objectIds: "objectIds", objectType: "objectType", pageToken: "pageToken", profileId: "profileId", searchString: "searchString", userProfileIds: "userProfileIds", }); /** Retrieves a list of cities, possibly filtered. */ await gapi.client.cities.list({ countryDartIds: "countryDartIds", dartIds: "dartIds", namePrefix: "namePrefix", profileId: "profileId", regionDartIds: "regionDartIds", }); /** Gets one connection type by ID. */ await gapi.client.connectionTypes.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of connection types. */ await gapi.client.connectionTypes.list({ profileId: "profileId", }); /** Deletes an existing content category. */ await gapi.client.contentCategories.delete({ id: "id", profileId: "profileId", }); /** Gets one content category by ID. */ await gapi.client.contentCategories.get({ id: "id", profileId: "profileId", }); /** Inserts a new content category. */ await gapi.client.contentCategories.insert({ profileId: "profileId", }); /** Retrieves a list of content categories, possibly filtered. This method supports paging. */ await gapi.client.contentCategories.list({ ids: "ids", maxResults: 2, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing content category. This method supports patch semantics. */ await gapi.client.contentCategories.patch({ id: "id", profileId: "profileId", }); /** Updates an existing content category. */ await gapi.client.contentCategories.update({ profileId: "profileId", }); /** Inserts conversions. */ await gapi.client.conversions.batchinsert({ profileId: "profileId", }); /** Updates existing conversions. */ await gapi.client.conversions.batchupdate({ profileId: "profileId", }); /** Gets one country by ID. */ await gapi.client.countries.get({ dartId: "dartId", profileId: "profileId", }); /** Retrieves a list of countries. */ await gapi.client.countries.list({ profileId: "profileId", }); /** Inserts a new creative asset. */ await gapi.client.creativeAssets.insert({ advertiserId: "advertiserId", profileId: "profileId", }); /** Deletes an existing creative field value. */ await gapi.client.creativeFieldValues.delete({ creativeFieldId: "creativeFieldId", id: "id", profileId: "profileId", }); /** Gets one creative field value by ID. */ await gapi.client.creativeFieldValues.get({ creativeFieldId: "creativeFieldId", id: "id", profileId: "profileId", }); /** Inserts a new creative field value. */ await gapi.client.creativeFieldValues.insert({ creativeFieldId: "creativeFieldId", profileId: "profileId", }); /** Retrieves a list of creative field values, possibly filtered. This method supports paging. */ await gapi.client.creativeFieldValues.list({ creativeFieldId: "creativeFieldId", ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing creative field value. This method supports patch semantics. */ await gapi.client.creativeFieldValues.patch({ creativeFieldId: "creativeFieldId", id: "id", profileId: "profileId", }); /** Updates an existing creative field value. */ await gapi.client.creativeFieldValues.update({ creativeFieldId: "creativeFieldId", profileId: "profileId", }); /** Deletes an existing creative field. */ await gapi.client.creativeFields.delete({ id: "id", profileId: "profileId", }); /** Gets one creative field by ID. */ await gapi.client.creativeFields.get({ id: "id", profileId: "profileId", }); /** Inserts a new creative field. */ await gapi.client.creativeFields.insert({ profileId: "profileId", }); /** Retrieves a list of creative fields, possibly filtered. This method supports paging. */ await gapi.client.creativeFields.list({ advertiserIds: "advertiserIds", ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing creative field. This method supports patch semantics. */ await gapi.client.creativeFields.patch({ id: "id", profileId: "profileId", }); /** Updates an existing creative field. */ await gapi.client.creativeFields.update({ profileId: "profileId", }); /** Gets one creative group by ID. */ await gapi.client.creativeGroups.get({ id: "id", profileId: "profileId", }); /** Inserts a new creative group. */ await gapi.client.creativeGroups.insert({ profileId: "profileId", }); /** Retrieves a list of creative groups, possibly filtered. This method supports paging. */ await gapi.client.creativeGroups.list({ advertiserIds: "advertiserIds", groupNumber: 2, ids: "ids", maxResults: 4, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing creative group. This method supports patch semantics. */ await gapi.client.creativeGroups.patch({ id: "id", profileId: "profileId", }); /** Updates an existing creative group. */ await gapi.client.creativeGroups.update({ profileId: "profileId", }); /** Gets one creative by ID. */ await gapi.client.creatives.get({ id: "id", profileId: "profileId", }); /** Inserts a new creative. */ await gapi.client.creatives.insert({ profileId: "profileId", }); /** Retrieves a list of creatives, possibly filtered. This method supports paging. */ await gapi.client.creatives.list({ active: true, advertiserId: "advertiserId", archived: true, campaignId: "campaignId", companionCreativeIds: "companionCreativeIds", creativeFieldIds: "creativeFieldIds", ids: "ids", maxResults: 8, pageToken: "pageToken", profileId: "profileId", renderingIds: "renderingIds", searchString: "searchString", sizeIds: "sizeIds", sortField: "sortField", sortOrder: "sortOrder", studioCreativeId: "studioCreativeId", types: "types", }); /** Updates an existing creative. This method supports patch semantics. */ await gapi.client.creatives.patch({ id: "id", profileId: "profileId", }); /** Updates an existing creative. */ await gapi.client.creatives.update({ profileId: "profileId", }); /** Retrieves list of report dimension values for a list of filters. */ await gapi.client.dimensionValues.query({ maxResults: 1, pageToken: "pageToken", profileId: "profileId", }); /** Gets one directory site contact by ID. */ await gapi.client.directorySiteContacts.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of directory site contacts, possibly filtered. This method supports paging. */ await gapi.client.directorySiteContacts.list({ directorySiteIds: "directorySiteIds", ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Gets one directory site by ID. */ await gapi.client.directorySites.get({ id: "id", profileId: "profileId", }); /** Inserts a new directory site. */ await gapi.client.directorySites.insert({ profileId: "profileId", }); /** Retrieves a list of directory sites, possibly filtered. This method supports paging. */ await gapi.client.directorySites.list({ acceptsInStreamVideoPlacements: true, acceptsInterstitialPlacements: true, acceptsPublisherPaidPlacements: true, active: true, countryId: "countryId", dfpNetworkCode: "dfpNetworkCode", ids: "ids", maxResults: 8, pageToken: "pageToken", parentId: "parentId", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Deletes an existing dynamic targeting key. */ await gapi.client.dynamicTargetingKeys.delete({ name: "name", objectId: "objectId", objectType: "objectType", profileId: "profileId", }); /** * Inserts a new dynamic targeting key. Keys must be created at the advertiser level before being assigned to the advertiser's ads, creatives, or * placements. There is a maximum of 1000 keys per advertiser, out of which a maximum of 20 keys can be assigned per ad, creative, or placement. */ await gapi.client.dynamicTargetingKeys.insert({ profileId: "profileId", }); /** Retrieves a list of dynamic targeting keys. */ await gapi.client.dynamicTargetingKeys.list({ advertiserId: "advertiserId", names: "names", objectId: "objectId", objectType: "objectType", profileId: "profileId", }); /** Deletes an existing event tag. */ await gapi.client.eventTags.delete({ id: "id", profileId: "profileId", }); /** Gets one event tag by ID. */ await gapi.client.eventTags.get({ id: "id", profileId: "profileId", }); /** Inserts a new event tag. */ await gapi.client.eventTags.insert({ profileId: "profileId", }); /** Retrieves a list of event tags, possibly filtered. */ await gapi.client.eventTags.list({ adId: "adId", advertiserId: "advertiserId", campaignId: "campaignId", definitionsOnly: true, enabled: true, eventTagTypes: "eventTagTypes", ids: "ids", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing event tag. This method supports patch semantics. */ await gapi.client.eventTags.patch({ id: "id", profileId: "profileId", }); /** Updates an existing event tag. */ await gapi.client.eventTags.update({ profileId: "profileId", }); /** Retrieves a report file by its report ID and file ID. This method supports media download. */ await gapi.client.files.get({ fileId: "fileId", reportId: "reportId", }); /** Lists files for a user profile. */ await gapi.client.files.list({ maxResults: 1, pageToken: "pageToken", profileId: "profileId", scope: "scope", sortField: "sortField", sortOrder: "sortOrder", }); /** Deletes an existing floodlight activity. */ await gapi.client.floodlightActivities.delete({ id: "id", profileId: "profileId", }); /** Generates a tag for a floodlight activity. */ await gapi.client.floodlightActivities.generatetag({ floodlightActivityId: "floodlightActivityId", profileId: "profileId", }); /** Gets one floodlight activity by ID. */ await gapi.client.floodlightActivities.get({ id: "id", profileId: "profileId", }); /** Inserts a new floodlight activity. */ await gapi.client.floodlightActivities.insert({ profileId: "profileId", }); /** Retrieves a list of floodlight activities, possibly filtered. This method supports paging. */ await gapi.client.floodlightActivities.list({ advertiserId: "advertiserId", floodlightActivityGroupIds: "floodlightActivityGroupIds", floodlightActivityGroupName: "floodlightActivityGroupName", floodlightActivityGroupTagString: "floodlightActivityGroupTagString", floodlightActivityGroupType: "floodlightActivityGroupType", floodlightConfigurationId: "floodlightConfigurationId", ids: "ids", maxResults: 8, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", tagString: "tagString", }); /** Updates an existing floodlight activity. This method supports patch semantics. */ await gapi.client.floodlightActivities.patch({ id: "id", profileId: "profileId", }); /** Updates an existing floodlight activity. */ await gapi.client.floodlightActivities.update({ profileId: "profileId", }); /** Gets one floodlight activity group by ID. */ await gapi.client.floodlightActivityGroups.get({ id: "id", profileId: "profileId", }); /** Inserts a new floodlight activity group. */ await gapi.client.floodlightActivityGroups.insert({ profileId: "profileId", }); /** Retrieves a list of floodlight activity groups, possibly filtered. This method supports paging. */ await gapi.client.floodlightActivityGroups.list({ advertiserId: "advertiserId", floodlightConfigurationId: "floodlightConfigurationId", ids: "ids", maxResults: 4, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", type: "type", }); /** Updates an existing floodlight activity group. This method supports patch semantics. */ await gapi.client.floodlightActivityGroups.patch({ id: "id", profileId: "profileId", }); /** Updates an existing floodlight activity group. */ await gapi.client.floodlightActivityGroups.update({ profileId: "profileId", }); /** Gets one floodlight configuration by ID. */ await gapi.client.floodlightConfigurations.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of floodlight configurations, possibly filtered. */ await gapi.client.floodlightConfigurations.list({ ids: "ids", profileId: "profileId", }); /** Updates an existing floodlight configuration. This method supports patch semantics. */ await gapi.client.floodlightConfigurations.patch({ id: "id", profileId: "profileId", }); /** Updates an existing floodlight configuration. */ await gapi.client.floodlightConfigurations.update({ profileId: "profileId", }); /** Gets one inventory item by ID. */ await gapi.client.inventoryItems.get({ id: "id", profileId: "profileId", projectId: "projectId", }); /** Retrieves a list of inventory items, possibly filtered. This method supports paging. */ await gapi.client.inventoryItems.list({ ids: "ids", inPlan: true, maxResults: 3, orderId: "orderId", pageToken: "pageToken", profileId: "profileId", projectId: "projectId", siteId: "siteId", sortField: "sortField", sortOrder: "sortOrder", type: "type", }); /** Deletes an existing campaign landing page. */ await gapi.client.landingPages.delete({ campaignId: "campaignId", id: "id", profileId: "profileId", }); /** Gets one campaign landing page by ID. */ await gapi.client.landingPages.get({ campaignId: "campaignId", id: "id", profileId: "profileId", }); /** Inserts a new landing page for the specified campaign. */ await gapi.client.landingPages.insert({ campaignId: "campaignId", profileId: "profileId", }); /** Retrieves the list of landing pages for the specified campaign. */ await gapi.client.landingPages.list({ campaignId: "campaignId", profileId: "profileId", }); /** Updates an existing campaign landing page. This method supports patch semantics. */ await gapi.client.landingPages.patch({ campaignId: "campaignId", id: "id", profileId: "profileId", }); /** Updates an existing campaign landing page. */ await gapi.client.landingPages.update({ campaignId: "campaignId", profileId: "profileId", }); /** Retrieves a list of languages. */ await gapi.client.languages.list({ profileId: "profileId", }); /** Retrieves a list of metros. */ await gapi.client.metros.list({ profileId: "profileId", }); /** Gets one mobile carrier by ID. */ await gapi.client.mobileCarriers.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of mobile carriers. */ await gapi.client.mobileCarriers.list({ profileId: "profileId", }); /** Gets one operating system version by ID. */ await gapi.client.operatingSystemVersions.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of operating system versions. */ await gapi.client.operatingSystemVersions.list({ profileId: "profileId", }); /** Gets one operating system by DART ID. */ await gapi.client.operatingSystems.get({ dartId: "dartId", profileId: "profileId", }); /** Retrieves a list of operating systems. */ await gapi.client.operatingSystems.list({ profileId: "profileId", }); /** Gets one order document by ID. */ await gapi.client.orderDocuments.get({ id: "id", profileId: "profileId", projectId: "projectId", }); /** Retrieves a list of order documents, possibly filtered. This method supports paging. */ await gapi.client.orderDocuments.list({ approved: true, ids: "ids", maxResults: 3, orderId: "orderId", pageToken: "pageToken", profileId: "profileId", projectId: "projectId", searchString: "searchString", siteId: "siteId", sortField: "sortField", sortOrder: "sortOrder", }); /** Gets one order by ID. */ await gapi.client.orders.get({ id: "id", profileId: "profileId", projectId: "projectId", }); /** Retrieves a list of orders, possibly filtered. This method supports paging. */ await gapi.client.orders.list({ ids: "ids", maxResults: 2, pageToken: "pageToken", profileId: "profileId", projectId: "projectId", searchString: "searchString", siteId: "siteId", sortField: "sortField", sortOrder: "sortOrder", }); /** Gets one placement group by ID. */ await gapi.client.placementGroups.get({ id: "id", profileId: "profileId", }); /** Inserts a new placement group. */ await gapi.client.placementGroups.insert({ profileId: "profileId", }); /** Retrieves a list of placement groups, possibly filtered. This method supports paging. */ await gapi.client.placementGroups.list({ advertiserIds: "advertiserIds", archived: true, campaignIds: "campaignIds", contentCategoryIds: "contentCategoryIds", directorySiteIds: "directorySiteIds", ids: "ids", maxEndDate: "maxEndDate", maxResults: 8, maxStartDate: "maxStartDate", minEndDate: "minEndDate", minStartDate: "minStartDate", pageToken: "pageToken", placementGroupType: "placementGroupType", placementStrategyIds: "placementStrategyIds", pricingTypes: "pricingTypes", profileId: "profileId", searchString: "searchString", siteIds: "siteIds", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing placement group. This method supports patch semantics. */ await gapi.client.placementGroups.patch({ id: "id", profileId: "profileId", }); /** Updates an existing placement group. */ await gapi.client.placementGroups.update({ profileId: "profileId", }); /** Deletes an existing placement strategy. */ await gapi.client.placementStrategies.delete({ id: "id", profileId: "profileId", }); /** Gets one placement strategy by ID. */ await gapi.client.placementStrategies.get({ id: "id", profileId: "profileId", }); /** Inserts a new placement strategy. */ await gapi.client.placementStrategies.insert({ profileId: "profileId", }); /** Retrieves a list of placement strategies, possibly filtered. This method supports paging. */ await gapi.client.placementStrategies.list({ ids: "ids", maxResults: 2, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing placement strategy. This method supports patch semantics. */ await gapi.client.placementStrategies.patch({ id: "id", profileId: "profileId", }); /** Updates an existing placement strategy. */ await gapi.client.placementStrategies.update({ profileId: "profileId", }); /** Generates tags for a placement. */ await gapi.client.placements.generatetags({ campaignId: "campaignId", placementIds: "placementIds", profileId: "profileId", tagFormats: "tagFormats", }); /** Gets one placement by ID. */ await gapi.client.placements.get({ id: "id", profileId: "profileId", }); /** Inserts a new placement. */ await gapi.client.placements.insert({ profileId: "profileId", }); /** Retrieves a list of placements, possibly filtered. This method supports paging. */ await gapi.client.placements.list({ advertiserIds: "advertiserIds", archived: true, campaignIds: "campaignIds", compatibilities: "compatibilities", contentCategoryIds: "contentCategoryIds", directorySiteIds: "directorySiteIds", groupIds: "groupIds", ids: "ids", maxEndDate: "maxEndDate", maxResults: 10, maxStartDate: "maxStartDate", minEndDate: "minEndDate", minStartDate: "minStartDate", pageToken: "pageToken", paymentSource: "paymentSource", placementStrategyIds: "placementStrategyIds", pricingTypes: "pricingTypes", profileId: "profileId", searchString: "searchString", siteIds: "siteIds", sizeIds: "sizeIds", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing placement. This method supports patch semantics. */ await gapi.client.placements.patch({ id: "id", profileId: "profileId", }); /** Updates an existing placement. */ await gapi.client.placements.update({ profileId: "profileId", }); /** Gets one platform type by ID. */ await gapi.client.platformTypes.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of platform types. */ await gapi.client.platformTypes.list({ profileId: "profileId", }); /** Gets one postal code by ID. */ await gapi.client.postalCodes.get({ code: "code", profileId: "profileId", }); /** Retrieves a list of postal codes. */ await gapi.client.postalCodes.list({ profileId: "profileId", }); /** Gets one project by ID. */ await gapi.client.projects.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of projects, possibly filtered. This method supports paging. */ await gapi.client.projects.list({ advertiserIds: "advertiserIds", ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Retrieves a list of regions. */ await gapi.client.regions.list({ profileId: "profileId", }); /** Gets one remarketing list share by remarketing list ID. */ await gapi.client.remarketingListShares.get({ profileId: "profileId", remarketingListId: "remarketingListId", }); /** Updates an existing remarketing list share. This method supports patch semantics. */ await gapi.client.remarketingListShares.patch({ profileId: "profileId", remarketingListId: "remarketingListId", }); /** Updates an existing remarketing list share. */ await gapi.client.remarketingListShares.update({ profileId: "profileId", }); /** Gets one remarketing list by ID. */ await gapi.client.remarketingLists.get({ id: "id", profileId: "profileId", }); /** Inserts a new remarketing list. */ await gapi.client.remarketingLists.insert({ profileId: "profileId", }); /** Retrieves a list of remarketing lists, possibly filtered. This method supports paging. */ await gapi.client.remarketingLists.list({ active: true, advertiserId: "advertiserId", floodlightActivityId: "floodlightActivityId", maxResults: 4, name: "name", pageToken: "pageToken", profileId: "profileId", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing remarketing list. This method supports patch semantics. */ await gapi.client.remarketingLists.patch({ id: "id", profileId: "profileId", }); /** Updates an existing remarketing list. */ await gapi.client.remarketingLists.update({ profileId: "profileId", }); /** Deletes a report by its ID. */ await gapi.client.reports.delete({ profileId: "profileId", reportId: "reportId", }); /** Retrieves a report by its ID. */ await gapi.client.reports.get({ profileId: "profileId", reportId: "reportId", }); /** Creates a report. */ await gapi.client.reports.insert({ profileId: "profileId", }); /** Retrieves list of reports. */ await gapi.client.reports.list({ maxResults: 1, pageToken: "pageToken", profileId: "profileId", scope: "scope", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates a report. This method supports patch semantics. */ await gapi.client.reports.patch({ profileId: "profileId", reportId: "reportId", }); /** Runs a report. */ await gapi.client.reports.run({ profileId: "profileId", reportId: "reportId", synchronous: true, }); /** Updates a report. */ await gapi.client.reports.update({ profileId: "profileId", reportId: "reportId", }); /** Gets one site by ID. */ await gapi.client.sites.get({ id: "id", profileId: "profileId", }); /** Inserts a new site. */ await gapi.client.sites.insert({ profileId: "profileId", }); /** Retrieves a list of sites, possibly filtered. This method supports paging. */ await gapi.client.sites.list({ acceptsInStreamVideoPlacements: true, acceptsInterstitialPlacements: true, acceptsPublisherPaidPlacements: true, adWordsSite: true, approved: true, campaignIds: "campaignIds", directorySiteIds: "directorySiteIds", ids: "ids", maxResults: 9, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", subaccountId: "subaccountId", unmappedSite: true, }); /** Updates an existing site. This method supports patch semantics. */ await gapi.client.sites.patch({ id: "id", profileId: "profileId", }); /** Updates an existing site. */ await gapi.client.sites.update({ profileId: "profileId", }); /** Gets one size by ID. */ await gapi.client.sizes.get({ id: "id", profileId: "profileId", }); /** Inserts a new size. */ await gapi.client.sizes.insert({ profileId: "profileId", }); /** Retrieves a list of sizes, possibly filtered. */ await gapi.client.sizes.list({ height: 1, iabStandard: true, ids: "ids", profileId: "profileId", width: 5, }); /** Gets one subaccount by ID. */ await gapi.client.subaccounts.get({ id: "id", profileId: "profileId", }); /** Inserts a new subaccount. */ await gapi.client.subaccounts.insert({ profileId: "profileId", }); /** Gets a list of subaccounts, possibly filtered. This method supports paging. */ await gapi.client.subaccounts.list({ ids: "ids", maxResults: 2, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing subaccount. This method supports patch semantics. */ await gapi.client.subaccounts.patch({ id: "id", profileId: "profileId", }); /** Updates an existing subaccount. */ await gapi.client.subaccounts.update({ profileId: "profileId", }); /** Gets one remarketing list by ID. */ await gapi.client.targetableRemarketingLists.get({ id: "id", profileId: "profileId", }); /** Retrieves a list of targetable remarketing lists, possibly filtered. This method supports paging. */ await gapi.client.targetableRemarketingLists.list({ active: true, advertiserId: "advertiserId", maxResults: 3, name: "name", pageToken: "pageToken", profileId: "profileId", sortField: "sortField", sortOrder: "sortOrder", }); /** Gets one targeting template by ID. */ await gapi.client.targetingTemplates.get({ id: "id", profileId: "profileId", }); /** Inserts a new targeting template. */ await gapi.client.targetingTemplates.insert({ profileId: "profileId", }); /** Retrieves a list of targeting templates, optionally filtered. This method supports paging. */ await gapi.client.targetingTemplates.list({ advertiserId: "advertiserId", ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", }); /** Updates an existing targeting template. This method supports patch semantics. */ await gapi.client.targetingTemplates.patch({ id: "id", profileId: "profileId", }); /** Updates an existing targeting template. */ await gapi.client.targetingTemplates.update({ profileId: "profileId", }); /** Gets one user profile by ID. */ await gapi.client.userProfiles.get({ profileId: "profileId", }); /** Retrieves list of user profiles for a user. */ await gapi.client.userProfiles.list({ }); /** Gets one user role permission group by ID. */ await gapi.client.userRolePermissionGroups.get({ id: "id", profileId: "profileId", }); /** Gets a list of all supported user role permission groups. */ await gapi.client.userRolePermissionGroups.list({ profileId: "profileId", }); /** Gets one user role permission by ID. */ await gapi.client.userRolePermissions.get({ id: "id", profileId: "profileId", }); /** Gets a list of user role permissions, possibly filtered. */ await gapi.client.userRolePermissions.list({ ids: "ids", profileId: "profileId", }); /** Deletes an existing user role. */ await gapi.client.userRoles.delete({ id: "id", profileId: "profileId", }); /** Gets one user role by ID. */ await gapi.client.userRoles.get({ id: "id", profileId: "profileId", }); /** Inserts a new user role. */ await gapi.client.userRoles.insert({ profileId: "profileId", }); /** Retrieves a list of user roles, possibly filtered. This method supports paging. */ await gapi.client.userRoles.list({ accountUserRoleOnly: true, ids: "ids", maxResults: 3, pageToken: "pageToken", profileId: "profileId", searchString: "searchString", sortField: "sortField", sortOrder: "sortOrder", subaccountId: "subaccountId", }); /** Updates an existing user role. This method supports patch semantics. */ await gapi.client.userRoles.patch({ id: "id", profileId: "profileId", }); /** Updates an existing user role. */ await gapi.client.userRoles.update({ profileId: "profileId", }); /** Gets one video format by ID. */ await gapi.client.videoFormats.get({ id: 1, profileId: "profileId", }); /** Lists available video formats. */ await gapi.client.videoFormats.list({ profileId: "profileId", }); } });
the_stack
export type Char = | "\x00" | "\x01" | "\x02" | "\x03" | "\x04" | "\x05" | "\x06" | "\x07" | "\x08" | "\x09" | "\x0A" | "\x0B" | "\x0C" | "\x0D" | "\x0E" | "\x0F" | "\x10" | "\x11" | "\x12" | "\x13" | "\x14" | "\x15" | "\x16" | "\x17" | "\x18" | "\x19" | "\x1A" | "\x1B" | "\x1C" | "\x1D" | "\x1E" | "\x1F" | "\x20" | "\x21" | "\x22" | "\x23" | "\x24" | "\x25" | "\x26" | "\x27" | "\x28" | "\x29" | "\x2A" | "\x2B" | "\x2C" | "\x2D" | "\x2E" | "\x2F" | "\x30" | "\x31" | "\x32" | "\x33" | "\x34" | "\x35" | "\x36" | "\x37" | "\x38" | "\x39" | "\x3A" | "\x3B" | "\x3C" | "\x3D" | "\x3E" | "\x3F" | "\x40" | "\x41" | "\x42" | "\x43" | "\x44" | "\x45" | "\x46" | "\x47" | "\x48" | "\x49" | "\x4A" | "\x4B" | "\x4C" | "\x4D" | "\x4E" | "\x4F" | "\x50" | "\x51" | "\x52" | "\x53" | "\x54" | "\x55" | "\x56" | "\x57" | "\x58" | "\x59" | "\x5A" | "\x5B" | "\x5C" | "\x5D" | "\x5E" | "\x5F" | "\x60" | "\x61" | "\x62" | "\x63" | "\x64" | "\x65" | "\x66" | "\x67" | "\x68" | "\x69" | "\x6A" | "\x6B" | "\x6C" | "\x6D" | "\x6E" | "\x6F" | "\x70" | "\x71" | "\x72" | "\x73" | "\x74" | "\x75" | "\x76" | "\x77" | "\x78" | "\x79" | "\x7A" | "\x7B" | "\x7C" | "\x7D" | "\x7E" | "\x7F" | "\x80" | "\x81" | "\x82" | "\x83" | "\x84" | "\x85" | "\x86" | "\x87" | "\x88" | "\x89" | "\x8A" | "\x8B" | "\x8C" | "\x8D" | "\x8E" | "\x8F" | "\x90" | "\x91" | "\x92" | "\x93" | "\x94" | "\x95" | "\x96" | "\x97" | "\x98" | "\x99" | "\x9A" | "\x9B" | "\x9C" | "\x9D" | "\x9E" | "\x9F" | "\xA0" | "\xA1" | "\xA2" | "\xA3" | "\xA4" | "\xA5" | "\xA6" | "\xA7" | "\xA8" | "\xA9" | "\xAA" | "\xAB" | "\xAC" | "\xAD" | "\xAE" | "\xAF" | "\xB0" | "\xB1" | "\xB2" | "\xB3" | "\xB4" | "\xB5" | "\xB6" | "\xB7" | "\xB8" | "\xB9" | "\xBA" | "\xBB" | "\xBC" | "\xBD" | "\xBE" | "\xBF" | "\xC0" | "\xC1" | "\xC2" | "\xC3" | "\xC4" | "\xC5" | "\xC6" | "\xC7" | "\xC8" | "\xC9" | "\xCA" | "\xCB" | "\xCC" | "\xCD" | "\xCE" | "\xCF" | "\xD0" | "\xD1" | "\xD2" | "\xD3" | "\xD4" | "\xD5" | "\xD6" | "\xD7" | "\xD8" | "\xD9" | "\xDA" | "\xDB" | "\xDC" | "\xDD" | "\xDE" | "\xDF" | "\xE0" | "\xE1" | "\xE2" | "\xE3" | "\xE4" | "\xE5" | "\xE6" | "\xE7" | "\xE8" | "\xE9" | "\xEA" | "\xEB" | "\xEC" | "\xED" | "\xEE" | "\xEF" | "\xF0" | "\xF1" | "\xF2" | "\xF3" | "\xF4" | "\xF5" | "\xF6" | "\xF7" | "\xF8" | "\xF9" | "\xFA" | "\xFB" | "\xFC" | "\xFD" | "\xFE" | "\xFF"; // prettier-ignore type Incrs = { "\x00": "\x01", "\x01": "\x02", "\x02": "\x03", "\x03": "\x04", "\x04": "\x05", "\x05": "\x06", "\x06": "\x07", "\x07": "\x08", "\x08": "\x09", "\x09": "\x0A", "\x0A": "\x0B", "\x0B": "\x0C", "\x0C": "\x0D", "\x0D": "\x0E", "\x0E": "\x0F", "\x0F": "\x10", "\x10": "\x11", "\x11": "\x12", "\x12": "\x13", "\x13": "\x14", "\x14": "\x15", "\x15": "\x16", "\x16": "\x17", "\x17": "\x18", "\x18": "\x19", "\x19": "\x1A", "\x1A": "\x1B", "\x1B": "\x1C", "\x1C": "\x1D", "\x1D": "\x1E", "\x1E": "\x1F", "\x1F": "\x20", "\x20": "\x21", "\x21": "\x22", "\x22": "\x23", "\x23": "\x24", "\x24": "\x25", "\x25": "\x26", "\x26": "\x27", "\x27": "\x28", "\x28": "\x29", "\x29": "\x2A", "\x2A": "\x2B", "\x2B": "\x2C", "\x2C": "\x2D", "\x2D": "\x2E", "\x2E": "\x2F", "\x2F": "\x30", "\x30": "\x31", "\x31": "\x32", "\x32": "\x33", "\x33": "\x34", "\x34": "\x35", "\x35": "\x36", "\x36": "\x37", "\x37": "\x38", "\x38": "\x39", "\x39": "\x3A", "\x3A": "\x3B", "\x3B": "\x3C", "\x3C": "\x3D", "\x3D": "\x3E", "\x3E": "\x3F", "\x3F": "\x40", "\x40": "\x41", "\x41": "\x42", "\x42": "\x43", "\x43": "\x44", "\x44": "\x45", "\x45": "\x46", "\x46": "\x47", "\x47": "\x48", "\x48": "\x49", "\x49": "\x4A", "\x4A": "\x4B", "\x4B": "\x4C", "\x4C": "\x4D", "\x4D": "\x4E", "\x4E": "\x4F", "\x4F": "\x50", "\x50": "\x51", "\x51": "\x52", "\x52": "\x53", "\x53": "\x54", "\x54": "\x55", "\x55": "\x56", "\x56": "\x57", "\x57": "\x58", "\x58": "\x59", "\x59": "\x5A", "\x5A": "\x5B", "\x5B": "\x5C", "\x5C": "\x5D", "\x5D": "\x5E", "\x5E": "\x5F", "\x5F": "\x60", "\x60": "\x61", "\x61": "\x62", "\x62": "\x63", "\x63": "\x64", "\x64": "\x65", "\x65": "\x66", "\x66": "\x67", "\x67": "\x68", "\x68": "\x69", "\x69": "\x6A", "\x6A": "\x6B", "\x6B": "\x6C", "\x6C": "\x6D", "\x6D": "\x6E", "\x6E": "\x6F", "\x6F": "\x70", "\x70": "\x71", "\x71": "\x72", "\x72": "\x73", "\x73": "\x74", "\x74": "\x75", "\x75": "\x76", "\x76": "\x77", "\x77": "\x78", "\x78": "\x79", "\x79": "\x7A", "\x7A": "\x7B", "\x7B": "\x7C", "\x7C": "\x7D", "\x7D": "\x7E", "\x7E": "\x7F", "\x7F": "\x80", "\x80": "\x81", "\x81": "\x82", "\x82": "\x83", "\x83": "\x84", "\x84": "\x85", "\x85": "\x86", "\x86": "\x87", "\x87": "\x88", "\x88": "\x89", "\x89": "\x8A", "\x8A": "\x8B", "\x8B": "\x8C", "\x8C": "\x8D", "\x8D": "\x8E", "\x8E": "\x8F", "\x8F": "\x90", "\x90": "\x91", "\x91": "\x92", "\x92": "\x93", "\x93": "\x94", "\x94": "\x95", "\x95": "\x96", "\x96": "\x97", "\x97": "\x98", "\x98": "\x99", "\x99": "\x9A", "\x9A": "\x9B", "\x9B": "\x9C", "\x9C": "\x9D", "\x9D": "\x9E", "\x9E": "\x9F", "\x9F": "\xA0", "\xA0": "\xA1", "\xA1": "\xA2", "\xA2": "\xA3", "\xA3": "\xA4", "\xA4": "\xA5", "\xA5": "\xA6", "\xA6": "\xA7", "\xA7": "\xA8", "\xA8": "\xA9", "\xA9": "\xAA", "\xAA": "\xAB", "\xAB": "\xAC", "\xAC": "\xAD", "\xAD": "\xAE", "\xAE": "\xAF", "\xAF": "\xB0", "\xB0": "\xB1", "\xB1": "\xB2", "\xB2": "\xB3", "\xB3": "\xB4", "\xB4": "\xB5", "\xB5": "\xB6", "\xB6": "\xB7", "\xB7": "\xB8", "\xB8": "\xB9", "\xB9": "\xBA", "\xBA": "\xBB", "\xBB": "\xBC", "\xBC": "\xBD", "\xBD": "\xBE", "\xBE": "\xBF", "\xBF": "\xC0", "\xC0": "\xC1", "\xC1": "\xC2", "\xC2": "\xC3", "\xC3": "\xC4", "\xC4": "\xC5", "\xC5": "\xC6", "\xC6": "\xC7", "\xC7": "\xC8", "\xC8": "\xC9", "\xC9": "\xCA", "\xCA": "\xCB", "\xCB": "\xCC", "\xCC": "\xCD", "\xCD": "\xCE", "\xCE": "\xCF", "\xCF": "\xD0", "\xD0": "\xD1", "\xD1": "\xD2", "\xD2": "\xD3", "\xD3": "\xD4", "\xD4": "\xD5", "\xD5": "\xD6", "\xD6": "\xD7", "\xD7": "\xD8", "\xD8": "\xD9", "\xD9": "\xDA", "\xDA": "\xDB", "\xDB": "\xDC", "\xDC": "\xDD", "\xDD": "\xDE", "\xDE": "\xDF", "\xDF": "\xE0", "\xE0": "\xE1", "\xE1": "\xE2", "\xE2": "\xE3", "\xE3": "\xE4", "\xE4": "\xE5", "\xE5": "\xE6", "\xE6": "\xE7", "\xE7": "\xE8", "\xE8": "\xE9", "\xE9": "\xEA", "\xEA": "\xEB", "\xEB": "\xEC", "\xEC": "\xED", "\xED": "\xEE", "\xEE": "\xEF", "\xEF": "\xF0", "\xF0": "\xF1", "\xF1": "\xF2", "\xF2": "\xF3", "\xF3": "\xF4", "\xF4": "\xF5", "\xF5": "\xF6", "\xF6": "\xF7", "\xF7": "\xF8", "\xF8": "\xF9", "\xF9": "\xFA", "\xFA": "\xFB", "\xFB": "\xFC", "\xFC": "\xFD", "\xFD": "\xFE", "\xFE": "\xFF", "\xFF": "\x00", }; // prettier-ignore type Decrs = { "\x00": "\xFF", "\x01": "\x00", "\x02": "\x01", "\x03": "\x02", "\x04": "\x03", "\x05": "\x04", "\x06": "\x05", "\x07": "\x06", "\x08": "\x07", "\x09": "\x08", "\x0A": "\x09", "\x0B": "\x0A", "\x0C": "\x0B", "\x0D": "\x0C", "\x0E": "\x0D", "\x0F": "\x0E", "\x10": "\x0F", "\x11": "\x10", "\x12": "\x11", "\x13": "\x12", "\x14": "\x13", "\x15": "\x14", "\x16": "\x15", "\x17": "\x16", "\x18": "\x17", "\x19": "\x18", "\x1A": "\x19", "\x1B": "\x1A", "\x1C": "\x1B", "\x1D": "\x1C", "\x1E": "\x1D", "\x1F": "\x1E", "\x20": "\x1F", "\x21": "\x20", "\x22": "\x21", "\x23": "\x22", "\x24": "\x23", "\x25": "\x24", "\x26": "\x25", "\x27": "\x26", "\x28": "\x27", "\x29": "\x28", "\x2A": "\x29", "\x2B": "\x2A", "\x2C": "\x2B", "\x2D": "\x2C", "\x2E": "\x2D", "\x2F": "\x2E", "\x30": "\x2F", "\x31": "\x30", "\x32": "\x31", "\x33": "\x32", "\x34": "\x33", "\x35": "\x34", "\x36": "\x35", "\x37": "\x36", "\x38": "\x37", "\x39": "\x38", "\x3A": "\x39", "\x3B": "\x3A", "\x3C": "\x3B", "\x3D": "\x3C", "\x3E": "\x3D", "\x3F": "\x3E", "\x40": "\x3F", "\x41": "\x40", "\x42": "\x41", "\x43": "\x42", "\x44": "\x43", "\x45": "\x44", "\x46": "\x45", "\x47": "\x46", "\x48": "\x47", "\x49": "\x48", "\x4A": "\x49", "\x4B": "\x4A", "\x4C": "\x4B", "\x4D": "\x4C", "\x4E": "\x4D", "\x4F": "\x4E", "\x50": "\x4F", "\x51": "\x50", "\x52": "\x51", "\x53": "\x52", "\x54": "\x53", "\x55": "\x54", "\x56": "\x55", "\x57": "\x56", "\x58": "\x57", "\x59": "\x58", "\x5A": "\x59", "\x5B": "\x5A", "\x5C": "\x5B", "\x5D": "\x5C", "\x5E": "\x5D", "\x5F": "\x5E", "\x60": "\x5F", "\x61": "\x60", "\x62": "\x61", "\x63": "\x62", "\x64": "\x63", "\x65": "\x64", "\x66": "\x65", "\x67": "\x66", "\x68": "\x67", "\x69": "\x68", "\x6A": "\x69", "\x6B": "\x6A", "\x6C": "\x6B", "\x6D": "\x6C", "\x6E": "\x6D", "\x6F": "\x6E", "\x70": "\x6F", "\x71": "\x70", "\x72": "\x71", "\x73": "\x72", "\x74": "\x73", "\x75": "\x74", "\x76": "\x75", "\x77": "\x76", "\x78": "\x77", "\x79": "\x78", "\x7A": "\x79", "\x7B": "\x7A", "\x7C": "\x7B", "\x7D": "\x7C", "\x7E": "\x7D", "\x7F": "\x7E", "\x80": "\x7F", "\x81": "\x80", "\x82": "\x81", "\x83": "\x82", "\x84": "\x83", "\x85": "\x84", "\x86": "\x85", "\x87": "\x86", "\x88": "\x87", "\x89": "\x88", "\x8A": "\x89", "\x8B": "\x8A", "\x8C": "\x8B", "\x8D": "\x8C", "\x8E": "\x8D", "\x8F": "\x8E", "\x90": "\x8F", "\x91": "\x90", "\x92": "\x91", "\x93": "\x92", "\x94": "\x93", "\x95": "\x94", "\x96": "\x95", "\x97": "\x96", "\x98": "\x97", "\x99": "\x98", "\x9A": "\x99", "\x9B": "\x9A", "\x9C": "\x9B", "\x9D": "\x9C", "\x9E": "\x9D", "\x9F": "\x9E", "\xA0": "\x9F", "\xA1": "\xA0", "\xA2": "\xA1", "\xA3": "\xA2", "\xA4": "\xA3", "\xA5": "\xA4", "\xA6": "\xA5", "\xA7": "\xA6", "\xA8": "\xA7", "\xA9": "\xA8", "\xAA": "\xA9", "\xAB": "\xAA", "\xAC": "\xAB", "\xAD": "\xAC", "\xAE": "\xAD", "\xAF": "\xAE", "\xB0": "\xAF", "\xB1": "\xB0", "\xB2": "\xB1", "\xB3": "\xB2", "\xB4": "\xB3", "\xB5": "\xB4", "\xB6": "\xB5", "\xB7": "\xB6", "\xB8": "\xB7", "\xB9": "\xB8", "\xBA": "\xB9", "\xBB": "\xBA", "\xBC": "\xBB", "\xBD": "\xBC", "\xBE": "\xBD", "\xBF": "\xBE", "\xC0": "\xBF", "\xC1": "\xC0", "\xC2": "\xC1", "\xC3": "\xC2", "\xC4": "\xC3", "\xC5": "\xC4", "\xC6": "\xC5", "\xC7": "\xC6", "\xC8": "\xC7", "\xC9": "\xC8", "\xCA": "\xC9", "\xCB": "\xCA", "\xCC": "\xCB", "\xCD": "\xCC", "\xCE": "\xCD", "\xCF": "\xCE", "\xD0": "\xCF", "\xD1": "\xD0", "\xD2": "\xD1", "\xD3": "\xD2", "\xD4": "\xD3", "\xD5": "\xD4", "\xD6": "\xD5", "\xD7": "\xD6", "\xD8": "\xD7", "\xD9": "\xD8", "\xDA": "\xD9", "\xDB": "\xDA", "\xDC": "\xDB", "\xDD": "\xDC", "\xDE": "\xDD", "\xDF": "\xDE", "\xE0": "\xDF", "\xE1": "\xE0", "\xE2": "\xE1", "\xE3": "\xE2", "\xE4": "\xE3", "\xE5": "\xE4", "\xE6": "\xE5", "\xE7": "\xE6", "\xE8": "\xE7", "\xE9": "\xE8", "\xEA": "\xE9", "\xEB": "\xEA", "\xEC": "\xEB", "\xED": "\xEC", "\xEE": "\xED", "\xEF": "\xEE", "\xF0": "\xEF", "\xF1": "\xF0", "\xF2": "\xF1", "\xF3": "\xF2", "\xF4": "\xF3", "\xF5": "\xF4", "\xF6": "\xF5", "\xF7": "\xF6", "\xF8": "\xF7", "\xF9": "\xF8", "\xFA": "\xF9", "\xFB": "\xFA", "\xFC": "\xFB", "\xFD": "\xFC", "\xFE": "\xFD", "\xFF": "\xFE", }; /** * `Incr<C>` computes the successor of a single-byte character `C`. * If `C` is not a single-byte character, it returns \x00. */ export type Incr<C> = C extends Char ? Incrs[C] : "\x00"; /** * `Decr<C>` computes the predecessor of a single-byte character `C`. * If `C` is not a single-byte character, it returns \x00. */ export type Decr<C> = C extends Char ? Decrs[C] : "\x00";
the_stack
'use strict'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { FontInfo } from 'vs/editor/common/config/fontInfo'; import * as objects from 'vs/base/common/objects'; /** * Configuration options for editor scrollbars */ export interface IEditorScrollbarOptions { /** * The size of arrows (if displayed). * Defaults to 11. */ arrowSize?: number; /** * Render vertical scrollbar. * Accepted values: 'auto', 'visible', 'hidden'. * Defaults to 'auto'. */ vertical?: string; /** * Render horizontal scrollbar. * Accepted values: 'auto', 'visible', 'hidden'. * Defaults to 'auto'. */ horizontal?: string; /** * Cast horizontal and vertical shadows when the content is scrolled. * Defaults to true. */ useShadows?: boolean; /** * Render arrows at the top and bottom of the vertical scrollbar. * Defaults to false. */ verticalHasArrows?: boolean; /** * Render arrows at the left and right of the horizontal scrollbar. * Defaults to false. */ horizontalHasArrows?: boolean; /** * Listen to mouse wheel events and react to them by scrolling. * Defaults to true. */ handleMouseWheel?: boolean; /** * Height in pixels for the horizontal scrollbar. * Defaults to 10 (px). */ horizontalScrollbarSize?: number; /** * Width in pixels for the vertical scrollbar. * Defaults to 10 (px). */ verticalScrollbarSize?: number; /** * Width in pixels for the vertical slider. * Defaults to `verticalScrollbarSize`. */ verticalSliderSize?: number; /** * Height in pixels for the horizontal slider. * Defaults to `horizontalScrollbarSize`. */ horizontalSliderSize?: number; } /** * Configuration options for editor minimap */ export interface IEditorMinimapOptions { /** * Enable the rendering of the minimap. * Defaults to false. */ enabled?: boolean; /** * Render the actual text on a line (as opposed to color blocks). * Defaults to true. */ renderCharacters?: boolean; /** * Limit the width of the minimap to render at most a certain number of columns. * Defaults to 120. */ maxColumn?: number; } export type LineNumbersOption = 'on' | 'off' | 'relative' | ((lineNumber: number) => string); /** * Configuration options for the editor. */ export interface IEditorOptions { /** * This editor is used inside a diff editor. * @internal */ inDiffEditor?: boolean; /** * Enable experimental screen reader support. * Defaults to `true`. */ experimentalScreenReader?: boolean; /** * The aria label for the editor's textarea (when it is focused). */ ariaLabel?: string; /** * Render vertical lines at the specified columns. * Defaults to empty array. */ rulers?: number[]; /** * A string containing the word separators used when doing word navigation. * Defaults to `~!@#$%^&*()-=+[{]}\\|;:\'",.<>/? */ wordSeparators?: string; /** * Enable Linux primary clipboard. * Defaults to true. */ selectionClipboard?: boolean; /** * Control the rendering of line numbers. * If it is a function, it will be invoked when rendering a line number and the return value will be rendered. * Otherwise, if it is a truey, line numbers will be rendered normally (equivalent of using an identity function). * Otherwise, line numbers will not be rendered. * Defaults to true. */ lineNumbers?: LineNumbersOption; /** * Should the corresponding line be selected when clicking on the line number? * Defaults to true. */ selectOnLineNumbers?: boolean; /** * Control the width of line numbers, by reserving horizontal space for rendering at least an amount of digits. * Defaults to 5. */ lineNumbersMinChars?: number; /** * Enable the rendering of the glyph margin. * Defaults to true in vscode and to false in monaco-editor. */ glyphMargin?: boolean; /** * The width reserved for line decorations (in px). * Line decorations are placed between line numbers and the editor content. * You can pass in a string in the format floating point followed by "ch". e.g. 1.3ch. * Defaults to 10. */ lineDecorationsWidth?: number | string; /** * When revealing the cursor, a virtual padding (px) is added to the cursor, turning it into a rectangle. * This virtual padding ensures that the cursor gets revealed before hitting the edge of the viewport. * Defaults to 30 (px). */ revealHorizontalRightPadding?: number; /** * Render the editor selection with rounded borders. * Defaults to true. */ roundedSelection?: boolean; /** * Theme to be used for rendering. * The current out-of-the-box available themes are: 'vs' (default), 'vs-dark', 'hc-black'. * You can create custom themes via `monaco.editor.defineTheme`. */ theme?: string; /** * Should the editor be read only. * Defaults to false. */ readOnly?: boolean; /** * Control the behavior and rendering of the scrollbars. */ scrollbar?: IEditorScrollbarOptions; /** * Control the behavior and rendering of the minimap. */ minimap?: IEditorMinimapOptions; /** * Display overflow widgets as `fixed`. * Defaults to `false`. */ fixedOverflowWidgets?: boolean; /** * The number of vertical lanes the overview ruler should render. * Defaults to 2. */ overviewRulerLanes?: number; /** * Controls if a border should be drawn around the overview ruler. * Defaults to `true`. */ overviewRulerBorder?: boolean; /** * Control the cursor animation style, possible values are 'blink', 'smooth', 'phase', 'expand' and 'solid'. * Defaults to 'blink'. */ cursorBlinking?: string; /** * Zoom the font in the editor when using the mouse wheel in combination with holding Ctrl. * Defaults to false. */ mouseWheelZoom?: boolean; /** * Control the mouse pointer style, either 'text' or 'default' or 'copy' * Defaults to 'text' * @internal */ mouseStyle?: 'text' | 'default' | 'copy'; /** * Control the cursor style, either 'block' or 'line'. * Defaults to 'line'. */ cursorStyle?: string; /** * Enable font ligatures. * Defaults to false. */ fontLigatures?: boolean; /** * Disable the use of `translate3d`. * Defaults to false. */ disableTranslate3d?: boolean; /** * Disable the optimizations for monospace fonts. * Defaults to false. */ disableMonospaceOptimizations?: boolean; /** * Should the cursor be hidden in the overview ruler. * Defaults to false. */ hideCursorInOverviewRuler?: boolean; /** * Enable that scrolling can go one screen size after the last line. * Defaults to true. */ scrollBeyondLastLine?: boolean; /** * Enable that the editor will install an interval to check if its container dom node size has changed. * Enabling this might have a severe performance impact. * Defaults to false. */ automaticLayout?: boolean; /** * Control the wrapping of the editor. * When `wordWrap` = "off", the lines will never wrap. * When `wordWrap` = "on", the lines will wrap at the viewport width. * When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`. * When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn). * Defaults to "off". */ wordWrap?: 'off' | 'on' | 'wordWrapColumn' | 'bounded'; /** * Control the wrapping of the editor. * When `wordWrap` = "off", the lines will never wrap. * When `wordWrap` = "on", the lines will wrap at the viewport width. * When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`. * When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn). * Defaults to 80. */ wordWrapColumn?: number; /** * Force word wrapping when the text appears to be of a minified/generated file. * Defaults to true. */ wordWrapMinified?: boolean; /** * Control indentation of wrapped lines. Can be: 'none', 'same' or 'indent'. * Defaults to 'same' in vscode and to 'none' in monaco-editor. */ wrappingIndent?: string; /** * Configure word wrapping characters. A break will be introduced before these characters. * Defaults to '{([+'. */ wordWrapBreakBeforeCharacters?: string; /** * Configure word wrapping characters. A break will be introduced after these characters. * Defaults to ' \t})]?|&,;'. */ wordWrapBreakAfterCharacters?: string; /** * Configure word wrapping characters. A break will be introduced after these characters only if no `wordWrapBreakBeforeCharacters` or `wordWrapBreakAfterCharacters` were found. * Defaults to '.'. */ wordWrapBreakObtrusiveCharacters?: string; /** * Performance guard: Stop rendering a line after x characters. * Defaults to 10000. * Use -1 to never stop rendering */ stopRenderingLineAfter?: number; /** * Enable hover. * Defaults to true. */ hover?: boolean; /** * Enable custom contextmenu. * Defaults to true. */ contextmenu?: boolean; /** * A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events. * Defaults to 1. */ mouseWheelScrollSensitivity?: number; /** * Enable quick suggestions (shadow suggestions) * Defaults to true. */ quickSuggestions?: boolean | { other: boolean, comments: boolean, strings: boolean }; /** * Quick suggestions show delay (in ms) * Defaults to 500 (ms) */ quickSuggestionsDelay?: number; /** * Enables parameter hints */ parameterHints?: boolean; /** * Render icons in suggestions box. * Defaults to true. */ iconsInSuggestions?: boolean; /** * Enable auto closing brackets. * Defaults to true. */ autoClosingBrackets?: boolean; /** * Enable format on type. * Defaults to false. */ formatOnType?: boolean; /** * Enable format on paste. * Defaults to false. */ formatOnPaste?: boolean; /** * Controls if the editor should allow to move selections via drag and drop. * Defaults to false. */ dragAndDrop?: boolean; /** * Enable the suggestion box to pop-up on trigger characters. * Defaults to true. */ suggestOnTriggerCharacters?: boolean; /** * Accept suggestions on ENTER. * Defaults to true. */ acceptSuggestionOnEnter?: boolean; /** * Accept suggestions on provider defined characters. * Defaults to true. */ acceptSuggestionOnCommitCharacter?: boolean; /** * Enable snippet suggestions. Default to 'true'. */ snippetSuggestions?: 'top' | 'bottom' | 'inline' | 'none'; /** * Copying without a selection copies the current line. */ emptySelectionClipboard?: boolean; /** * Enable word based suggestions. Defaults to 'true' */ wordBasedSuggestions?: boolean; /** * The font size for the suggest widget. * Defaults to the editor font size. */ suggestFontSize?: number; /** * The line height for the suggest widget. * Defaults to the editor line height. */ suggestLineHeight?: number; /** * Enable selection highlight. * Defaults to true. */ selectionHighlight?: boolean; /** * Enable semantic occurrences highlight. * Defaults to true. */ occurrencesHighlight?: boolean; /** * Show code lens * Defaults to true. */ codeLens?: boolean; /** * @deprecated - use codeLens instead * @internal */ referenceInfos?: boolean; /** * Enable code folding * Defaults to true in vscode and to false in monaco-editor. */ folding?: boolean; /** * Enable highlighting of matching brackets. * Defaults to true. */ matchBrackets?: boolean; /** * Enable rendering of whitespace. * Defaults to none. */ renderWhitespace?: 'none' | 'boundary' | 'all'; /** * Enable rendering of control characters. * Defaults to false. */ renderControlCharacters?: boolean; /** * Enable rendering of indent guides. * Defaults to false. */ renderIndentGuides?: boolean; /** * Enable rendering of current line highlight. * Defaults to all. */ renderLineHighlight?: 'none' | 'gutter' | 'line' | 'all'; /** * Inserting and deleting whitespace follows tab stops. */ useTabStops?: boolean; /** * The font family */ fontFamily?: string; /** * The font weight */ fontWeight?: 'normal' | 'bold' | 'bolder' | 'lighter' | 'initial' | 'inherit' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'; /** * The font size */ fontSize?: number; /** * The line height */ lineHeight?: number; } /** * Configuration options for the diff editor. */ export interface IDiffEditorOptions extends IEditorOptions { /** * Allow the user to resize the diff editor split view. * Defaults to true. */ enableSplitViewResizing?: boolean; /** * Render the differences in two side-by-side editors. * Defaults to true. */ renderSideBySide?: boolean; /** * Compute the diff by ignoring leading/trailing whitespace * Defaults to true. */ ignoreTrimWhitespace?: boolean; /** * Render +/- indicators for added/deleted changes. * Defaults to true. */ renderIndicators?: boolean; /** * Original model should be editable? * Defaults to false. */ originalEditable?: boolean; } export enum RenderMinimap { None = 0, Small = 1, Large = 2, SmallBlocks = 3, LargeBlocks = 4, } /** * Describes how to indent wrapped lines. */ export enum WrappingIndent { /** * No indentation => wrapped lines begin at column 1. */ None = 0, /** * Same => wrapped lines get the same indentation as the parent. */ Same = 1, /** * Indent => wrapped lines get +1 indentation as the parent. */ Indent = 2 } /** * The kind of animation in which the editor's cursor should be rendered. */ export enum TextEditorCursorBlinkingStyle { /** * Hidden */ Hidden = 0, /** * Blinking */ Blink = 1, /** * Blinking with smooth fading */ Smooth = 2, /** * Blinking with prolonged filled state and smooth fading */ Phase = 3, /** * Expand collapse animation on the y axis */ Expand = 4, /** * No-Blinking */ Solid = 5 } /** * The style in which the editor's cursor should be rendered. */ export enum TextEditorCursorStyle { /** * As a vertical line (sitting between two characters). */ Line = 1, /** * As a block (sitting on top of a character). */ Block = 2, /** * As a horizontal line (sitting under a character). */ Underline = 3, /** * As a thin vertical line (sitting between two characters). */ LineThin = 4, /** * As an outlined block (sitting on top of a character). */ BlockOutline = 5, /** * As a thin horizontal line (sitting under a character). */ UnderlineThin = 6 } /** * @internal */ export function cursorStyleToString(cursorStyle: TextEditorCursorStyle): string { if (cursorStyle === TextEditorCursorStyle.Line) { return 'line'; } else if (cursorStyle === TextEditorCursorStyle.Block) { return 'block'; } else if (cursorStyle === TextEditorCursorStyle.Underline) { return 'underline'; } else if (cursorStyle === TextEditorCursorStyle.LineThin) { return 'line-thin'; } else if (cursorStyle === TextEditorCursorStyle.BlockOutline) { return 'block-outline'; } else if (cursorStyle === TextEditorCursorStyle.UnderlineThin) { return 'underline-thin'; } else { throw new Error('cursorStyleToString: Unknown cursorStyle'); } } export class InternalEditorScrollbarOptions { readonly _internalEditorScrollbarOptionsBrand: void; readonly arrowSize: number; readonly vertical: ScrollbarVisibility; readonly horizontal: ScrollbarVisibility; readonly useShadows: boolean; readonly verticalHasArrows: boolean; readonly horizontalHasArrows: boolean; readonly handleMouseWheel: boolean; readonly horizontalScrollbarSize: number; readonly horizontalSliderSize: number; readonly verticalScrollbarSize: number; readonly verticalSliderSize: number; readonly mouseWheelScrollSensitivity: number; /** * @internal */ constructor(source: { arrowSize: number; vertical: ScrollbarVisibility; horizontal: ScrollbarVisibility; useShadows: boolean; verticalHasArrows: boolean; horizontalHasArrows: boolean; handleMouseWheel: boolean; horizontalScrollbarSize: number; horizontalSliderSize: number; verticalScrollbarSize: number; verticalSliderSize: number; mouseWheelScrollSensitivity: number; }) { this.arrowSize = source.arrowSize | 0; this.vertical = source.vertical | 0; this.horizontal = source.horizontal | 0; this.useShadows = Boolean(source.useShadows); this.verticalHasArrows = Boolean(source.verticalHasArrows); this.horizontalHasArrows = Boolean(source.horizontalHasArrows); this.handleMouseWheel = Boolean(source.handleMouseWheel); this.horizontalScrollbarSize = source.horizontalScrollbarSize | 0; this.horizontalSliderSize = source.horizontalSliderSize | 0; this.verticalScrollbarSize = source.verticalScrollbarSize | 0; this.verticalSliderSize = source.verticalSliderSize | 0; this.mouseWheelScrollSensitivity = Number(source.mouseWheelScrollSensitivity); } /** * @internal */ public equals(other: InternalEditorScrollbarOptions): boolean { return ( this.arrowSize === other.arrowSize && this.vertical === other.vertical && this.horizontal === other.horizontal && this.useShadows === other.useShadows && this.verticalHasArrows === other.verticalHasArrows && this.horizontalHasArrows === other.horizontalHasArrows && this.handleMouseWheel === other.handleMouseWheel && this.horizontalScrollbarSize === other.horizontalScrollbarSize && this.horizontalSliderSize === other.horizontalSliderSize && this.verticalScrollbarSize === other.verticalScrollbarSize && this.verticalSliderSize === other.verticalSliderSize && this.mouseWheelScrollSensitivity === other.mouseWheelScrollSensitivity ); } /** * @internal */ public clone(): InternalEditorScrollbarOptions { return new InternalEditorScrollbarOptions(this); } } export class InternalEditorMinimapOptions { readonly _internalEditorMinimapOptionsBrand: void; readonly enabled: boolean; readonly renderCharacters: boolean; readonly maxColumn: number; /** * @internal */ constructor(source: { enabled: boolean; renderCharacters: boolean; maxColumn: number; }) { this.enabled = Boolean(source.enabled); this.renderCharacters = Boolean(source.renderCharacters); this.maxColumn = source.maxColumn | 0; } /** * @internal */ public equals(other: InternalEditorMinimapOptions): boolean { return ( this.enabled === other.enabled && this.renderCharacters === other.renderCharacters && this.maxColumn === other.maxColumn ); } /** * @internal */ public clone(): InternalEditorMinimapOptions { return new InternalEditorMinimapOptions(this); } } export class EditorWrappingInfo { readonly _editorWrappingInfoBrand: void; readonly inDiffEditor: boolean; readonly isDominatedByLongLines: boolean; readonly isWordWrapMinified: boolean; readonly isViewportWrapping: boolean; readonly wrappingColumn: number; readonly wrappingIndent: WrappingIndent; readonly wordWrapBreakBeforeCharacters: string; readonly wordWrapBreakAfterCharacters: string; readonly wordWrapBreakObtrusiveCharacters: string; /** * @internal */ constructor(source: { inDiffEditor: boolean; isDominatedByLongLines: boolean; isWordWrapMinified: boolean; isViewportWrapping: boolean; wrappingColumn: number; wrappingIndent: WrappingIndent; wordWrapBreakBeforeCharacters: string; wordWrapBreakAfterCharacters: string; wordWrapBreakObtrusiveCharacters: string; }) { this.inDiffEditor = Boolean(source.inDiffEditor); this.isDominatedByLongLines = Boolean(source.isDominatedByLongLines); this.isWordWrapMinified = Boolean(source.isWordWrapMinified); this.isViewportWrapping = Boolean(source.isViewportWrapping); this.wrappingColumn = source.wrappingColumn | 0; this.wrappingIndent = source.wrappingIndent | 0; this.wordWrapBreakBeforeCharacters = String(source.wordWrapBreakBeforeCharacters); this.wordWrapBreakAfterCharacters = String(source.wordWrapBreakAfterCharacters); this.wordWrapBreakObtrusiveCharacters = String(source.wordWrapBreakObtrusiveCharacters); } /** * @internal */ public equals(other: EditorWrappingInfo): boolean { return ( this.inDiffEditor === other.inDiffEditor && this.isDominatedByLongLines === other.isDominatedByLongLines && this.isWordWrapMinified === other.isWordWrapMinified && this.isViewportWrapping === other.isViewportWrapping && this.wrappingColumn === other.wrappingColumn && this.wrappingIndent === other.wrappingIndent && this.wordWrapBreakBeforeCharacters === other.wordWrapBreakBeforeCharacters && this.wordWrapBreakAfterCharacters === other.wordWrapBreakAfterCharacters && this.wordWrapBreakObtrusiveCharacters === other.wordWrapBreakObtrusiveCharacters ); } /** * @internal */ public clone(): EditorWrappingInfo { return new EditorWrappingInfo(this); } } export class InternalEditorViewOptions { readonly _internalEditorViewOptionsBrand: void; readonly theme: string; readonly canUseTranslate3d: boolean; readonly disableMonospaceOptimizations: boolean; readonly experimentalScreenReader: boolean; readonly rulers: number[]; readonly ariaLabel: string; readonly renderLineNumbers: boolean; readonly renderCustomLineNumbers: (lineNumber: number) => string; readonly renderRelativeLineNumbers: boolean; readonly selectOnLineNumbers: boolean; readonly glyphMargin: boolean; readonly revealHorizontalRightPadding: number; readonly roundedSelection: boolean; readonly overviewRulerLanes: number; readonly overviewRulerBorder: boolean; readonly cursorBlinking: TextEditorCursorBlinkingStyle; readonly mouseWheelZoom: boolean; readonly cursorStyle: TextEditorCursorStyle; readonly hideCursorInOverviewRuler: boolean; readonly scrollBeyondLastLine: boolean; readonly editorClassName: string; readonly stopRenderingLineAfter: number; readonly renderWhitespace: 'none' | 'boundary' | 'all'; readonly renderControlCharacters: boolean; readonly fontLigatures: boolean; readonly renderIndentGuides: boolean; readonly renderLineHighlight: 'none' | 'gutter' | 'line' | 'all'; readonly scrollbar: InternalEditorScrollbarOptions; readonly minimap: InternalEditorMinimapOptions; readonly fixedOverflowWidgets: boolean; /** * @internal */ constructor(source: { theme: string; canUseTranslate3d: boolean; disableMonospaceOptimizations: boolean; experimentalScreenReader: boolean; rulers: number[]; ariaLabel: string; renderLineNumbers: boolean; renderCustomLineNumbers: (lineNumber: number) => string; renderRelativeLineNumbers: boolean; selectOnLineNumbers: boolean; glyphMargin: boolean; revealHorizontalRightPadding: number; roundedSelection: boolean; overviewRulerLanes: number; overviewRulerBorder: boolean; cursorBlinking: TextEditorCursorBlinkingStyle; mouseWheelZoom: boolean; cursorStyle: TextEditorCursorStyle; hideCursorInOverviewRuler: boolean; scrollBeyondLastLine: boolean; editorClassName: string; stopRenderingLineAfter: number; renderWhitespace: 'none' | 'boundary' | 'all'; renderControlCharacters: boolean; fontLigatures: boolean; renderIndentGuides: boolean; renderLineHighlight: 'none' | 'gutter' | 'line' | 'all'; scrollbar: InternalEditorScrollbarOptions; minimap: InternalEditorMinimapOptions; fixedOverflowWidgets: boolean; }) { this.theme = String(source.theme); this.canUseTranslate3d = Boolean(source.canUseTranslate3d); this.disableMonospaceOptimizations = Boolean(source.disableMonospaceOptimizations); this.experimentalScreenReader = Boolean(source.experimentalScreenReader); this.rulers = InternalEditorViewOptions._toSortedIntegerArray(source.rulers); this.ariaLabel = String(source.ariaLabel); this.renderLineNumbers = Boolean(source.renderLineNumbers); this.renderCustomLineNumbers = source.renderCustomLineNumbers; this.renderRelativeLineNumbers = Boolean(source.renderRelativeLineNumbers); this.selectOnLineNumbers = Boolean(source.selectOnLineNumbers); this.glyphMargin = Boolean(source.glyphMargin); this.revealHorizontalRightPadding = source.revealHorizontalRightPadding | 0; this.roundedSelection = Boolean(source.roundedSelection); this.overviewRulerLanes = source.overviewRulerLanes | 0; this.overviewRulerBorder = Boolean(source.overviewRulerBorder); this.cursorBlinking = source.cursorBlinking | 0; this.mouseWheelZoom = Boolean(source.mouseWheelZoom); this.cursorStyle = source.cursorStyle | 0; this.hideCursorInOverviewRuler = Boolean(source.hideCursorInOverviewRuler); this.scrollBeyondLastLine = Boolean(source.scrollBeyondLastLine); this.editorClassName = String(source.editorClassName); this.stopRenderingLineAfter = source.stopRenderingLineAfter | 0; this.renderWhitespace = source.renderWhitespace; this.renderControlCharacters = Boolean(source.renderControlCharacters); this.fontLigatures = Boolean(source.fontLigatures); this.renderIndentGuides = Boolean(source.renderIndentGuides); this.renderLineHighlight = source.renderLineHighlight; this.scrollbar = source.scrollbar.clone(); this.minimap = source.minimap.clone(); this.fixedOverflowWidgets = Boolean(source.fixedOverflowWidgets); } private static _toSortedIntegerArray(source: any): number[] { if (!Array.isArray(source)) { return []; } let arrSource = <any[]>source; let result = arrSource.map(el => { let r = parseInt(el, 10); if (isNaN(r)) { return 0; } return r; }); result.sort(); return result; } private static _numberArraysEqual(a: number[], b: number[]): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } /** * @internal */ public equals(other: InternalEditorViewOptions): boolean { return ( this.theme === other.theme && this.canUseTranslate3d === other.canUseTranslate3d && this.disableMonospaceOptimizations === other.disableMonospaceOptimizations && this.experimentalScreenReader === other.experimentalScreenReader && InternalEditorViewOptions._numberArraysEqual(this.rulers, other.rulers) && this.ariaLabel === other.ariaLabel && this.renderLineNumbers === other.renderLineNumbers && this.renderCustomLineNumbers === other.renderCustomLineNumbers && this.renderRelativeLineNumbers === other.renderRelativeLineNumbers && this.selectOnLineNumbers === other.selectOnLineNumbers && this.glyphMargin === other.glyphMargin && this.revealHorizontalRightPadding === other.revealHorizontalRightPadding && this.roundedSelection === other.roundedSelection && this.overviewRulerLanes === other.overviewRulerLanes && this.overviewRulerBorder === other.overviewRulerBorder && this.cursorBlinking === other.cursorBlinking && this.mouseWheelZoom === other.mouseWheelZoom && this.cursorStyle === other.cursorStyle && this.hideCursorInOverviewRuler === other.hideCursorInOverviewRuler && this.scrollBeyondLastLine === other.scrollBeyondLastLine && this.editorClassName === other.editorClassName && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.fontLigatures === other.fontLigatures && this.renderIndentGuides === other.renderIndentGuides && this.renderLineHighlight === other.renderLineHighlight && this.scrollbar.equals(other.scrollbar) && this.minimap.equals(other.minimap) && this.fixedOverflowWidgets === other.fixedOverflowWidgets ); } /** * @internal */ public createChangeEvent(newOpts: InternalEditorViewOptions): IViewConfigurationChangedEvent { return { theme: this.theme !== newOpts.theme, canUseTranslate3d: this.canUseTranslate3d !== newOpts.canUseTranslate3d, disableMonospaceOptimizations: this.disableMonospaceOptimizations !== newOpts.disableMonospaceOptimizations, experimentalScreenReader: this.experimentalScreenReader !== newOpts.experimentalScreenReader, rulers: (!InternalEditorViewOptions._numberArraysEqual(this.rulers, newOpts.rulers)), ariaLabel: this.ariaLabel !== newOpts.ariaLabel, renderLineNumbers: this.renderLineNumbers !== newOpts.renderLineNumbers, renderCustomLineNumbers: this.renderCustomLineNumbers !== newOpts.renderCustomLineNumbers, renderRelativeLineNumbers: this.renderRelativeLineNumbers !== newOpts.renderRelativeLineNumbers, selectOnLineNumbers: this.selectOnLineNumbers !== newOpts.selectOnLineNumbers, glyphMargin: this.glyphMargin !== newOpts.glyphMargin, revealHorizontalRightPadding: this.revealHorizontalRightPadding !== newOpts.revealHorizontalRightPadding, roundedSelection: this.roundedSelection !== newOpts.roundedSelection, overviewRulerLanes: this.overviewRulerLanes !== newOpts.overviewRulerLanes, overviewRulerBorder: this.overviewRulerBorder !== newOpts.overviewRulerBorder, cursorBlinking: this.cursorBlinking !== newOpts.cursorBlinking, mouseWheelZoom: this.mouseWheelZoom !== newOpts.mouseWheelZoom, cursorStyle: this.cursorStyle !== newOpts.cursorStyle, hideCursorInOverviewRuler: this.hideCursorInOverviewRuler !== newOpts.hideCursorInOverviewRuler, scrollBeyondLastLine: this.scrollBeyondLastLine !== newOpts.scrollBeyondLastLine, editorClassName: this.editorClassName !== newOpts.editorClassName, stopRenderingLineAfter: this.stopRenderingLineAfter !== newOpts.stopRenderingLineAfter, renderWhitespace: this.renderWhitespace !== newOpts.renderWhitespace, renderControlCharacters: this.renderControlCharacters !== newOpts.renderControlCharacters, fontLigatures: this.fontLigatures !== newOpts.fontLigatures, renderIndentGuides: this.renderIndentGuides !== newOpts.renderIndentGuides, renderLineHighlight: this.renderLineHighlight !== newOpts.renderLineHighlight, scrollbar: (!this.scrollbar.equals(newOpts.scrollbar)), minimap: (!this.minimap.equals(newOpts.minimap)), fixedOverflowWidgets: this.fixedOverflowWidgets !== newOpts.fixedOverflowWidgets }; } /** * @internal */ public clone(): InternalEditorViewOptions { return new InternalEditorViewOptions(this); } } export class EditorContribOptions { readonly selectionClipboard: boolean; readonly hover: boolean; readonly contextmenu: boolean; readonly quickSuggestions: boolean | { other: boolean, comments: boolean, strings: boolean }; readonly quickSuggestionsDelay: number; readonly parameterHints: boolean; readonly iconsInSuggestions: boolean; readonly formatOnType: boolean; readonly formatOnPaste: boolean; readonly suggestOnTriggerCharacters: boolean; readonly acceptSuggestionOnEnter: boolean; readonly acceptSuggestionOnCommitCharacter: boolean; readonly snippetSuggestions: 'top' | 'bottom' | 'inline' | 'none'; readonly emptySelectionClipboard: boolean; readonly wordBasedSuggestions: boolean; readonly suggestFontSize: number; readonly suggestLineHeight: number; readonly selectionHighlight: boolean; readonly occurrencesHighlight: boolean; readonly codeLens: boolean; readonly folding: boolean; readonly matchBrackets: boolean; /** * @internal */ constructor(source: { selectionClipboard: boolean; hover: boolean; contextmenu: boolean; quickSuggestions: boolean | { other: boolean, comments: boolean, strings: boolean }; quickSuggestionsDelay: number; parameterHints: boolean; iconsInSuggestions: boolean; formatOnType: boolean; formatOnPaste: boolean; suggestOnTriggerCharacters: boolean; acceptSuggestionOnEnter: boolean; acceptSuggestionOnCommitCharacter: boolean; snippetSuggestions: 'top' | 'bottom' | 'inline' | 'none'; emptySelectionClipboard: boolean; wordBasedSuggestions: boolean; suggestFontSize: number; suggestLineHeight: number; selectionHighlight: boolean; occurrencesHighlight: boolean; codeLens: boolean; folding: boolean; matchBrackets: boolean; }) { this.selectionClipboard = Boolean(source.selectionClipboard); this.hover = Boolean(source.hover); this.contextmenu = Boolean(source.contextmenu); this.quickSuggestions = source.quickSuggestions; this.quickSuggestionsDelay = source.quickSuggestionsDelay || 0; this.parameterHints = Boolean(source.parameterHints); this.iconsInSuggestions = Boolean(source.iconsInSuggestions); this.formatOnType = Boolean(source.formatOnType); this.formatOnPaste = Boolean(source.formatOnPaste); this.suggestOnTriggerCharacters = Boolean(source.suggestOnTriggerCharacters); this.acceptSuggestionOnEnter = Boolean(source.acceptSuggestionOnEnter); this.acceptSuggestionOnCommitCharacter = Boolean(source.acceptSuggestionOnCommitCharacter); this.snippetSuggestions = source.snippetSuggestions; this.emptySelectionClipboard = source.emptySelectionClipboard; this.wordBasedSuggestions = source.wordBasedSuggestions; this.suggestFontSize = source.suggestFontSize; this.suggestLineHeight = source.suggestLineHeight; this.selectionHighlight = Boolean(source.selectionHighlight); this.occurrencesHighlight = Boolean(source.occurrencesHighlight); this.codeLens = Boolean(source.codeLens); this.folding = Boolean(source.folding); this.matchBrackets = Boolean(source.matchBrackets); } /** * @internal */ public equals(other: EditorContribOptions): boolean { return ( this.selectionClipboard === other.selectionClipboard && this.hover === other.hover && this.contextmenu === other.contextmenu && objects.equals(this.quickSuggestions, other.quickSuggestions) && this.quickSuggestionsDelay === other.quickSuggestionsDelay && this.parameterHints === other.parameterHints && this.iconsInSuggestions === other.iconsInSuggestions && this.formatOnType === other.formatOnType && this.formatOnPaste === other.formatOnPaste && this.suggestOnTriggerCharacters === other.suggestOnTriggerCharacters && this.acceptSuggestionOnEnter === other.acceptSuggestionOnEnter && this.acceptSuggestionOnCommitCharacter === other.acceptSuggestionOnCommitCharacter && this.snippetSuggestions === other.snippetSuggestions && this.emptySelectionClipboard === other.emptySelectionClipboard && objects.equals(this.wordBasedSuggestions, other.wordBasedSuggestions) && this.suggestFontSize === other.suggestFontSize && this.suggestLineHeight === other.suggestLineHeight && this.selectionHighlight === other.selectionHighlight && this.occurrencesHighlight === other.occurrencesHighlight && this.codeLens === other.codeLens && this.folding === other.folding && this.matchBrackets === other.matchBrackets ); } /** * @internal */ public clone(): EditorContribOptions { return new EditorContribOptions(this); } } /** * Internal configuration options (transformed or computed) for the editor. */ export class InternalEditorOptions { readonly _internalEditorOptionsBrand: void; readonly lineHeight: number; // todo: move to fontInfo readonly readOnly: boolean; // ---- cursor options readonly wordSeparators: string; readonly autoClosingBrackets: boolean; readonly useTabStops: boolean; readonly tabFocusMode: boolean; readonly dragAndDrop: boolean; // ---- grouped options readonly layoutInfo: EditorLayoutInfo; readonly fontInfo: FontInfo; readonly viewInfo: InternalEditorViewOptions; readonly wrappingInfo: EditorWrappingInfo; readonly contribInfo: EditorContribOptions; /** * @internal */ constructor(source: { lineHeight: number; readOnly: boolean; wordSeparators: string; autoClosingBrackets: boolean; useTabStops: boolean; tabFocusMode: boolean; dragAndDrop: boolean; layoutInfo: EditorLayoutInfo; fontInfo: FontInfo; viewInfo: InternalEditorViewOptions; wrappingInfo: EditorWrappingInfo; contribInfo: EditorContribOptions; }) { this.lineHeight = source.lineHeight | 0; this.readOnly = Boolean(source.readOnly); this.wordSeparators = String(source.wordSeparators); this.autoClosingBrackets = Boolean(source.autoClosingBrackets); this.useTabStops = Boolean(source.useTabStops); this.tabFocusMode = Boolean(source.tabFocusMode); this.dragAndDrop = Boolean(source.dragAndDrop); this.layoutInfo = source.layoutInfo.clone(); this.fontInfo = source.fontInfo.clone(); this.viewInfo = source.viewInfo.clone(); this.wrappingInfo = source.wrappingInfo.clone(); this.contribInfo = source.contribInfo.clone(); } /** * @internal */ public equals(other: InternalEditorOptions): boolean { return ( this.lineHeight === other.lineHeight && this.readOnly === other.readOnly && this.wordSeparators === other.wordSeparators && this.autoClosingBrackets === other.autoClosingBrackets && this.useTabStops === other.useTabStops && this.tabFocusMode === other.tabFocusMode && this.dragAndDrop === other.dragAndDrop && this.layoutInfo.equals(other.layoutInfo) && this.fontInfo.equals(other.fontInfo) && this.viewInfo.equals(other.viewInfo) && this.wrappingInfo.equals(other.wrappingInfo) && this.contribInfo.equals(other.contribInfo) ); } /** * @internal */ public createChangeEvent(newOpts: InternalEditorOptions): IConfigurationChangedEvent { return { lineHeight: (this.lineHeight !== newOpts.lineHeight), readOnly: (this.readOnly !== newOpts.readOnly), wordSeparators: (this.wordSeparators !== newOpts.wordSeparators), autoClosingBrackets: (this.autoClosingBrackets !== newOpts.autoClosingBrackets), useTabStops: (this.useTabStops !== newOpts.useTabStops), tabFocusMode: (this.tabFocusMode !== newOpts.tabFocusMode), dragAndDrop: (this.dragAndDrop !== newOpts.dragAndDrop), layoutInfo: (!this.layoutInfo.equals(newOpts.layoutInfo)), fontInfo: (!this.fontInfo.equals(newOpts.fontInfo)), viewInfo: this.viewInfo.createChangeEvent(newOpts.viewInfo), wrappingInfo: (!this.wrappingInfo.equals(newOpts.wrappingInfo)), contribInfo: (!this.contribInfo.equals(newOpts.contribInfo)), }; } /** * @internal */ public clone(): InternalEditorOptions { return new InternalEditorOptions(this); } } /** * A description for the overview ruler position. */ export class OverviewRulerPosition { readonly _overviewRulerPositionBrand: void; /** * Width of the overview ruler */ readonly width: number; /** * Height of the overview ruler */ readonly height: number; /** * Top position for the overview ruler */ readonly top: number; /** * Right position for the overview ruler */ readonly right: number; /** * @internal */ constructor(source: { width: number; height: number; top: number; right: number; }) { this.width = source.width | 0; this.height = source.height | 0; this.top = source.top | 0; this.right = source.right | 0; } /** * @internal */ public equals(other: OverviewRulerPosition): boolean { return ( this.width === other.width && this.height === other.height && this.top === other.top && this.right === other.right ); } /** * @internal */ public clone(): OverviewRulerPosition { return new OverviewRulerPosition(this); } } /** * The internal layout details of the editor. */ export class EditorLayoutInfo { readonly _editorLayoutInfoBrand: void; /** * Full editor width. */ readonly width: number; /** * Full editor height. */ readonly height: number; /** * Left position for the glyph margin. */ readonly glyphMarginLeft: number; /** * The width of the glyph margin. */ readonly glyphMarginWidth: number; /** * The height of the glyph margin. */ readonly glyphMarginHeight: number; /** * Left position for the line numbers. */ readonly lineNumbersLeft: number; /** * The width of the line numbers. */ readonly lineNumbersWidth: number; /** * The height of the line numbers. */ readonly lineNumbersHeight: number; /** * Left position for the line decorations. */ readonly decorationsLeft: number; /** * The width of the line decorations. */ readonly decorationsWidth: number; /** * The height of the line decorations. */ readonly decorationsHeight: number; /** * Left position for the content (actual text) */ readonly contentLeft: number; /** * The width of the content (actual text) */ readonly contentWidth: number; /** * The height of the content (actual height) */ readonly contentHeight: number; /** * The width of the minimap */ readonly minimapWidth: number; /** * Minimap render type */ readonly renderMinimap: RenderMinimap; /** * The number of columns (of typical characters) fitting on a viewport line. */ readonly viewportColumn: number; /** * The width of the vertical scrollbar. */ readonly verticalScrollbarWidth: number; /** * The height of the horizontal scrollbar. */ readonly horizontalScrollbarHeight: number; /** * The position of the overview ruler. */ readonly overviewRuler: OverviewRulerPosition; /** * @internal */ constructor(source: { width: number; height: number; glyphMarginLeft: number; glyphMarginWidth: number; glyphMarginHeight: number; lineNumbersLeft: number; lineNumbersWidth: number; lineNumbersHeight: number; decorationsLeft: number; decorationsWidth: number; decorationsHeight: number; contentLeft: number; contentWidth: number; contentHeight: number; renderMinimap: RenderMinimap; minimapWidth: number; viewportColumn: number; verticalScrollbarWidth: number; horizontalScrollbarHeight: number; overviewRuler: OverviewRulerPosition; }) { this.width = source.width | 0; this.height = source.height | 0; this.glyphMarginLeft = source.glyphMarginLeft | 0; this.glyphMarginWidth = source.glyphMarginWidth | 0; this.glyphMarginHeight = source.glyphMarginHeight | 0; this.lineNumbersLeft = source.lineNumbersLeft | 0; this.lineNumbersWidth = source.lineNumbersWidth | 0; this.lineNumbersHeight = source.lineNumbersHeight | 0; this.decorationsLeft = source.decorationsLeft | 0; this.decorationsWidth = source.decorationsWidth | 0; this.decorationsHeight = source.decorationsHeight | 0; this.contentLeft = source.contentLeft | 0; this.contentWidth = source.contentWidth | 0; this.contentHeight = source.contentHeight | 0; this.renderMinimap = source.renderMinimap | 0; this.minimapWidth = source.minimapWidth | 0; this.viewportColumn = source.viewportColumn | 0; this.verticalScrollbarWidth = source.verticalScrollbarWidth | 0; this.horizontalScrollbarHeight = source.horizontalScrollbarHeight | 0; this.overviewRuler = source.overviewRuler.clone(); } /** * @internal */ public equals(other: EditorLayoutInfo): boolean { return ( this.width === other.width && this.height === other.height && this.glyphMarginLeft === other.glyphMarginLeft && this.glyphMarginWidth === other.glyphMarginWidth && this.glyphMarginHeight === other.glyphMarginHeight && this.lineNumbersLeft === other.lineNumbersLeft && this.lineNumbersWidth === other.lineNumbersWidth && this.lineNumbersHeight === other.lineNumbersHeight && this.decorationsLeft === other.decorationsLeft && this.decorationsWidth === other.decorationsWidth && this.decorationsHeight === other.decorationsHeight && this.contentLeft === other.contentLeft && this.contentWidth === other.contentWidth && this.contentHeight === other.contentHeight && this.renderMinimap === other.renderMinimap && this.minimapWidth === other.minimapWidth && this.viewportColumn === other.viewportColumn && this.verticalScrollbarWidth === other.verticalScrollbarWidth && this.horizontalScrollbarHeight === other.horizontalScrollbarHeight && this.overviewRuler.equals(other.overviewRuler) ); } /** * @internal */ public clone(): EditorLayoutInfo { return new EditorLayoutInfo(this); } } export interface IViewConfigurationChangedEvent { readonly theme: boolean; readonly canUseTranslate3d: boolean; readonly disableMonospaceOptimizations: boolean; readonly experimentalScreenReader: boolean; readonly rulers: boolean; readonly ariaLabel: boolean; readonly renderLineNumbers: boolean; readonly renderCustomLineNumbers: boolean; readonly renderRelativeLineNumbers: boolean; readonly selectOnLineNumbers: boolean; readonly glyphMargin: boolean; readonly revealHorizontalRightPadding: boolean; readonly roundedSelection: boolean; readonly overviewRulerLanes: boolean; readonly overviewRulerBorder: boolean; readonly cursorBlinking: boolean; readonly mouseWheelZoom: boolean; readonly cursorStyle: boolean; readonly hideCursorInOverviewRuler: boolean; readonly scrollBeyondLastLine: boolean; readonly editorClassName: boolean; readonly stopRenderingLineAfter: boolean; readonly renderWhitespace: boolean; readonly renderControlCharacters: boolean; readonly fontLigatures: boolean; readonly renderIndentGuides: boolean; readonly renderLineHighlight: boolean; readonly scrollbar: boolean; readonly minimap: boolean; readonly fixedOverflowWidgets: boolean; } /** * An event describing that the configuration of the editor has changed. */ export interface IConfigurationChangedEvent { readonly lineHeight: boolean; readonly readOnly: boolean; readonly wordSeparators: boolean; readonly autoClosingBrackets: boolean; readonly useTabStops: boolean; readonly tabFocusMode: boolean; readonly dragAndDrop: boolean; readonly layoutInfo: boolean; readonly fontInfo: boolean; readonly viewInfo: IViewConfigurationChangedEvent; readonly wrappingInfo: boolean; readonly contribInfo: boolean; }
the_stack
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { I18nEventBus, ShopEventBus, ShippingService, FulfilmentService, PaymentService, UserEventBus, Util } from './../shared/services/index'; import { ModalComponent, ModalResult, ModalAction } from './../shared/modal/index'; import { CarrierVO, CarrierInfoVO, CarrierSlaVO, CarrierSlaInfoVO, ShopVO, PaymentGatewayInfoVO, FulfilmentCentreInfoVO, Pair, SearchContextVO, SearchResultVO, AttributeVO } from './../shared/model/index'; import { FormValidationEvent, Futures, Future } from './../shared/event/index'; import { Config } from './../../environments/environment'; import { LogUtil } from './../shared/log/index'; @Component({ selector: 'cw-shipping', templateUrl: 'shipping.component.html', }) export class ShippingComponent implements OnInit, OnDestroy { private static CARRIERS:string = 'carriers'; private static CARRIER:string = 'carrier'; private static SLA:string = 'sla'; public viewMode:string = ShippingComponent.CARRIERS; public carriers:SearchResultVO<CarrierInfoVO>; public carrierFilter:string; private delayedFilteringCarrier:Future; private delayedFilteringCarrierMs:number = Config.UI_INPUT_DELAY; public selectedCarrier:CarrierVO; public carrierEdit:CarrierVO; @ViewChild('deleteConfirmationModalDialog') private deleteConfirmationModalDialog:ModalComponent; public pgs:Array<PaymentGatewayInfoVO> = []; public fcs:Array<FulfilmentCentreInfoVO> = []; public shops:Array<ShopVO> = []; public slaTypes:Array<AttributeVO> = []; public selectedSla:CarrierSlaInfoVO; public slaEdit:CarrierSlaVO; public deleteValue:String; private shopAllSub:any; public loading:boolean = false; public changed:boolean = false; public validForSave:boolean = false; constructor(private _shippingService:ShippingService, private _paymentService:PaymentService, private _fulfilmentService:FulfilmentService) { LogUtil.debug('ShippingComponent constructed'); this.shopAllSub = ShopEventBus.getShopEventBus().shopsUpdated$.subscribe(shopsevt => { this.shops = shopsevt; }); this.carriers = this.newSearchResultCarrierInstance(); } newCarrierInstance():CarrierVO { return { carrierId: 0, code: null, name: '', description: '', displayNames: [], displayDescriptions: [], carrierShops: [], slas: [] }; } newSearchResultCarrierInstance():SearchResultVO<CarrierInfoVO> { return { searchContext: { parameters: { filter: [] }, start: 0, size: Config.UI_TABLE_PAGE_SIZE, sortBy: null, sortDesc: false }, items: [], total: 0 }; } newSlaInstance():CarrierSlaVO { let carrierId = this.selectedCarrier != null ? this.selectedCarrier.carrierId : 0; return { carrierslaId: 0, carrierId: carrierId, code: null, name: '', description: '', displayNames: [], displayDescriptions: [], maxDays: 1, minDays: 1, excludeWeekDays: [], excludeDates: [], guaranteed: false, namedDay: false, excludeCustomerTypes: null, slaType: 'F', script: '', billingAddressNotRequired: false, deliveryAddressNotRequired: false, supportedPaymentGateways: [], supportedFulfilmentCentres: [], externalRef: null }; } ngOnInit() { LogUtil.debug('ShippingComponent ngOnInit'); this.onRefreshHandler(); let that = this; this.delayedFilteringCarrier = Futures.perpetual(function() { that.getFilteredCarriers(); }, this.delayedFilteringCarrierMs); } ngOnDestroy() { LogUtil.debug('ShippingComponent ngOnDestroy'); if (this.shopAllSub) { this.shopAllSub.unsubscribe(); } } onCarrierFilterChange(event:any) { this.carriers.searchContext.start = 0; // changing filter means we need to start from first page this.delayedFilteringCarrier.delay(); } onRefreshHandler() { LogUtil.debug('ShippingComponent refresh handler'); if (UserEventBus.getUserEventBus().current() != null) { this.getFilteredCarriers(); } } onPageSelected(page:number) { LogUtil.debug('ShippingComponent onPageSelected', page); this.carriers.searchContext.start = page; this.delayedFilteringCarrier.delay(); } onSortSelected(sort:Pair<string, boolean>) { LogUtil.debug('ShippingComponent ononSortSelected', sort); if (sort == null) { this.carriers.searchContext.sortBy = null; this.carriers.searchContext.sortDesc = false; } else { this.carriers.searchContext.sortBy = sort.first; this.carriers.searchContext.sortDesc = sort.second; } this.delayedFilteringCarrier.delay(); } onCarrierSelected(data:CarrierVO) { LogUtil.debug('ShippingComponent onCarrierSelected', data); this.selectedCarrier = data; } onCarrierChanged(event:FormValidationEvent<CarrierVO>) { LogUtil.debug('ShippingComponent onCarrierChanged', event); this.changed = true; this.validForSave = event.valid; this.carrierEdit = event.source; } onSlaSelected(data:CarrierSlaInfoVO) { LogUtil.debug('ShippingComponent onSlaSelected', data); this.selectedSla = data; } onSlaAdd(data:CarrierSlaInfoVO) { LogUtil.debug('ShippingComponent onSlaAdd', data); this.onRowNew(); } onSlaEdit(data:CarrierSlaInfoVO) { LogUtil.debug('ShippingComponent onSlaEdit', data); this.onRowEditSla(data); } onSlaDelete(data:CarrierSlaInfoVO) { LogUtil.debug('ShippingComponent onSlaDelete', data); this.selectedSla = data; this.onRowDelete(data); } onSlaChanged(event:FormValidationEvent<CarrierSlaVO>) { LogUtil.debug('ShippingComponent onSlaChanged', event); this.changed = true; this.validForSave = event.valid; this.slaEdit = event.source; } onBackToList() { LogUtil.debug('ShippingComponent onBackToList handler'); if (this.viewMode === ShippingComponent.SLA) { this.slaEdit = null; if (this.carrierEdit != null) { this.viewMode = ShippingComponent.CARRIER; } } else if (this.viewMode === ShippingComponent.CARRIER) { this.carrierEdit = null; this.slaEdit = null; this.selectedSla = null; this.viewMode = ShippingComponent.CARRIERS; } } onRowNew() { LogUtil.debug('ShippingComponent onRowNew handler'); this.changed = false; this.validForSave = false; if (this.viewMode === ShippingComponent.CARRIERS) { this.carrierEdit = this.newCarrierInstance(); this.viewMode = ShippingComponent.CARRIER; } else if (this.viewMode === ShippingComponent.CARRIER) { this.slaEdit = this.newSlaInstance(); this.viewMode = ShippingComponent.SLA; } } onRowDelete(row:any) { LogUtil.debug('ShippingComponent onRowDelete handler', row); this.deleteValue = row.name; this.deleteConfirmationModalDialog.show(); } onRowDeleteSelected() { if (this.selectedSla != null) { this.onRowDelete(this.selectedSla); } else if (this.selectedCarrier != null) { this.onRowDelete(this.selectedCarrier); } } onRowEditCarrier(row:CarrierInfoVO) { LogUtil.debug('ShippingComponent onRowEditCarrier handler', row); this.loading = true; this._shippingService.getCarrierById(row.carrierId).subscribe(res => { LogUtil.debug('ShippingComponent getCarrierById', res); this.carrierEdit = res; this.changed = false; this.validForSave = false; this.viewMode = ShippingComponent.CARRIER; this.loading = false; }); } onRowEditSla(row:CarrierSlaInfoVO) { LogUtil.debug('ShippingComponent onRowEditSla handler', row); this.slaEdit = Util.clone(row); this.changed = false; this.validForSave = false; this.viewMode = ShippingComponent.SLA; } onRowEditSelected() { if (this.selectedSla != null) { this.onRowEditSla(this.selectedSla); } else if (this.selectedCarrier != null) { this.onRowEditCarrier(this.selectedCarrier); } } onSaveHandler() { if (this.validForSave && this.changed) { if (this.slaEdit != null) { LogUtil.debug('ShippingComponent Save handler sla', this.slaEdit); this.loading = true; this._shippingService.saveCarrierSla(this.slaEdit).subscribe( rez => { let pk = this.slaEdit.carrierslaId; if (pk > 0) { LogUtil.debug('ShippingComponent sla edit', rez); if (this.carrierEdit != null) { let idx = this.carrierEdit.slas.findIndex(rez => rez.carrierslaId == pk); if (idx !== -1) { this.carrierEdit.slas[idx] = rez; this.carrierEdit.slas = this.carrierEdit.slas.slice(0, this.carrierEdit.slas.length); // reset to propagate changes } } } else { if (this.carrierEdit != null) { this.carrierEdit.slas.push(rez); this.carrierEdit.slas = this.carrierEdit.slas.slice(0, this.carrierEdit.slas.length); // reset to propagate changes } LogUtil.debug('ShippingComponent sla added', rez); } this.changed = false; this.selectedSla = rez; this.slaEdit = null; this.loading = false; this.viewMode = ShippingComponent.CARRIER; } ); } else if (this.carrierEdit != null) { LogUtil.debug('ShippingComponent Save handler carrier', this.carrierEdit); this.loading = true; this._shippingService.saveCarrier(this.carrierEdit).subscribe( rez => { LogUtil.debug('ShippingComponent country changed', rez); this.changed = false; this.selectedCarrier = rez; this.selectedSla = null; this.carrierEdit = null; this.loading = false; this.getFilteredCarriers(); } ); } } } onDiscardEventHandler() { LogUtil.debug('ShippingComponent discard handler'); if (this.viewMode === ShippingComponent.SLA) { if (this.selectedSla != null) { this.onRowEditSla(this.selectedSla); } else { this.onRowNew(); } } if (this.viewMode === ShippingComponent.CARRIER) { if (this.selectedCarrier != null) { this.onRowEditCarrier(this.selectedCarrier); } else { this.onRowNew(); } } } onDeleteConfirmationResult(modalresult: ModalResult) { LogUtil.debug('ShippingComponent onDeleteConfirmationResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { if (this.selectedSla != null) { LogUtil.debug('ShippingComponent onDeleteConfirmationResult', this.selectedSla); this.loading = true; this._shippingService.removeCarrierSla(this.selectedSla).subscribe(res => { LogUtil.debug('ShippingComponent removeSla', this.selectedSla); let pk = this.selectedSla.carrierslaId; this.slaEdit = null; if (this.carrierEdit != null) { let idx2 = this.carrierEdit.slas.findIndex(rez => rez.carrierslaId == pk); if (idx2 !== -1) { this.carrierEdit.slas.splice(idx2, 1); this.carrierEdit.slas = this.carrierEdit.slas.slice(0, this.carrierEdit.slas.length); // reset to propagate changes } } this.selectedSla = null; this.loading = false; this.viewMode = ShippingComponent.CARRIER; }); } else if (this.selectedCarrier != null) { LogUtil.debug('ShippingComponent onDeleteConfirmationResult', this.selectedCarrier); this.loading = true; this._shippingService.removeCarrier(this.selectedCarrier).subscribe(res => { LogUtil.debug('ShippingComponent removeCarrier', this.selectedCarrier); this.selectedCarrier = null; this.carrierEdit = null; this.loading = false; this.getFilteredCarriers(); }); } } } onClearFilterCarrier() { this.carrierFilter = ''; this.getFilteredCarriers(); } private getFilteredCarriers() { LogUtil.debug('ShippingComponent getFilteredCarriers'); this.loading = true; this.carriers.searchContext.parameters.filter = [ this.carrierFilter ]; this.carriers.searchContext.size = Config.UI_TABLE_PAGE_SIZE; this._shippingService.getFilteredCarriers(this.carriers.searchContext).subscribe( allcarriers => { LogUtil.debug('ShippingComponent getFilteredCarriers', allcarriers); this.carriers = allcarriers; this.selectedCarrier = null; this.carrierEdit = null; this.viewMode = ShippingComponent.CARRIERS; this.changed = false; this.validForSave = false; this.loading = false; if (this.pgs == null || this.pgs.length == 0) { let lang = I18nEventBus.getI18nEventBus().current(); this._paymentService.getPaymentGateways(lang).subscribe(allpgs => { LogUtil.debug('ShippingComponent getPaymentGateways', allpgs); this.pgs = allpgs; }); } if (this.fcs.length == 0) { let _ctx: SearchContextVO = { parameters: { filter: [] }, start: 0, size: 1000, sortBy: null, sortDesc: false }; this._fulfilmentService.getFilteredFulfilmentCentres(_ctx).subscribe(allfcs => { LogUtil.debug('ShippingComponent getAllFulfilmentCentres', allfcs); this.fcs = allfcs != null ? allfcs.items : []; }); } if (this.slaTypes.length == 0) { this._shippingService.getCarrierSlaOptions().subscribe(options => { LogUtil.debug('ShippingComponent getCarrierSlaOptions', options); this.slaTypes = options; }); } }); } }
the_stack
import { Clipboard, InteractionManager, PromiseTask, SimpleTask } from 'react-native' import * as WebBrowser from 'expo-web-browser' import dayjs from 'dayjs' import AsyncStorage from '@components/@/react-native-async-storage' import { DEV, B, M } from '@constants' import { info } from './ui' /** * 排除null * @param {*} value */ export function isObject(value: any) { return typeof value === 'object' && !!value } /** * 缩短runAfterInteractions * @param {*} fn */ export function runAfter(fn: (() => any) | SimpleTask | PromiseTask) { return InteractionManager.runAfterInteractions(fn) } /** * 节流 * @param {*} callback */ export function throttle(callback: () => void, delay = 400) { let timeoutID let lastExec = 0 function wrapper() { // eslint-disable-next-line consistent-this const self = this const elapsed = Number(new Date()) - lastExec const args = arguments function exec() { lastExec = Number(new Date()) callback.apply(self, args) } clearTimeout(timeoutID) if (elapsed > delay) { exec() } else { timeoutID = setTimeout(exec, delay - elapsed) } } return wrapper } export function asc(a, b, fn) { let _a = a let _b = b if (typeof fn === 'function') { _a = fn(a) _b = fn(b) } if (_a === _b) return 0 if (_a < _b) return -1 return 1 } export function desc(a, b, fn) { let _a = a let _b = b if (typeof fn === 'function') { _a = fn(a) _b = fn(b) } if (_a === _b) return 0 if (_a > _b) return -1 return 1 } /** * 接口防并发请求问题严重, 暂时延迟一下, n个请求一组 * @param {*} fetchs */ export async function queue(fetchs = [], num = 2) { if (!fetchs.length) return false await Promise.all( new Array(num).fill(0).map(async () => { while (fetchs.length) { await fetchs.shift()() } }) ) return true } /** * 防抖 * @param {*} fn * @param {*} ms */ export function debounce(fn, ms = 400) { let timeout = null // 创建一个标记用来存放定时器的返回值 return function () { clearTimeout(timeout) // 每当用户输入的时候把前一个 setTimeout clear 掉 timeout = setTimeout(() => { // 然后又创建一个新的 setTimeout, 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数 fn.apply(this, arguments) }, ms) } } export function pick(obj, arr) { return arr.reduce( // eslint-disable-next-line no-sequences (acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {} ) } export function omit(obj, arr) { return Object.keys(obj).reduce( // eslint-disable-next-line no-sequences (acc, curr) => (arr.indexOf(curr) === -1 && (acc[curr] = obj[curr]), acc), {} ) } /** * 复制到剪贴板 * @param {*} string */ export function copy(string) { return Clipboard.setString(string) } /** * 安全toFixed * @param {*} object */ export function toFixed(value, num = 2) { return Number(value || 0).toFixed(num) } /** * 安全对象 * @param {*} url */ export function safeObject(object = {}) { Object.keys(object).forEach(key => { if (object[key] === undefined) { object[key] = '' } }) return object } /** * 浏览器打开网页 * @param {*} url */ export function open(url) { if (!url || typeof url !== 'string') { info('地址不合法') return false } WebBrowser.openBrowserAsync(url, { enableBarCollapsing: true, showInRecents: true }) if (DEV) console.info(url) return true } /** * 保存数据 * @version 190321 1.0 * @version 211112 2.0 * @param {*} key */ const setStorageLazyMap = {} export async function setStorage(key, data) { if (!key) return false const _data = JSON.stringify(data) if (_data.length >= 10000) { setStorageLazyMap[key] = _data } else { AsyncStorage.setItem(key, _data) } } // @version 211112 数据较大的键, 合并没必要的多次写入 let setStorageInterval if (setStorageInterval) clearInterval(setStorageInterval) setStorageInterval = setInterval(async () => { const keys = Object.keys(setStorageLazyMap) if (!keys.length) { // console.log('setStorage', 'empty') return } const setItems = [] keys.forEach(key => { setItems.push(async () => { // console.log( // 'setStorage', // key, // `${(setStorageLazyMap[key].length / 1000).toFixed(2)}kb` // ) AsyncStorage.setItem(key, setStorageLazyMap[key]) delete setStorageLazyMap[key] }) }) queue(setItems, 1) }, 60000) /** * 读取数据 * @version 190321 1.0 * @param {*} key */ export async function getStorage(key) { try { if (!key) return null const data = await AsyncStorage.getItem(key) return Promise.resolve(JSON.parse(data)) } catch (error) { return Promise.resolve(null) } } /** * url字符串化 * @version 190221 1.0 * @param {*} data * @param {*} encode */ export function urlStringify(data, encode = true) { if (!data) return '' const arr = Object.keys(data).map( key => `${key}=${encode ? encodeURIComponent(data[key]) : data[key]}` ) return arr.join('&') } /** * 补零 * @version 190301 1.0 * @param {*} n * @param {*} c */ export function pad(n) { return Number(n) < 10 ? `0${n}` : n } /** * 睡眠 * @version 180417 1.0 * @return {Promise} */ export function sleep(ms = 800) { return new Promise(resolve => setTimeout(resolve, ms)) } /** * 简易时间戳格式化函数 * @param {String} format 格式化格式 * @param {Int} timestamp 时间戳 * @return {String} */ export function date(format, timestamp) { // 假如第二个参数不存在,第一个参数作为timestamp if (!timestamp) { timestamp = format format = 'Y-m-d H:i:s' } const jsdate = timestamp ? new Date(timestamp * 1000) : new Date() const f = { Y: function () { return jsdate.getFullYear() }, y: function () { return (jsdate.getFullYear() + '').slice(2) }, m: function () { return pad(f.n()) }, d: function () { return pad(f.j()) }, H: function () { return pad(jsdate.getHours()) }, i: function () { return pad(jsdate.getMinutes()) }, s: function () { return pad(jsdate.getSeconds()) }, n: function () { return jsdate.getMonth() + 1 }, j: function () { return jsdate.getDate() } } return format.replace(/[\\]?([a-zA-Z])/g, function (t, s) { let ret = '' if (t != s) { ret = s } else { if (f[s]) { ret = f[s]() } else { ret = s } } return ret }) } /** * IOS8601时间转换 * @param {*} isostr */ export function parseIOS8601(isostr, format = 'Y-m-d') { if (!isostr) return '' const parts = isostr.match(/\d+/g) const timestamp = new Date( `${parts[0]}-${parts[1]}-${parts[2]} ${parts[3]}:${parts[4]}:${parts[5]}` ).getTime() / 1000 return date(format, timestamp) } /** * 返回timestamp */ export function getTimestamp(date = '') { const _date = trim(date) if (_date) return dayjs(_date).unix() return dayjs().unix() } /** * 返回最简单的时间表达 * @version 190430 1.1 * @return {String} *time 时间戳字符串 */ const _y = date('y', getTimestamp()) export function simpleTime(time = '') { if (!time) return '-' const _time = getTimestamp(time) const ymd = date('y-m-d', _time) .split('-') .filter((item, index) => (index === 0 ? item != _y : true)) .map(item => parseInt(item)) .join('-') const hi = date('H:i', _time) return `${ymd} ${hi}` } /** * 数组分组 * @param {*} arr * @param {*} num */ export function arrGroup(arr, num = 40) { const allData = [] let currData = [] for (let i = 0; i < arr.length; i += 1) { currData.push(arr[i]) if ((i != 0 && (i + 1) % num == 0) || i == arr.length - 1) { allData.push(currData) currData = [] } } return allData } /** * 首字母大写 * @param {*} str */ export function titleCase(str = '') { return str.replace(/( |^)[a-z]/g, L => L.toUpperCase()) } /** * 颜色过渡 * @param {*} startColor * @param {*} endColor * @param {*} step */ export function gradientColor(startRGB, endRGB, step) { const startR = startRGB[0] const startG = startRGB[1] const startB = startRGB[2] const endR = endRGB[0] const endG = endRGB[1] const endB = endRGB[2] const sR = (endR - startR) / step // 总差值 const sG = (endG - startG) / step const sB = (endB - startB) / step const colorArr = [] for (let i = 0; i < step; i += 1) { // 计算每一步的hex值 const rgb = `rgb(${parseInt(sR * i + startR)}, ${parseInt( sG * i + startG )}, ${parseInt(sB * i + startB)})` colorArr.push(rgb) } return colorArr } /** * @param {*} str */ export function trim(str = '') { return str.replace(/^\s+|\s+$/gm, '') } /** * 生成n位随机整数 * @param {*} n */ export function randomn(n) { if (n > 21) return null return Math.floor((Math.random() + 1) * Math.pow(10, n - 1)) } /** * 区间随机 * @param {*} start * @param {*} end */ export function random(start, end) { return Math.floor(Math.random() * (end - start + 1) + start) } /** * 数字分割加逗号 * @version 160811 1.0 * @version 160902 1.1 添加保留多少位小数 * @version 160907 1.2 代码优化,金额少于1000时直接返回 * @version 170103 1.3 判断n为0的情况 * @param {Number} s 数字 * @param {Int} n 保留多少位小数 * @return {String} */ export function formatNumber(s, n = 2, xsb?) { if (xsb) { if (s >= B) return `${formatNumber(s / B, 1)}亿` if (s >= M) return `${formatNumber(s / M, 1)}万` return formatNumber(s, n) } if (s === '') return Number(s).toFixed(n) if (typeof s === 'undefined') return Number(0).toFixed(n) s = parseFloat((s + '').replace(/[^\d.-]/g, '')).toFixed(n) + '' if (s == 0) return Number(s).toFixed(n) if (s < 1000) return Number(s).toFixed(n) const l = s.split('.')[0].split('').reverse(), r = s.split('.')[1] let t = '' for (let i = 0; i < l.length; i++) { t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? ',' : '') } if (typeof r === 'undefined') return t.split('').reverse().join('') return t.split('').reverse().join('') + '.' + r } /** * 时间戳距离现在时间的描述 * @version 170217 1.0 * @version 170605 1.1 修复年份非常小导致的问题 * @version 180628 1.2 [+]simple * @param {String} *timestamp 时间戳 * @param {String} overDaysToShowTime 多少天之后就显示具体时间 * @return {String} simple 简单模式 */ export function lastDate(timestamp, simple = true) { const d = new Date(timestamp * 1000) const _date = `${d.getFullYear()}-${ d.getMonth() + 1 }-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}` const dateTime = new Date(_date) const currentTime = new Date() let totalTime = currentTime.getTime() - dateTime.getTime() let _ const getNumber = () => Math.floor(totalTime / _) const modTimestamp = () => totalTime % _ _ = 1000 * 60 * 60 * 24 * 365 const years = getNumber() totalTime = modTimestamp() _ = 1000 * 60 * 60 * 24 * 30 const months = getNumber() totalTime = modTimestamp() if (years > 0) return simple ? `${years}年前` : `${years}年${months}月前` _ = 1000 * 60 * 60 * 24 * 7 const weeks = getNumber() totalTime = modTimestamp() if (months > 0) return simple ? `${months}月前` : `${months}月${weeks}周前` _ = 1000 * 60 * 60 * 24 const days = getNumber() totalTime = modTimestamp() if (weeks > 0) return simple ? `${weeks}周前` : `${weeks}周${days}天前` _ = 1000 * 60 * 60 const hours = getNumber() totalTime = modTimestamp() if (days > 0) return simple ? `${days}天前` : `${days}天${hours}时前` _ = 1000 * 60 const minutes = getNumber() totalTime = modTimestamp() if (hours > 0) return simple ? `${hours}时前` : `${hours}时${minutes}分前` if (minutes > 0) return `${minutes}分前` return '刚刚' } /** * 清除搜索关键字的特殊字符 * @param {*} str */ export function cleanQ(str) { return String(str).replace(/['!"#$%&\\'()*+,./:;<=>?@[\\\]^`{|}~']/g, ' ') } /** * 字符串相似度 * @param {*} s * @param {*} t * @param {*} f */ export function similar(s, t, f) { if (!s || !t) return 0 const l = s.length > t.length ? s.length : t.length const n = s.length const m = t.length const d = [] f = f || 3 const min = (a, b, c) => (a < b ? (a < c ? a : c) : b < c ? b : c) let i let j let si let tj let cost if (n === 0) return m if (m === 0) return n for (i = 0; i <= n; i += 1) { d[i] = [] d[i][0] = i } for (j = 0; j <= m; j += 1) { d[0][j] = j } for (i = 1; i <= n; i += 1) { si = s.charAt(i - 1) for (j = 1; j <= m; j += 1) { tj = t.charAt(j - 1) if (si === tj) { cost = 0 } else { cost = 1 } d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost) } } const res = 1 - d[n][m] / l return res.toFixed(f) }
the_stack
import type * as vscode from 'vscode'; import * as errors from 'vs/base/common/errors'; import { IDisposable } from 'vs/base/common/lifecycle'; import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { ExtensionActivationReason, MissingExtensionDependency } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { Barrier } from 'vs/base/common/async'; /** * Represents the source code (module) of an extension. */ export interface IExtensionModule { activate?(ctx: vscode.ExtensionContext): Promise<IExtensionAPI>; deactivate?(): void; } /** * Represents the API of an extension (return value of `activate`). */ export interface IExtensionAPI { // _extensionAPIBrand: any; } export type ExtensionActivationTimesFragment = { startup?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true }; codeLoadingTime?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true }; activateCallTime?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true }; activateResolvedTime?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true }; }; export class ExtensionActivationTimes { public static readonly NONE = new ExtensionActivationTimes(false, -1, -1, -1); public readonly startup: boolean; public readonly codeLoadingTime: number; public readonly activateCallTime: number; public readonly activateResolvedTime: number; constructor(startup: boolean, codeLoadingTime: number, activateCallTime: number, activateResolvedTime: number) { this.startup = startup; this.codeLoadingTime = codeLoadingTime; this.activateCallTime = activateCallTime; this.activateResolvedTime = activateResolvedTime; } } export class ExtensionActivationTimesBuilder { private readonly _startup: boolean; private _codeLoadingStart: number; private _codeLoadingStop: number; private _activateCallStart: number; private _activateCallStop: number; private _activateResolveStart: number; private _activateResolveStop: number; constructor(startup: boolean) { this._startup = startup; this._codeLoadingStart = -1; this._codeLoadingStop = -1; this._activateCallStart = -1; this._activateCallStop = -1; this._activateResolveStart = -1; this._activateResolveStop = -1; } private _delta(start: number, stop: number): number { if (start === -1 || stop === -1) { return -1; } return stop - start; } public build(): ExtensionActivationTimes { return new ExtensionActivationTimes( this._startup, this._delta(this._codeLoadingStart, this._codeLoadingStop), this._delta(this._activateCallStart, this._activateCallStop), this._delta(this._activateResolveStart, this._activateResolveStop) ); } public codeLoadingStart(): void { this._codeLoadingStart = Date.now(); } public codeLoadingStop(): void { this._codeLoadingStop = Date.now(); } public activateCallStart(): void { this._activateCallStart = Date.now(); } public activateCallStop(): void { this._activateCallStop = Date.now(); } public activateResolveStart(): void { this._activateResolveStart = Date.now(); } public activateResolveStop(): void { this._activateResolveStop = Date.now(); } } export class ActivatedExtension { public readonly activationFailed: boolean; public readonly activationFailedError: Error | null; public readonly activationTimes: ExtensionActivationTimes; public readonly module: IExtensionModule; public readonly exports: IExtensionAPI | undefined; public readonly subscriptions: IDisposable[]; constructor( activationFailed: boolean, activationFailedError: Error | null, activationTimes: ExtensionActivationTimes, module: IExtensionModule, exports: IExtensionAPI | undefined, subscriptions: IDisposable[] ) { this.activationFailed = activationFailed; this.activationFailedError = activationFailedError; this.activationTimes = activationTimes; this.module = module; this.exports = exports; this.subscriptions = subscriptions; } } export class EmptyExtension extends ActivatedExtension { constructor(activationTimes: ExtensionActivationTimes) { super(false, null, activationTimes, { activate: undefined, deactivate: undefined }, undefined, []); } } export class HostExtension extends ActivatedExtension { constructor() { super(false, null, ExtensionActivationTimes.NONE, { activate: undefined, deactivate: undefined }, undefined, []); } } export class FailedExtension extends ActivatedExtension { constructor(activationError: Error) { super(true, activationError, ExtensionActivationTimes.NONE, { activate: undefined, deactivate: undefined }, undefined, []); } } export interface IExtensionsActivatorHost { onExtensionActivationError(extensionId: ExtensionIdentifier, error: Error | null, missingExtensionDependency: MissingExtensionDependency | null): void; actualActivateExtension(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<ActivatedExtension>; } type ActivationIdAndReason = { id: ExtensionIdentifier; reason: ExtensionActivationReason }; export class ExtensionsActivator implements IDisposable { private readonly _registry: ExtensionDescriptionRegistry; private readonly _resolvedExtensionsSet: Set<string>; private readonly _externalExtensionsMap: Map<string, ExtensionIdentifier>; private readonly _host: IExtensionsActivatorHost; private readonly _operations: Map<string, ActivationOperation>; /** * A map of already activated events to speed things up if the same activation event is triggered multiple times. */ private readonly _alreadyActivatedEvents: { [activationEvent: string]: boolean }; constructor( registry: ExtensionDescriptionRegistry, resolvedExtensions: ExtensionIdentifier[], externalExtensions: ExtensionIdentifier[], host: IExtensionsActivatorHost, @ILogService private readonly _logService: ILogService ) { this._registry = registry; this._resolvedExtensionsSet = new Set<string>(); resolvedExtensions.forEach((extensionId) => this._resolvedExtensionsSet.add(ExtensionIdentifier.toKey(extensionId))); this._externalExtensionsMap = new Map<string, ExtensionIdentifier>(); externalExtensions.forEach((extensionId) => this._externalExtensionsMap.set(ExtensionIdentifier.toKey(extensionId), extensionId)); this._host = host; this._operations = new Map<string, ActivationOperation>(); this._alreadyActivatedEvents = Object.create(null); } public dispose(): void { for (const [_, op] of this._operations) { op.dispose(); } } public isActivated(extensionId: ExtensionIdentifier): boolean { const op = this._operations.get(ExtensionIdentifier.toKey(extensionId)); return Boolean(op && op.value); } public getActivatedExtension(extensionId: ExtensionIdentifier): ActivatedExtension { const op = this._operations.get(ExtensionIdentifier.toKey(extensionId)); if (!op || !op.value) { throw new Error(`Extension '${extensionId.value}' is not known or not activated`); } return op.value; } public async activateByEvent(activationEvent: string, startup: boolean): Promise<void> { if (this._alreadyActivatedEvents[activationEvent]) { return; } const activateExtensions = this._registry.getExtensionDescriptionsForActivationEvent(activationEvent); await this._activateExtensions(activateExtensions.map(e => ({ id: e.identifier, reason: { startup, extensionId: e.identifier, activationEvent } }))); this._alreadyActivatedEvents[activationEvent] = true; } public activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> { const desc = this._registry.getExtensionDescription(extensionId); if (!desc) { throw new Error(`Extension '${extensionId}' is not known`); } return this._activateExtensions([{ id: desc.identifier, reason }]); } private async _activateExtensions(extensions: ActivationIdAndReason[]): Promise<void> { const operations = extensions .filter((p) => !this.isActivated(p.id)) .map(ext => this._handleActivationRequest(ext)); await Promise.all(operations.map(op => op.wait())); } /** * Handle semantics related to dependencies for `currentExtension`. * We don't need to worry about dependency loops because they are handled by the registry. */ private _handleActivationRequest(currentActivation: ActivationIdAndReason): ActivationOperation { if (this._operations.has(ExtensionIdentifier.toKey(currentActivation.id))) { return this._operations.get(ExtensionIdentifier.toKey(currentActivation.id))!; } if (this._externalExtensionsMap.has(ExtensionIdentifier.toKey(currentActivation.id))) { return this._createAndSaveOperation(currentActivation, null, [], null); } const currentExtension = this._registry.getExtensionDescription(currentActivation.id); if (!currentExtension) { // Error condition 0: unknown extension const error = new Error(`Cannot activate unknown extension '${currentActivation.id.value}'`); const result = this._createAndSaveOperation(currentActivation, null, [], new FailedExtension(error)); this._host.onExtensionActivationError( currentActivation.id, error, new MissingExtensionDependency(currentActivation.id.value) ); return result; } const deps: ActivationOperation[] = []; const depIds = (typeof currentExtension.extensionDependencies === 'undefined' ? [] : currentExtension.extensionDependencies); for (const depId of depIds) { if (this._resolvedExtensionsSet.has(ExtensionIdentifier.toKey(depId))) { // This dependency is already resolved continue; } const dep = this._operations.get(ExtensionIdentifier.toKey(depId)); if (dep) { deps.push(dep); continue; } if (this._externalExtensionsMap.has(ExtensionIdentifier.toKey(depId))) { // must first wait for the dependency to activate deps.push(this._handleActivationRequest({ id: this._externalExtensionsMap.get(ExtensionIdentifier.toKey(depId))!, reason: currentActivation.reason })); continue; } const depDesc = this._registry.getExtensionDescription(depId); if (depDesc) { if (!depDesc.main && !depDesc.browser) { // this dependency does not need to activate because it is descriptive only continue; } // must first wait for the dependency to activate deps.push(this._handleActivationRequest({ id: depDesc.identifier, reason: currentActivation.reason })); continue; } // Error condition 1: unknown dependency const currentExtensionFriendlyName = currentExtension.displayName || currentExtension.identifier.value; const error = new Error(`Cannot activate the '${currentExtensionFriendlyName}' extension because it depends on unknown extension '${depId}'`); const result = this._createAndSaveOperation(currentActivation, currentExtension.displayName, [], new FailedExtension(error)); this._host.onExtensionActivationError( currentExtension.identifier, error, new MissingExtensionDependency(depId) ); return result; } return this._createAndSaveOperation(currentActivation, currentExtension.displayName, deps, null); } private _createAndSaveOperation(activation: ActivationIdAndReason, displayName: string | null | undefined, deps: ActivationOperation[], value: ActivatedExtension | null): ActivationOperation { const operation = new ActivationOperation(activation.id, displayName, activation.reason, deps, value, this._host, this._logService); this._operations.set(ExtensionIdentifier.toKey(activation.id), operation); return operation; } } class ActivationOperation { private readonly _barrier = new Barrier(); private _isDisposed = false; public get value(): ActivatedExtension | null { return this._value; } public get friendlyName(): string { return this._displayName || this._id.value; } constructor( private readonly _id: ExtensionIdentifier, private readonly _displayName: string | null | undefined, private readonly _reason: ExtensionActivationReason, private readonly _deps: ActivationOperation[], private _value: ActivatedExtension | null, private readonly _host: IExtensionsActivatorHost, @ILogService private readonly _logService: ILogService ) { this._initialize(); } public dispose(): void { this._isDisposed = true; } public wait() { return this._barrier.wait(); } private async _initialize(): Promise<void> { await this._waitForDepsThenActivate(); this._barrier.open(); } private async _waitForDepsThenActivate(): Promise<void> { if (this._value) { // this operation is already finished return; } while (this._deps.length > 0) { // remove completed deps for (let i = 0; i < this._deps.length; i++) { const dep = this._deps[i]; if (dep.value && !dep.value.activationFailed) { // the dependency is already activated OK this._deps.splice(i, 1); i--; continue; } if (dep.value && dep.value.activationFailed) { // Error condition 2: a dependency has already failed activation const error = new Error(`Cannot activate the '${this.friendlyName}' extension because its dependency '${dep.friendlyName}' failed to activate`); (<any>error).detail = dep.value.activationFailedError; this._value = new FailedExtension(error); this._host.onExtensionActivationError(this._id, error, null); return; } } if (this._deps.length > 0) { // wait for one dependency await Promise.race(this._deps.map(dep => dep.wait())); } } await this._activate(); } private async _activate(): Promise<void> { try { this._value = await this._host.actualActivateExtension(this._id, this._reason); } catch (err) { const error = new Error(); if (err && err.name) { error.name = err.name; } if (err && err.message) { error.message = `Activating extension '${this._id.value}' failed: ${err.message}.`; } else { error.message = `Activating extension '${this._id.value}' failed: ${err}.`; } if (err && err.stack) { error.stack = err.stack; } // Treat the extension as being empty this._value = new FailedExtension(error); if (this._isDisposed && errors.isCancellationError(err)) { // It is expected for ongoing activations to fail if the extension host is going down // So simply ignore and don't log canceled errors in this case return; } this._host.onExtensionActivationError(this._id, error, null); this._logService.error(`Activating extension ${this._id.value} failed due to an error:`); this._logService.error(err); } } }
the_stack
* This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export type UseTabs = boolean; export type UseTabs1 = true | false; export type SemiColons = "always" | "prefer" | "asi"; export type SemiColons1 = string; export type QuoteStyle = "alwaysDouble" | "alwaysSingle" | "preferDouble" | "preferSingle"; export type QuoteStyle1 = string; export type NewLineKind = "auto" | "crlf" | "lf" | "system"; export type NewLineKind1 = string; export type UseBraces = "maintain" | "whenNotSingleLine" | "always" | "preferNone"; export type UseBraces1 = string; export type BracePosition = "maintain" | "sameLine" | "nextLine" | "sameLineUnlessHanging"; export type BracePosition1 = string; export type SingleBodyPosition = "maintain" | "sameLine" | "nextLine"; export type SingleBodyPosition1 = string; export type NextControlFlowPosition = "maintain" | "sameLine" | "nextLine"; export type NextControlFlowPosition1 = string; export type TrailingCommas = "never" | "always" | "onlyMultiLine"; export type TrailingCommas1 = string; export type OperatorPosition = "maintain" | "sameLine" | "nextLine"; export type OperatorPosition1 = string; export type PreferHanging = boolean; export type PreferHanging1 = true | false; export type PreferSingleLine = boolean; export type PreferSingleLine1 = true | false; export type Deno = boolean; export type Deno1 = true | false; export type ArrowFunctionUseParentheses = "force" | "maintain" | "preferNone"; export type ArrowFunctionUseParentheses1 = string; export type BinaryExpressionLinePerExpression = boolean; export type BinaryExpressionLinePerExpression1 = true | false; export type JsxQuoteStyle = "preferDouble" | "preferSingle"; export type JsxQuoteStyle1 = string; export type JsxMultiLineParens = "never" | "prefer" | "always"; export type JsxMultiLineParens1 = string; export type MemberExpressionLinePerExpression = boolean; export type MemberExpressionLinePerExpression1 = true | false; export type TypeLiteralSeparatorKind = "semiColon" | "comma"; export type TypeLiteralSeparatorKind1 = string; export type EnumDeclarationMemberSpacing = "newLine" | "blankLine" | "maintain"; export type EnumDeclarationMemberSpacing1 = string; export type SpaceSurroundingProperties = boolean; export type SpaceSurroundingProperties1 = true | false; export type ObjectExpressionSpaceSurroundingProperties = boolean; export type ObjectExpressionSpaceSurroundingProperties1 = true | false; export type ObjectPatternSpaceSurroundingProperties = boolean; export type ObjectPatternSpaceSurroundingProperties1 = true | false; export type TypeLiteralSpaceSurroundingProperties = boolean; export type TypeLiteralSpaceSurroundingProperties1 = true | false; export type BinaryExpressionSpaceSurroundingBitwiseAndArithmeticOperator = boolean; export type BinaryExpressionSpaceSurroundingBitwiseAndArithmeticOperator1 = true | false; export type CommentLineForceSpaceAfterSlashes = boolean; export type CommentLineForceSpaceAfterSlashes1 = true | false; export type ConstructorSpaceBeforeParentheses = boolean; export type ConstructorSpaceBeforeParentheses1 = true | false; export type ConstructorTypeSpaceAfterNewKeyword = boolean; export type ConstructorTypeSpaceAfterNewKeyword1 = true | false; export type ConstructSignatureSpaceAfterNewKeyword = boolean; export type ConstructSignatureSpaceAfterNewKeyword1 = true | false; export type DoWhileStatementSpaceAfterWhileKeyword = boolean; export type DoWhileStatementSpaceAfterWhileKeyword1 = true | false; export type ExportDeclarationSpaceSurroundingNamedExports = boolean; export type ExportDeclarationSpaceSurroundingNamedExports1 = true | false; export type ForInStatementSpaceAfterForKeyword = boolean; export type ForInStatementSpaceAfterForKeyword1 = true | false; export type ForOfStatementSpaceAfterForKeyword = boolean; export type ForOfStatementSpaceAfterForKeyword1 = true | false; export type ForStatementSpaceAfterForKeyword = boolean; export type ForStatementSpaceAfterForKeyword1 = true | false; export type ForStatementSpaceAfterSemiColons = boolean; export type ForStatementSpaceAfterSemiColons1 = true | false; export type FunctionDeclarationSpaceBeforeParentheses = boolean; export type FunctionDeclarationSpaceBeforeParentheses1 = true | false; export type FunctionExpressionSpaceBeforeParentheses = boolean; export type FunctionExpressionSpaceBeforeParentheses1 = true | false; export type FunctionExpressionSpaceAfterFunctionKeyword = boolean; export type FunctionExpressionSpaceAfterFunctionKeyword1 = true | false; export type GetAccessorSpaceBeforeParentheses = boolean; export type GetAccessorSpaceBeforeParentheses1 = true | false; export type IfStatementSpaceAfterIfKeyword = boolean; export type IfStatementSpaceAfterIfKeyword1 = true | false; export type ImportDeclarationSpaceSurroundingNamedImports = boolean; export type ImportDeclarationSpaceSurroundingNamedImports1 = true | false; export type JsxElementSpaceBeforeSelfClosingTagSlash = boolean; export type JsxElementSpaceBeforeSelfClosingTagSlash1 = true | false; export type JsxExpressionContainerSpaceSurroundingExpression = boolean; export type JsxExpressionContainerSpaceSurroundingExpression1 = true | false; export type MethodSpaceBeforeParentheses = boolean; export type MethodSpaceBeforeParentheses1 = true | false; export type SetAccessorSpaceBeforeParentheses = boolean; export type SetAccessorSpaceBeforeParentheses1 = true | false; export type TaggedTemplateSpaceBeforeLiteral = boolean; export type TaggedTemplateSpaceBeforeLiteral1 = true | false; export type TypeAnnotationSpaceBeforeColon = boolean; export type TypeAnnotationSpaceBeforeColon1 = true | false; export type TypeAssertionSpaceBeforeExpression = boolean; export type TypeAssertionSpaceBeforeExpression1 = true | false; export type WhileStatementSpaceAfterWhileKeyword = boolean; export type WhileStatementSpaceAfterWhileKeyword1 = true | false; export type SortOrder = "maintain" | "caseSensitive" | "caseInsensitive"; export type SortOrder1 = string; export interface Options { /** * Whether the configuration is not allowed to be overriden or extended. */ locked?: boolean; /** * The width of a line the printer will try to stay under. Note that the printer may exceed this width in certain cases. */ lineWidth?: number; /** * The number of columns for an indent. */ indentWidth?: number; /** * Whether to use tabs (true) or spaces (false). */ useTabs?: UseTabs & UseTabs1; /** * How semi-colons should be used. */ semiColons?: SemiColons & SemiColons1; /** * How to use single or double quotes. */ quoteStyle?: QuoteStyle & QuoteStyle1; /** * The kind of newline to use. */ newLineKind?: NewLineKind & NewLineKind1; /** * If braces should be used or not. */ useBraces?: UseBraces & UseBraces1; /** * Where to place the opening brace. */ bracePosition?: BracePosition & BracePosition1; /** * Where to place the expression of a statement that could possibly be on one line (ex. `if (true) console.log(5);`). */ singleBodyPosition?: SingleBodyPosition & SingleBodyPosition1; /** * Where to place the next control flow within a control flow statement. */ nextControlFlowPosition?: NextControlFlowPosition & NextControlFlowPosition1; /** * If trailing commas should be used. */ trailingCommas?: TrailingCommas & TrailingCommas1; /** * Where to place the operator for expressions that span multiple lines. */ operatorPosition?: OperatorPosition & OperatorPosition1; /** * Set to prefer hanging indentation when exceeding the line width instead of making code split up on multiple lines. */ preferHanging?: PreferHanging & PreferHanging1; /** * If code should revert back from being on multiple lines to being on a single line when able. */ preferSingleLine?: PreferSingleLine & PreferSingleLine1; /** * Top level configuration that sets the configuration to what is used in Deno. */ deno?: Deno & Deno1; /** * Whether to use parentheses around a single parameter in an arrow function. */ "arrowFunction.useParentheses"?: ArrowFunctionUseParentheses & ArrowFunctionUseParentheses1; /** * Whether to force a line per expression when spanning multiple lines. */ "binaryExpression.linePerExpression"?: BinaryExpressionLinePerExpression & BinaryExpressionLinePerExpression1; /** * How to use single or double quotes in JSX attributes. */ "jsx.quoteStyle"?: JsxQuoteStyle & JsxQuoteStyle1; /** * Surrounds the top-most JSX element or fragment in parentheses when it spans multiple lines. */ "jsx.multiLineParens"?: JsxMultiLineParens & JsxMultiLineParens1; /** * Whether to force a line per expression when spanning multiple lines. */ "memberExpression.linePerExpression"?: MemberExpressionLinePerExpression & MemberExpressionLinePerExpression1; /** * The kind of separator to use in type literals. */ "typeLiteral.separatorKind"?: TypeLiteralSeparatorKind & TypeLiteralSeparatorKind1; "typeLiteral.separatorKind.singleLine"?: TypeLiteralSeparatorKind & TypeLiteralSeparatorKind1; "typeLiteral.separatorKind.multiLine"?: TypeLiteralSeparatorKind & TypeLiteralSeparatorKind1; /** * How to space the members of an enum. */ "enumDeclaration.memberSpacing"?: EnumDeclarationMemberSpacing & EnumDeclarationMemberSpacing1; /** * Whether to add a space surrounding the properties of single line object-like nodes. */ spaceSurroundingProperties?: SpaceSurroundingProperties & SpaceSurroundingProperties1; /** * Whether to add a space surrounding the properties of a single line object expression. */ "objectExpression.spaceSurroundingProperties"?: ObjectExpressionSpaceSurroundingProperties & ObjectExpressionSpaceSurroundingProperties1; /** * Whether to add a space surrounding the properties of a single line object pattern. */ "objectPattern.spaceSurroundingProperties"?: ObjectPatternSpaceSurroundingProperties & ObjectPatternSpaceSurroundingProperties1; /** * Whether to add a space surrounding the properties of a single line type literal. */ "typeLiteral.spaceSurroundingProperties"?: TypeLiteralSpaceSurroundingProperties & TypeLiteralSpaceSurroundingProperties1; /** * Whether to surround the operator in a binary expression with spaces. */ "binaryExpression.spaceSurroundingBitwiseAndArithmeticOperator"?: BinaryExpressionSpaceSurroundingBitwiseAndArithmeticOperator & BinaryExpressionSpaceSurroundingBitwiseAndArithmeticOperator1; /** * Forces a space after the double slash in a comment line. */ "commentLine.forceSpaceAfterSlashes"?: CommentLineForceSpaceAfterSlashes & CommentLineForceSpaceAfterSlashes1; /** * Whether to add a space before the parentheses of a constructor. */ "constructor.spaceBeforeParentheses"?: ConstructorSpaceBeforeParentheses & ConstructorSpaceBeforeParentheses1; /** * Whether to add a space after the `new` keyword in a constructor type. */ "constructorType.spaceAfterNewKeyword"?: ConstructorTypeSpaceAfterNewKeyword & ConstructorTypeSpaceAfterNewKeyword1; /** * Whether to add a space after the `new` keyword in a construct signature. */ "constructSignature.spaceAfterNewKeyword"?: ConstructSignatureSpaceAfterNewKeyword & ConstructSignatureSpaceAfterNewKeyword1; /** * Whether to add a space after the `while` keyword in a do while statement. */ "doWhileStatement.spaceAfterWhileKeyword"?: DoWhileStatementSpaceAfterWhileKeyword & DoWhileStatementSpaceAfterWhileKeyword1; /** * Whether to add spaces around named exports in an export declaration. */ "exportDeclaration.spaceSurroundingNamedExports"?: ExportDeclarationSpaceSurroundingNamedExports & ExportDeclarationSpaceSurroundingNamedExports1; /** * Whether to add a space after the `for` keyword in a "for in" statement. */ "forInStatement.spaceAfterForKeyword"?: ForInStatementSpaceAfterForKeyword & ForInStatementSpaceAfterForKeyword1; /** * Whether to add a space after the `for` keyword in a "for of" statement. */ "forOfStatement.spaceAfterForKeyword"?: ForOfStatementSpaceAfterForKeyword & ForOfStatementSpaceAfterForKeyword1; /** * Whether to add a space after the `for` keyword in a "for" statement. */ "forStatement.spaceAfterForKeyword"?: ForStatementSpaceAfterForKeyword & ForStatementSpaceAfterForKeyword1; /** * Whether to add a space after the semi-colons in a "for" statement. */ "forStatement.spaceAfterSemiColons"?: ForStatementSpaceAfterSemiColons & ForStatementSpaceAfterSemiColons1; /** * Whether to add a space before the parentheses of a function declaration. */ "functionDeclaration.spaceBeforeParentheses"?: FunctionDeclarationSpaceBeforeParentheses & FunctionDeclarationSpaceBeforeParentheses1; /** * Whether to add a space before the parentheses of a function expression. */ "functionExpression.spaceBeforeParentheses"?: FunctionExpressionSpaceBeforeParentheses & FunctionExpressionSpaceBeforeParentheses1; /** * Whether to add a space after the function keyword of a function expression. */ "functionExpression.spaceAfterFunctionKeyword"?: FunctionExpressionSpaceAfterFunctionKeyword & FunctionExpressionSpaceAfterFunctionKeyword1; /** * Whether to add a space before the parentheses of a get accessor. */ "getAccessor.spaceBeforeParentheses"?: GetAccessorSpaceBeforeParentheses & GetAccessorSpaceBeforeParentheses1; /** * Whether to add a space after the `if` keyword in an "if" statement. */ "ifStatement.spaceAfterIfKeyword"?: IfStatementSpaceAfterIfKeyword & IfStatementSpaceAfterIfKeyword1; /** * Whether to add spaces around named imports in an import declaration. */ "importDeclaration.spaceSurroundingNamedImports"?: ImportDeclarationSpaceSurroundingNamedImports & ImportDeclarationSpaceSurroundingNamedImports1; /** * Whether to add a space before a JSX element's slash when self closing. */ "jsxElement.spaceBeforeSelfClosingTagSlash"?: JsxElementSpaceBeforeSelfClosingTagSlash & JsxElementSpaceBeforeSelfClosingTagSlash1; /** * Whether to add a space surrounding the expression of a JSX container. */ "jsxExpressionContainer.spaceSurroundingExpression"?: JsxExpressionContainerSpaceSurroundingExpression & JsxExpressionContainerSpaceSurroundingExpression1; /** * Whether to add a space before the parentheses of a method. */ "method.spaceBeforeParentheses"?: MethodSpaceBeforeParentheses & MethodSpaceBeforeParentheses1; /** * Whether to add a space before the parentheses of a set accessor. */ "setAccessor.spaceBeforeParentheses"?: SetAccessorSpaceBeforeParentheses & SetAccessorSpaceBeforeParentheses1; /** * Whether to add a space before the literal in a tagged templte. */ "taggedTemplate.spaceBeforeLiteral"?: TaggedTemplateSpaceBeforeLiteral & TaggedTemplateSpaceBeforeLiteral1; /** * Whether to add a space before the colon of a type annotation. */ "typeAnnotation.spaceBeforeColon"?: TypeAnnotationSpaceBeforeColon & TypeAnnotationSpaceBeforeColon1; /** * Whether to add a space before the expression in a type assertion. */ "typeAssertion.spaceBeforeExpression"?: TypeAssertionSpaceBeforeExpression & TypeAssertionSpaceBeforeExpression1; /** * Whether to add a space after the `while` keyword in a while statement. */ "whileStatement.spaceAfterWhileKeyword"?: WhileStatementSpaceAfterWhileKeyword & WhileStatementSpaceAfterWhileKeyword1; /** * The kind of sort ordering to use. */ "module.sortImportDeclarations"?: SortOrder & SortOrder1; "module.sortExportDeclarations"?: SortOrder & SortOrder1; "exportDeclaration.sortNamedExports"?: SortOrder & SortOrder1; "importDeclaration.sortNamedImports"?: SortOrder & SortOrder1; /** * The text to use for an ignore comment (ex. `// dprint-ignore`). */ ignoreNodeCommentText?: string; /** * The text to use for a file ignore comment (ex. `// dprint-ignore-file`). */ ignoreFileCommentText?: string; "forInStatement.useBraces"?: UseBraces & UseBraces1; "forOfStatement.useBraces"?: UseBraces & UseBraces1; "forStatement.useBraces"?: UseBraces & UseBraces1; "ifStatement.useBraces"?: UseBraces & UseBraces1; "whileStatement.useBraces"?: UseBraces & UseBraces1; "arrowFunction.bracePosition"?: BracePosition & BracePosition1; "classDeclaration.bracePosition"?: BracePosition & BracePosition1; "classExpression.bracePosition"?: BracePosition & BracePosition1; "constructor.bracePosition"?: BracePosition & BracePosition1; "doWhileStatement.bracePosition"?: BracePosition & BracePosition1; "enumDeclaration.bracePosition"?: BracePosition & BracePosition1; "forInStatement.bracePosition"?: BracePosition & BracePosition1; "forOfStatement.bracePosition"?: BracePosition & BracePosition1; "forStatement.bracePosition"?: BracePosition & BracePosition1; "functionDeclaration.bracePosition"?: BracePosition & BracePosition1; "functionExpression.bracePosition"?: BracePosition & BracePosition1; "getAccessor.bracePosition"?: BracePosition & BracePosition1; "ifStatement.bracePosition"?: BracePosition & BracePosition1; "interfaceDeclaration.bracePosition"?: BracePosition & BracePosition1; "moduleDeclaration.bracePosition"?: BracePosition & BracePosition1; "method.bracePosition"?: BracePosition & BracePosition1; "setAccessor.bracePosition"?: BracePosition & BracePosition1; "staticBlock.bracePosition"?: BracePosition & BracePosition1; "switchStatement.bracePosition"?: BracePosition & BracePosition1; "switchCase.bracePosition"?: BracePosition & BracePosition1; "tryStatement.bracePosition"?: BracePosition & BracePosition1; "whileStatement.bracePosition"?: BracePosition & BracePosition1; "forInStatement.singleBodyPosition"?: SingleBodyPosition & SingleBodyPosition1; "forOfStatement.singleBodyPosition"?: SingleBodyPosition & SingleBodyPosition1; "forStatement.singleBodyPosition"?: SingleBodyPosition & SingleBodyPosition1; "ifStatement.singleBodyPosition"?: SingleBodyPosition & SingleBodyPosition1; "whileStatement.singleBodyPosition"?: SingleBodyPosition & SingleBodyPosition1; "ifStatement.nextControlFlowPosition"?: NextControlFlowPosition & NextControlFlowPosition1; "tryStatement.nextControlFlowPosition"?: NextControlFlowPosition & NextControlFlowPosition1; "arguments.trailingCommas"?: TrailingCommas & TrailingCommas1; "parameters.trailingCommas"?: TrailingCommas & TrailingCommas1; "arrayExpression.trailingCommas"?: TrailingCommas & TrailingCommas1; "arrayPattern.trailingCommas"?: TrailingCommas & TrailingCommas1; "enumDeclaration.trailingCommas"?: TrailingCommas & TrailingCommas1; "exportDeclaration.trailingCommas"?: TrailingCommas & TrailingCommas1; "importDeclaration.trailingCommas"?: TrailingCommas & TrailingCommas1; "objectExpression.trailingCommas"?: TrailingCommas & TrailingCommas1; "objectPattern.trailingCommas"?: TrailingCommas & TrailingCommas1; "tupleType.trailingCommas"?: TrailingCommas & TrailingCommas1; "typeLiteral.trailingCommas"?: TrailingCommas & TrailingCommas1; "typeParameters.trailingCommas"?: TrailingCommas & TrailingCommas1; "binaryExpression.operatorPosition"?: OperatorPosition & OperatorPosition1; "conditionalExpression.operatorPosition"?: OperatorPosition & OperatorPosition1; "arguments.preferHanging"?: PreferHanging & PreferHanging1; "arrayExpression.preferHanging"?: PreferHanging & PreferHanging1; "arrayPattern.preferHanging"?: PreferHanging & PreferHanging1; "doWhileStatement.preferHanging"?: PreferHanging & PreferHanging1; "exportDeclaration.preferHanging"?: PreferHanging & PreferHanging1; "extendsClause.preferHanging"?: PreferHanging & PreferHanging1; "forInStatement.preferHanging"?: PreferHanging & PreferHanging1; "forOfStatement.preferHanging"?: PreferHanging & PreferHanging1; "forStatement.preferHanging"?: PreferHanging & PreferHanging1; "ifStatement.preferHanging"?: PreferHanging & PreferHanging1; "implementsClause.preferHanging"?: PreferHanging & PreferHanging1; "importDeclaration.preferHanging"?: PreferHanging & PreferHanging1; "jsxAttributes.preferHanging"?: PreferHanging & PreferHanging1; "objectExpression.preferHanging"?: PreferHanging & PreferHanging1; "objectPattern.preferHanging"?: PreferHanging & PreferHanging1; "parameters.preferHanging"?: PreferHanging & PreferHanging1; "sequenceExpression.preferHanging"?: PreferHanging & PreferHanging1; "switchStatement.preferHanging"?: PreferHanging & PreferHanging1; "tupleType.preferHanging"?: PreferHanging & PreferHanging1; "typeLiteral.preferHanging"?: PreferHanging & PreferHanging1; "typeParameters.preferHanging"?: PreferHanging & PreferHanging1; "unionAndIntersectionType.preferHanging"?: PreferHanging & PreferHanging1; "variableStatement.preferHanging"?: PreferHanging & PreferHanging1; "whileStatement.preferHanging"?: PreferHanging & PreferHanging1; "arrayExpression.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "arrayPattern.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "arguments.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "binaryExpression.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "computed.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "conditionalExpression.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "conditionalType.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "decorators.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "exportDeclaration.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "forStatement.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "importDeclaration.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "jsxAttributes.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "jsxElement.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "mappedType.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "memberExpression.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "objectExpression.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "objectPattern.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "parameters.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "parentheses.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "tupleType.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "typeLiteral.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "typeParameters.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "unionAndIntersectionType.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; "variableStatement.preferSingleLine"?: PreferSingleLine & PreferSingleLine1; [k: string]: unknown; }
the_stack
import { Utils } from 'tuya-panel-utils'; import { getBrandColor, getTypedFontColor, normalizeFont } from './core'; const { convertX: cx } = Utils.RatioUtils; export interface IProps { [key: string]: any; } export interface IStyle { fontSize: number; lineHeight: number; } /** * 全局颜色变量 */ const globalVariable = { brand: '#FF4800', // 品牌色 background: '#f8f8f8', // 背景色 fontSizeBase: 1, // 字体基准比例 dividerColor: '#e5e5e5', // 分隔线颜色 success: '#00C800', warning: '#FAAE17', error: '#F4182C', fontFamily: undefined, // info, // 信息色 // disabled, // 禁用透明度 mask: 'rgba(0, 0, 0, 0.7)', // 遮罩颜色 text: { light: '#333', dark: '#fff', }, }; /** * 字体变量 */ const text = { heading: { small: (props: IProps): IStyle => normalizeFont(props, 28, 40), normal: (props: IProps): IStyle => normalizeFont(props, 40, 56), large: (props: IProps): IStyle => normalizeFont(props, 72, 100), }, title: { small: (props: IProps): IStyle => normalizeFont(props, 16, 22), normal: (props: IProps): IStyle => normalizeFont(props, 17, 24), large: (props: IProps): IStyle => normalizeFont(props, 20, 28), }, // title以上都走主要字体色#333 paragraph: { small: (props: IProps): IStyle => normalizeFont(props, 10, 14), normal: (props: IProps): IStyle => normalizeFont(props, 12, 17), large: (props: IProps): IStyle => normalizeFont(props, 14, 20), }, }; /** * 选择器 */ const picker = { light: { fontSize: 30, fontColor: 'rgba(0,0,0,0.9)', dividerColor: 'rgba(0, 0, 0, 0.05)', unitFontSize: 14, unitFontColor: 'rgba(0,0,0,0.9)', }, dark: { fontSize: 30, fontColor: '#fff', dividerColor: 'rgba(255, 255, 255, 0.1)', unitFontSize: 14, unitFontColor: '#fff', }, }; /** * 头部栏 */ const topbar = { light: { background: '#fff', color: '#000', }, dark: { background: '#323232', color: '#fff', }, }; /** * 按钮 */ const switchButton = { light: { width: 48, // 按钮宽度 height: 28, // 按钮宽度 thumbSize: 24, // 滑块宽高尺寸 // thumbWidth, // 滑块圆的宽度 // thumbHeight, // 滑块圆的高度 margin: 2, // 滑块四周边距 tintColor: '#e5e5e5', // 关闭情况下背景色 onTintColor: '#4CD964', // 开启情况下背景色 thumbTintColor: '#fff', // 关闭情况下滑块背景色 onThumbTintColor: '#fff', // 开启情况下滑块背景色 }, dark: { width: 48, // 按钮宽度 height: 28, // 按钮宽度 thumbSize: 24, // 滑块宽高尺寸 margin: 2, // 滑块四周边距 tintColor: 'rgba(255,255,255,0.3)', // 关闭情况下背景色 onTintColor: '#4CD964', // 开启情况下背景色 thumbTintColor: '#fff', // 关闭情况下滑块背景色 onThumbTintColor: '#fff', // 开启情况下滑块背景色 }, }; /** * 选择框 */ const checkbox = { light: { size: 28, fontColor: '#333', activeColor: '#3388FF', disabledColor: '#333', }, dark: { size: 28, fontColor: '#fff', activeColor: '#7ED321', disabledColor: '#fff', }, }; /** * 滑动器 */ const slider = { light: { width: null, // 默认跟随父容器(滑块宽度) trackRadius: 2, // 滑块圆角 trackHeight: 4, // 滑块高度 minimumTrackTintColor: getBrandColor, // 最小值颜色 maximumTrackTintColor: '#e5e5e5', // 最大值颜色 thumbSize: 24, // 滑块圆的尺寸(TODO: 是否被宽高替代) thumbRadius: 14, // 滑块圆的圆角 thumbTintColor: '#fff', // 滑块的颜色 // thumbWidth, // 滑块圆的宽度 // thumbHeight, // 滑块圆的高度 // thumbBorder, // thumbColor, }, dark: { width: null, // 默认跟随父容器 trackRadius: 2, trackHeight: 4, minimumTrackTintColor: getBrandColor, maximumTrackTintColor: 'rgba(255, 255, 255, 0.3)', thumbSize: 24, thumbRadius: 14, thumbTintColor: '#fff', }, }; /** * 列表 */ const list = { light: { boardBg: '#f8f8f8', iconColor: 'rgba(0, 0, 0, 0.2)', fontColor: '#333', subFontColor: 'rgba(51, 51, 51, 0.5)', descFontColor: 'rgba(51, 51, 51, 0.5)', cellLine: 'rgba(51, 51, 51, 0.1)', cellBg: '#fff', cellRadius: 0, margin: [0, 0, 0, 0], padding: [12, cx(14), 12, cx(14)], }, dark: { boardBg: '#2b2c2a', fontColor: '#fff', iconColor: 'rgba(255, 255, 255, 0.5)', subFontColor: 'rgba(255, 255, 255, 0.5)', descFontColor: 'rgba(255, 255, 255, 0.5)', cellLine: 'rgba(255, 255, 255, 0.02)', cellBg: 'rgba(255, 255, 255, 0.02)', cellRadius: 0, margin: [0, 0, 0, 0], padding: [12, cx(14), 12, cx(14)], }, }; /** * 提示Toast,os平台不允许修改 */ // const toast = { // light: { // bgColor: '#fff', // 背景颜色 // fontColor: '#333', // 跟随主要字体颜色 // }, // }; /** * 按钮 */ const button = { light: { margin: [0, 0, 0, 0], // 按钮容器边距 fontSize: 10, // 字体尺寸 fontColor: getTypedFontColor, iconSize: 17, iconColor: (props: IProps): string => getTypedFontColor(props, props.type === 'primary'), bgWidth: null, // 按钮背景宽度,默认组件内部自适应 bgHeight: null, // 按钮背景高度,默认组件内部自适应 bgRadius: null, // 按钮背景圆角,默认组件内部自适应 bgColor: getBrandColor, // 按钮背景色,默认跟随主色 // bgBorder, // 安卓有瑕疵预留暂不支持 // bgBorderWidth, // 安卓有瑕疵预留暂不支持 // badgeText, // 预留暂不暴露 // badgeTextColor, // 预留暂不暴露 }, dark: { margin: [0, 0, 0, 0], // 按钮容器边距 fontSize: 10, fontColor: getTypedFontColor, iconSize: 17, iconColor: (props: IProps): string => getTypedFontColor(props, props.type === 'primary'), bgWidth: null, // 按钮背景宽度,默认组件内部自适应 bgHeight: null, // 按钮背景高度,默认组件内部自适应 bgRadius: null, // 按钮背景圆角,默认组件内部自适应 bgColor: getBrandColor, // 按钮背景色,默认跟随主色 }, }; // const controllerBar = { // fontColor, // 文字颜色 // fontSize, // 文字大小 // iconColor, // 图标颜色 // iconSize, // 图标大小 // iconInset, // 图标间距 // iconBgColor, // 图标颜色 // iconBgRadius, // 图标背景圆角 // iconBgBorderColor, // 预留 // iconBgBorderWidth, // 预留 // }; /** * brick按钮 */ const brickButton = { light: { fontSize: 12, fontColor: '#fff', bgRadius: 24, bgColor: getBrandColor, // 跟随主色 bgBorder: 'transparent', bgBorderWidth: 0, loadingColor: '#fff', loadingBackground: 'rgba(0,0,0,.1)', }, dark: { fontSize: 12, fontColor: '#fff', bgRadius: 24, bgColor: getBrandColor, // 跟随主色 bgBorder: 'transparent', bgBorderWidth: 0, loadingColor: '#fff', loadingBackground: 'rgba(0,0,0,.1)', }, }; /** * Tips 气泡 */ const tips = { light: { bgColor: '#fff', }, dark: { bgColor: '#4A4A4A', }, }; /** * Dialog 弹窗 */ const dialog = { type: 'basic', // Enum: basic | dark | system /** * @desc 默认风格 */ basic: { width: cx(311), // 弹窗容器宽度 bg: '#fff', // 弹窗背景色 radius: cx(16), // 弹窗容器圆角 cellHeight: 55, // 列表高度(头部、底部) lineColor: 'rgba(0, 0, 0, 0.1)', // 分隔线颜色 titleFontSize: 17, // 标题字体大小 titleFontColor: 'rgba(0, 0, 0, 0.9)', // 头部栏标题颜色 subTitleFontSize: 15, // 副标题字体大小 subTitleFontColor: 'rgba(0, 0, 0, 0.5)', // 头部栏副标题颜色 cancelFontSize: 17, cancelFontColor: 'rgba(0, 0, 0, 0.7)', // 底部栏取消字体颜色 confirmFontSize: 17, confirmFontColor: '#FF4800', // 底部栏确认字体颜色 pressColor: '#E5E5E5', prompt: { padding: '12px 0px', // 输入框边距 placeholder: 'rgba(0, 0, 0, 0.3)', // 占位符字体颜色 bg: '#fff', // 输入框背景色 radius: 0, // 输入框圆角 }, }, /** * @desc 黑色主题 */ dark: { width: cx(311), // 弹窗容器宽度 bg: '#1a1a1a', // 弹窗背景色 radius: cx(16), // 弹窗容器圆角 cellHeight: 55, // 列表高度(头部、底部) lineColor: 'rgba(255, 255, 255, 0.1)', // 分隔线颜色 titleFontSize: 17, // 标题字体大小 titleFontColor: '#FFF', // 头部栏标题颜色 subTitleFontSize: 15, // 副标题字体大小 subTitleFontColor: 'rgba(255, 255, 255, 0.7)', // 头部栏副标题颜色 cancelFontSize: 17, cancelFontColor: 'rgba(255, 255, 255, 0.7)', // 底部栏取消字体颜色 confirmFontSize: 17, confirmFontColor: '#FF4800', // 底部栏确认字体颜色 prompt: { padding: '12px 0px', // 输入框边距 placeholder: 'rgba(255, 255, 255, 0.3)', // 占位符字体颜色 bg: '#fff', // 输入框背景色 radius: 0, // 输入框圆角 }, pressColor: '#313131', }, /** * @desc 系统风格 */ system: { width: cx(271), // 弹窗容器宽度 bg: '#fff', // 背景色 radius: cx(14), // 弹窗容器圆角 cellHeight: 48, // 列表高度(头部、底部) lineColor: '#dbdbdb', // 分隔线颜色 titleFontSize: 17, titleFontColor: '#333', // 头部栏标题颜色 subTitleFontSize: 13, // 副标题字体大小 subTitleFontColor: '#333', // 头部栏副标题颜色 cancelFontSize: 16, cancelFontColor: '#0077FF', // 底部栏取消字体颜色 confirmFontSize: 16, confirmFontColor: '#0077FF', // 底部栏确认字体颜色 prompt: { bg: '#fff', // 输入框背景色 radius: 0, // 输入框圆角 padding: '3px 4px', // 输入框边距 placeholder: '#b5b5b5', // 占位符字体颜色 }, }, }; /** * Popup 弹出层 */ const popup = { type: 'basic', // Enum: basic| dark | ... basic: { cellHeight: 56, // 列表高度 cellBg: '#fff', // 列表底色 cellFontColor: 'rgba(0,0,0,0.9)', // 列表字体颜色 cellFontSize: 16, // 列表字体大小 subTitleFontColor: 'rgba(0, 0, 0, .5)', // 头部栏副标题颜色 titleRadius: 16, // 头部圆角 titleBg: '#ffffff', // 头部背景色 titleHeight: 56, // 头部高度 footerRadius: 0, // 底部圆角 bottomBg: '#f8f8f8', // 底部栏底色 lineColor: 'rgba(0, 0, 0, 0.1)', // 分隔线颜色 titleFontSize: 14, checkboxColor: '#FF4800', // 选中icon颜色 titleFontColor: 'rgba(0,0,0,0.9)', // 头部栏标题颜色 cancelFontSize: 16, cancelFontColor: 'rgba(0,0,0,0.7)', // 底部栏取消字体颜色 confirmFontSize: 16, confirmFontColor: '#FF4800', // 底部栏确认字体颜色 pressColor: '#E5E5E5', backIconColor: '#000', // 返回文案和按钮颜色 tintColor: '#e5e5e5', // SwitchButton 关闭情况下背景色,popup 需要独立 numberSelector: { cellPlusColor: '#666', // Number-selector的加减颜色 maximumTrackTintColor: '#D8D8D8', // 大于当前值的轨道颜色 }, list: { cellFontColor: 'rgba(0,0,0,0.9)', // List 内容字体颜色 }, }, dark: { cellHeight: 56, // 列表高度 cellBg: '#1A1A1A', // 列表底色 cellFontColor: 'rgba(255, 255, 255, 0.9)', // 列表字体颜色 cellFontSize: 16, // 列表字体大小 subTitleFontColor: 'rgba(255,255,255,0.5)', // 头部栏副标题颜色 titleRadius: 16, // 头部圆角 titleBg: '#1A1A1A', // 头部背景色 titleHeight: 56, // 头部高度 footerRadius: 0, // 底部圆角 bottomBg: '#000', // 底部栏底色 lineColor: 'rgba(255,255,255, 0.1)', // 分隔线颜色 titleFontSize: 14, checkboxColor: '#FF4800', // 选中icon颜色 titleFontColor: 'rgba(255, 255, 255, 0.9)', // 头部栏标题颜色 cancelFontSize: 16, cancelFontColor: 'rgba(255,255,255,0.7)', // 底部栏取消字体颜色 confirmFontSize: 16, confirmFontColor: '#FF4800', // 底部栏确认字体颜色 backIconColor: '#fff', // 返回文案和按钮颜色 tintColor: 'rgba(255, 255, 255, 0.3)', // SwitchButton 关闭情况下背景色,popup 需要独立 pressColor: '#313131', numberSelector: { cellPlusColor: '#fff', // Number-selector的加减颜色 maximumTrackTintColor: '#1A1A1A', // 大于当前值的轨道颜色 }, list: { cellFontColor: 'rgba(255, 255, 255, 0.9)', // List 内容字体颜色 }, }, }; export default { type: 'light', global: globalVariable, text, picker, button, topbar, switchButton, slider, checkbox, list, brickButton, tips, dialog, popup, };
the_stack
/** * @author Christopher Cook * @copyright Webprofusion Ltd http://webprofusion.com */ /// <reference path="TypeScriptReferences/jquery/jquery.d.ts" /> module OCM { export class POI_SearchParams { constructor() { } public countryCode: string = null; public latitude: number = null; public longitude: number = null; public locationTitle: string = null; public distance: number = null; public distanceUnit: string = null; public connectionTypeID: number = null; public operatorID: number = null; public levelID: number = null; public countryID: number = null; public usageTypeID: number = null; public statusTypeID: number = null; public minPowerKW: number = null; public submissionStatusTypeID: number = null; public maxResults: number = 1000; public additionalParams: string = null; public includeComments: boolean = false; public compact: boolean = true; public enableCaching: boolean = true; //FIXME: need way for user to override cached data public levelOfDetail: number = 1; //if supplied, will return a random sample of matching results, higher number return less results public polyline: string = null; //(lat,lng),(lat,lng),(lat,lng),(lat,lng) or encoded polyline public boundingbox: string = null;//(lat,lng),(lat,lng),(lat,lng),(lat,lng) } export interface ConnectionInfo { ID: number; Reference: string; ConnectionType: any; StatusType: any; Level: any; CurrentType: any; Amps: number; Voltage: number; PowerKW: number; Quantity: number; Comments?: string; }; export class API { public serviceBaseURL: string = "https://api.openchargemap.io/v2"; public serviceBaseURL_Standard: string = "https://api.openchargemap.io/v2"; public serviceBaseURL_Sandbox: string = "https://sandbox.api.openchargemap.io/v2"; public hasAuthorizationError: boolean = false; public ATTRIBUTION_METADATAFIELDID = 4; public referenceData: any; public clientName: string = "ocm.api.default"; public authorizationErrorCallback: any; public generalErrorCallback: any; public allowMirror: boolean = false; fetchLocationDataList(countrycode, lat, lon, distance, distanceunit, maxresults, includecomments, callbackname, additionalparams, errorcallback) { if (countrycode === null) countrycode = ""; if (additionalparams === null) additionalparams = ""; if (!errorcallback) errorcallback = this.handleGeneralAjaxError; var apiCallURL = this.serviceBaseURL + "/poi/?client=" + this.clientName + "&verbose=false&output=json&countrycode=" + countrycode + "&longitude=" + lon + "&latitude=" + lat + "&distance=" + distance + "&distanceunit=" + distanceunit + "&includecomments=" + includecomments + "&maxresults=" + maxresults + "&" + additionalparams; if (console) { console.log("API Call:" + apiCallURL); } $.ajax({ type: "GET", url: apiCallURL + "&callback=" + callbackname, jsonp: "false", contentType: "application/json;", dataType: "jsonp", crossDomain: true, error: errorcallback }); } fetchLocationDataListByParam(params: OCM.POI_SearchParams, callbackname, errorcallback) { var serviceURL = this.serviceBaseURL + "/poi/?client=" + this.clientName + (this.allowMirror ? " &allowmirror=true" : "") + "&verbose=false&output=json"; var serviceParams = ""; if (params.countryCode != null) serviceParams += "&countrycode=" + params.countryCode; if (params.latitude != null) serviceParams += "&latitude=" + params.latitude; if (params.longitude != null) serviceParams += "&longitude=" + params.longitude; if (params.distance != null) serviceParams += "&distance=" + params.distance; if (params.distanceUnit != null) serviceParams += "&distanceunit=" + params.distanceUnit; if (params.includeComments != null) serviceParams += "&includecomments=" + params.includeComments; if (params.maxResults != null) serviceParams += "&maxresults=" + params.maxResults; if (params.countryID != null) serviceParams += "&countryid=" + params.countryID; if (params.levelID != null) serviceParams += "&levelid=" + params.levelID; if (params.connectionTypeID != null) serviceParams += "&connectiontypeid=" + params.connectionTypeID; if (params.operatorID != null) serviceParams += "&operatorid=" + params.operatorID; if (params.usageTypeID != null) serviceParams += "&usagetypeid=" + params.usageTypeID; if (params.statusTypeID != null) serviceParams += "&statustypeid=" + params.statusTypeID; if (params.locationTitle != null) serviceParams += "&locationtitle=" + params.locationTitle; if (params.minPowerKW != null) serviceParams += "&minpowerkw=" + params.minPowerKW; if (params.submissionStatusTypeID != null) serviceParams += "&submissionstatustypeid=" + params.submissionStatusTypeID; if (params.enableCaching == false) serviceParams += "&enablecaching=false"; if (params.compact != null) serviceParams += "&compact=" + params.compact; if (params.levelOfDetail > 1) serviceParams += "&levelofdetail=" + params.levelOfDetail; if (params.polyline != null) serviceParams += "&polyline=" + params.polyline; if (params.boundingbox != null) serviceParams += "&boundingbox=" + params.boundingbox; if (params.additionalParams != null) serviceParams += "&" + params.additionalParams; if (!errorcallback) errorcallback = this.handleGeneralAjaxError; var apiCallURL = serviceURL + serviceParams; //+ "&polyline=u`lyH|iW{}D|dHweCboEasA|x@_gAupBs}A{yE}n@ydG}bBi~FybCsnBmeCse@otLm{BshGscAw`E|nDawLykJq``@flAqbRczR"; if (console) { console.log("API Call:" + apiCallURL + "&callback=" + callbackname); } var ajaxSettings: JQueryAjaxSettings = { type: "GET", url: apiCallURL + "&callback=" + callbackname, jsonp: "false", contentType: "application/json;", dataType: "jsonp", crossDomain: true, error: errorcallback }; $.ajax(ajaxSettings); } fetchLocationById(id, callbackname, errorcallback, disableCaching) { var serviceURL = this.serviceBaseURL + "/poi/?client=" + this.clientName + "&output=json&includecomments=true&chargepointid=" + id; if (disableCaching) serviceURL += "&enablecaching=false"; if (!errorcallback) errorcallback = this.handleGeneralAjaxError; var ajaxSettings: JQueryAjaxSettings = { type: "GET", url: serviceURL + "&callback=" + callbackname, jsonp: "false", contentType: "application/json;", dataType: "jsonp", crossDomain: true, error: errorcallback }; $.ajax(ajaxSettings); } handleGeneralAjaxError(result, ajaxOptions, thrownError) { this.hasAuthorizationError = false; if (result.status == 200) { //all ok } else if (result.status == 401) { //unauthorised, user session has probably expired this.hasAuthorizationError = true; if (this.authorizationErrorCallback) { this.authorizationErrorCallback(); } else { if (console) console.log("Your session has expired. Please sign in again."); } } else { if (this.generalErrorCallback) { this.generalErrorCallback(); } else { if (console) console.log("There was a problem transferring data. Please check your internet connection."); } } } fetchCoreReferenceData(callbackname, authSessionInfo) { var authInfoParams = this.getAuthParamsFromSessionInfo(authSessionInfo); var ajaxSettings: JQueryAjaxSettings = { type: "GET", url: this.serviceBaseURL + "/referencedata/?client=" + this.clientName + "&output=json" + (this.allowMirror ? "&allowmirror=true" : "") + "&verbose=false&callback=" + callbackname + "&" + authInfoParams, jsonp: "false", contentType: "application/json;", dataType: "jsonp", crossDomain: true, error: this.handleGeneralAjaxError }; $.ajax(ajaxSettings); } fetchGeocodeResult(address, successCallback, authSessionInfo, errorCallback) { var authInfoParams = this.getAuthParamsFromSessionInfo(authSessionInfo); var ajaxSettings: JQueryAjaxSettings = { type: "GET", url: this.serviceBaseURL + "/geocode/?client=" + this.clientName + "&address=" + address + "&output=json&verbose=false&camelcase=true&" + authInfoParams, contentType: "application/json;", dataType: "jsonp", crossDomain: true, success: successCallback, error: (errorCallback != null ? errorCallback : this.handleGeneralAjaxError) }; $.ajax(ajaxSettings); } getAuthParamsFromSessionInfo(authSessionInfo) { var authInfoParams = ""; if (authSessionInfo != null) { if (authSessionInfo.Identifier != null) authInfoParams += "&Identifier=" + authSessionInfo.Identifier; if (authSessionInfo.SessionToken != null) authInfoParams += "&SessionToken=" + authSessionInfo.SessionToken; return authInfoParams; } return ""; } submitLocation(data, authSessionInfo, completedCallback, failureCallback) { var authInfoParams = this.getAuthParamsFromSessionInfo(authSessionInfo); var jsonString = JSON.stringify(data); var ajaxSettings: JQueryAjaxSettings = { type: "POST", url: this.serviceBaseURL + "/?client=" + this.clientName + "&action=cp_submission&format=json" + authInfoParams, data: jsonString, complete: function (jqXHR, textStatus) { completedCallback(jqXHR, textStatus); }, crossDomain: true, error: this.handleGeneralAjaxError }; $.ajax(ajaxSettings); } submitUserComment(data, authSessionInfo, completedCallback, failureCallback) { var authInfoParams = this.getAuthParamsFromSessionInfo(authSessionInfo); var jsonString = JSON.stringify(data); $.ajax({ type: "POST", url: this.serviceBaseURL + "/?client=" + this.clientName + "&action=comment_submission&format=json" + authInfoParams, data: jsonString, success: function (result, textStatus, jqXHR) { completedCallback(jqXHR, textStatus); }, crossDomain: true, error: failureCallback }); } submitMediaItem(data, authSessionInfo, completedCallback, failureCallback, progressCallback) { var authInfoParams = this.getAuthParamsFromSessionInfo(authSessionInfo); $.ajax({ url: this.serviceBaseURL + "/?client=" + this.clientName + "&action=mediaitem_submission" + authInfoParams, type: 'POST', xhr: function () { // custom xhr var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // check if upload property exists myXhr.upload.addEventListener('progress', progressCallback, false); // for handling the progress of the upload } return myXhr; }, success: function (result, textStatus, jqXHR) { completedCallback(jqXHR, textStatus); }, error: (failureCallback == null ? this.handleGeneralAjaxError : failureCallback), data: data, cache: false, contentType: false, processData: false, crossDomain: true }); } getRefDataByID(refDataList, id) { if (id != "") id = parseInt(id); if (refDataList != null) { for (var i = 0; i < refDataList.length; i++) { if (refDataList[i].ID == id) { return refDataList[i]; } } } return null; } sortCoreReferenceData() { //sort reference data lists this.sortReferenceData(this.referenceData.ConnectionTypes); this.sortReferenceData(this.referenceData.Countries); this.sortReferenceData(this.referenceData.Operators); this.sortReferenceData(this.referenceData.DataProviders); this.sortReferenceData(this.referenceData.UsageTypes); this.sortReferenceData(this.referenceData.StatusTypes); this.sortReferenceData(this.referenceData.CheckinStatusTypes); } sortReferenceData(sourceList) { sourceList.sort(this.sortListByTitle); } getMetadataValueByMetadataFieldID(metadataValues, id) { if (id != "") id = parseInt(id); if (metadataValues != null) { for (var i = 0; i < metadataValues.length; i++) { if (metadataValues[i].ID == id) { return metadataValues[i]; } } } return null; } sortListByTitle(a, b) { if (a.Title < b.Title) return -1; if (a.Title > b.Title) return 1; if (a.Title == b.Title) return 0; return 0; } hydrateCompactPOI(poi: any): Array<any> { if (poi.DataProviderID != null && poi.DataProvider == null) { poi.DataProvider = this.getRefDataByID(this.referenceData.DataProviders, poi.DataProviderID); } if (poi.OperatorID != null && poi.OperatorInfo == null) { poi.OperatorInfo = this.getRefDataByID(this.referenceData.Operators, poi.OperatorID); } if (poi.UsageTypeID != null && poi.UsageType == null) { poi.UsageType = this.getRefDataByID(this.referenceData.UsageTypes, poi.UsageTypeID); } if (poi.AddressInfo.CountryID != null && poi.AddressInfo.Country == null) { poi.AddressInfo.Country = this.getRefDataByID(this.referenceData.Countries, poi.AddressInfo.CountryID); } if (poi.StatusTypeID != null && poi.StatusType == null) { poi.StatusType = this.getRefDataByID(this.referenceData.StatusTypes, poi.StatusTypeID); } if (poi.SubmissionStatusTypeID != null && poi.SubmissionStatusType == null) { poi.SubmissionStatusType = this.getRefDataByID(this.referenceData.SubmissionStatusTypes, poi.SubmissionStatusTypeID); } //TOD: UserComments, MediaItems, if (poi.Connections != null) { for (var c = 0; c < poi.Connections.length; c++) { var conn = poi.Connections[c]; if (conn.ConnectionTypeID != null && conn.ConnectionType == null) { conn.ConnectionType = this.getRefDataByID(this.referenceData.ConnectionTypes, conn.ConnectionTypeID); } if (conn.LevelID != null && conn.Level == null) { conn.Level = this.getRefDataByID(this.referenceData.ChargerTypes, conn.LevelID); } if (conn.CurrentTypeID != null && conn.CurrentTypeID == null) { conn.CurrentType = this.getRefDataByID(this.referenceData.CurrentTypes, conn.CurrentTypeID); } if (conn.StatusTypeID != null && conn.StatusTypeID == null) { conn.StatusTypeID = this.getRefDataByID(this.referenceData.StatusTypes, conn.StatusTypeID); } poi.Connections[c] = conn; } } if (poi.UserComments != null) { for (var c = 0; c < poi.UserComments.length; c++) { var comment = poi.UserComments[c]; if (comment.CommentType != null && comment.CommentTypeID == null) { comment.CommentType = this.getRefDataByID(this.referenceData.CommentTypes, conn.CommentTypeID); } if (comment.CheckinStatusType != null && comment.CheckinStatusTypeID == null) { comment.CheckinStatusTypeID = this.getRefDataByID(this.referenceData.CheckinStatusTypes, conn.CheckinStatusTypeID); } poi.UserComments[c] = comment; } } return poi; } // for a given list of POIs expand navigation properties (such as AddresssInfo.Country, Connection[0].ConnectionType etc) hydrateCompactPOIList(poiList: Array<any>) { for (var i = 0; i < poiList.length; i++) { poiList[i] = this.hydrateCompactPOI(poiList[i]); } return poiList; } isLocalStorageAvailable() { return typeof window.localStorage != 'undefined'; } setCachedDataObject(itemName, itemValue) { if (this.isLocalStorageAvailable()) { if (typeof itemValue === 'undefined') itemValue = null; if (itemValue === null) { localStorage.removeItem(itemName); } else { localStorage.setItem(itemName, JSON.stringify(itemValue)); } } } getCachedDataObject(itemName) { if (this.isLocalStorageAvailable()) { var val = localStorage.getItem(itemName); if (val != null && val.length > 0) { return JSON.parse(val); } } return null; } } }
the_stack
import * as ethers from 'ethers' import * as Logger from 'js-logger' import EventEmitter from 'events' import { PlasmaClient } from './client' import { IStorage } from './storage/IStorage' import { EventWatcher } from '@layer2/events-watcher' import { WalletStorage } from './storage/WalletStorage' import { Address, constants, ExitableRangeManager, SignedTransaction, SignedTransactionWithProof, Block, Segment, ChamberResult, ChamberResultError, ChamberOk, SwapRequest, StateUpdate, OwnershipPredicate, PredicatesManager } from '@layer2/core' import { WalletErrorFactory } from './error' import { Exit, WaitingBlockWrapper, TokenType, UserAction, UserActionUtil, FastTransferResponse } from './models' import Contract = ethers.Contract import { BigNumber } from 'ethers/utils' import { PlasmaSyncher } from './client/PlasmaSyncher' import { StateManager } from './StateManager' import artifact from './assets/RootChain.json' import { SegmentHistoryManager } from './history' import { DefragAlgorithm } from './strategy/defrag' import { TransferAlgorithm } from './strategy/transfer' if (!artifact.abi) { console.error('ABI not found') } const abi = [ 'event BlockSubmitted(bytes32 _superRoot, bytes32 _root, uint256 _timestamp, uint256 _blkNum)', 'event Deposited(address indexed _depositer, uint256 _tokenId, uint256 _start, uint256 _end, uint256 _blkNum)', 'event ExitStarted(address indexed _exitor, uint256 _exitId, uint256 exitableAt, uint256 _segment, uint256 _blkNum)', 'event FinalizedExit(uint256 _exitId, uint256 _tokenId, uint256 _start, uint256 _end)', 'function deposit() payable', 'function depositERC20(address token, uint256 amount) payable', 'function exit(uint256 _utxoPos, uint256 _segment, bytes _txBytes, bytes _proof) payable', 'function finalizeExit(uint256 _exitableEnd, uint256 _exitId, bytes _exitStateBytes)', 'function getExit(uint256 _exitId) constant returns(address, uint256)' ] const ERC20abi = [ 'function approve(address _spender, uint256 _value) returns (bool)', 'function balanceOf(address tokenOwner) view returns (uint)' ] export class ChamberWallet extends EventEmitter { /** * * @param client * @param privateKey * @param rootChainEndpoint Main chain endpoint * @param contractAddress RootChain address * @param storage * * ### Example * * ```typescript * const jsonRpcClient = new JsonRpcClient('http://localhost:3000') * const client = new PlasmaClient(jsonRpcClient) * const storage = new WalletStorage() * return ChamberWallet.createWalletWithPrivateKey( * client, * 'http://127.0.0.1:8545', * '0x00... root chain address', * storage, * '0x00... private key' * ) * ``` */ public static createWalletWithPrivateKey( client: PlasmaClient, rootChainEndpoint: string, contractAddress: Address, storage: IStorage, privateKey: string, options?: any ) { const httpProvider = new ethers.providers.JsonRpcProvider(rootChainEndpoint) return new ChamberWallet( client, httpProvider, new ethers.Wallet(privateKey, httpProvider), contractAddress, storage, options ) } public static createWalletWithMnemonic( client: PlasmaClient, rootChainEndpoint: string, contractAddress: Address, storage: IStorage, mnemonic: string, options?: any ) { return new ChamberWallet( client, new ethers.providers.JsonRpcProvider(rootChainEndpoint), ethers.Wallet.fromMnemonic(mnemonic), contractAddress, storage, options ) } public static createRandomWallet( client: PlasmaClient, rootChainEndpoint: string, contractAddress: Address, storage: IStorage, options?: any ) { return new ChamberWallet( client, new ethers.providers.JsonRpcProvider(rootChainEndpoint), ethers.Wallet.createRandom(), contractAddress, storage, options ) } public isMerchant: boolean private client: PlasmaClient private loadedBlockNumber: number = 0 private rootChainContract: Contract private wallet: ethers.Wallet private storage: WalletStorage private httpProvider: ethers.providers.JsonRpcProvider private listener: EventWatcher private rootChainInterface: ethers.utils.Interface private exitableRangeManager: ExitableRangeManager = new ExitableRangeManager() private plasmaSyncher: PlasmaSyncher private options: any private segmentHistoryManager: SegmentHistoryManager private predicatesManager: PredicatesManager private stateManager: StateManager constructor( client: PlasmaClient, provider: ethers.providers.JsonRpcProvider, wallet: ethers.Wallet, contractAddress: Address, storage: IStorage, options?: any ) { super() this.client = client this.options = options || {} this.httpProvider = provider const contract = new ethers.Contract( contractAddress, abi, this.httpProvider ) this.wallet = wallet this.rootChainContract = contract.connect(this.wallet) this.storage = new WalletStorage(storage) this.rootChainInterface = new ethers.utils.Interface(artifact.abi) this.plasmaSyncher = new PlasmaSyncher( client, provider, contractAddress, this.storage, this.options ) this.isMerchant = this.options.isMerchant || false this.listener = this.plasmaSyncher.getListener() this.listener.addEvent('ListingEvent', e => { Logger.debug('ListingEvent', e) this.handleListingEvent(e.values._tokenId, e.values._tokenAddress) }) this.listener.addEvent('ExitStarted', e => { Logger.debug('ExitStarted', e) this.handleExit( e.values._exitId, e.values._exitStateHash, e.values._exitableAt, e.values._segment ) }) this.listener.addEvent('FinalizedExit', e => { Logger.debug('FinalizedExit', e) this.handleFinalizedExit( e.values._tokenId, e.values._start, e.values._end ) }) this.listener.addEvent('Deposited', e => { Logger.debug('Deposited', e) this.handleDeposit( e.values._depositer, e.values._tokenId, e.values._start, e.values._end, e.values._blkNum ) }) this.predicatesManager = new PredicatesManager() this.predicatesManager.addPredicate( ethers.constants.AddressZero, 'OwnershipPredicate' ) this.stateManager = new StateManager(this.predicatesManager) this.segmentHistoryManager = new SegmentHistoryManager( storage, this.client, this.predicatesManager ) this.plasmaSyncher.on('PlasmaBlockHeaderAdded', (e: any) => { this.segmentHistoryManager.appendBlockHeader( e.blockHeader as WaitingBlockWrapper ) }) Logger.useDefaults() if (this.options.logLevel === 'debug') { Logger.setLevel(Logger.DEBUG) } else { Logger.setLevel(Logger.WARN) } } public setPredicate(name: string, predicate: Address) { this.predicatesManager.addPredicate(predicate, name) } /** * * @param handler * * ```typescript * await wallet.init((wallet) => {}) * ``` */ public async init() { await this.storage.init() const state: any[] = await this.storage.getState() this.stateManager.deserialize(state) this.exitableRangeManager = await this.storage.loadExitableRangeManager() this.loadedBlockNumber = await this.storage.getLoadedPlasmaBlockNumber() if (this.isMerchant) { this.client.subscribeFastTransfer(this.getAddress(), async tx => { await this.sendFastTransferToOperator(tx) }) } await this.plasmaSyncher.init(() => { this.emit('updated', { wallet: this }) }) } public async cancelPolling() { this.plasmaSyncher.cancel() this.client.unsubscribeFastTransfer(this.getAddress()) } public async loadBlockNumber() { return this.client.getBlockNumber() } public getPlasmaBlockNumber() { return this.loadedBlockNumber } /** * get current targetBlock */ public getTargetBlockNumber() { return this.loadedBlockNumber + 3 } public async syncChildChain(): Promise<SignedTransactionWithProof[]> { await this.plasmaSyncher.sync(async (block: Block) => { await this.updateBlock(block) }) return this.getUTXOArray() } public async handleListingEvent(tokenId: BigNumber, tokenAddress: string) { // add available token this.storage.addToken(tokenId.toNumber(), tokenAddress) } public getAvailableTokens(): TokenType[] { return this.storage.getTokens() } /** * @ignore */ public handleDeposit( depositor: string, tokenId: BigNumber, start: BigNumber, end: BigNumber, blkNum: BigNumber ) { const depositorAddress = ethers.utils.getAddress(depositor) const segment = new Segment(tokenId, start, end) const depositTx = OwnershipPredicate.create( segment, blkNum, this.predicatesManager.getNativePredicate('OwnershipPredicate'), depositorAddress ) if (depositorAddress === this.getAddress()) { this.segmentHistoryManager.init(depositTx.hash(), segment) this.stateManager.insertDepositTx(depositTx) this.flushCurrentState() } this.segmentHistoryManager.appendDeposit(depositTx) this.exitableRangeManager.insert(tokenId, start, end) this.storage.saveExitableRangeManager(this.exitableRangeManager) this.emit('deposited', { wallet: this, tx: depositTx }) return depositTx } /** * @ignore */ public handleExit( exitId: BigNumber, exitStateHash: string, exitableAt: BigNumber, segmentUint: BigNumber ) { const segment = Segment.fromBigNumber(segmentUint) const utxo = this.getUTXOArray().filter(utxo => { return utxo .getOutput() .getSegment() .toBigNumber() .eq(segment.toBigNumber()) })[0] if (utxo) { this.stateManager.startExit(utxo.getSegment()) this.flushCurrentState() const exit = new Exit(exitId, exitableAt, segment, utxo.getStateBytes()) this.storage.setExit(exit) this.emit('exitStarted', { wallet: this }) return exit } else { return null } } /** * @ignore */ public handleFinalizedExit( tokenId: BigNumber, start: BigNumber, end: BigNumber ) { try { this.exitableRangeManager.remove(tokenId, start, end) } catch (e) { console.warn(e.message) } this.storage.saveExitableRangeManager(this.exitableRangeManager) this.emit('finlaizedEixt', { wallet: this }) } public getExits() { return this.storage.getExitList() } public async getUserActions(blkNum: number): Promise<UserAction[]> { return this.storage.searchActions(blkNum) } public getUTXOArray(): SignedTransactionWithProof[] { const arr = this.stateManager.getSignedTransactionWithProofs() arr.sort((a: SignedTransactionWithProof, b: SignedTransactionWithProof) => { const aa = a.getOutput().getSegment().start const bb = b.getOutput().getSegment().start if (aa.gt(bb)) { return 1 } else if (aa.lt(bb)) { return -1 } else { return 0 } }) return arr } public getAddress() { return this.wallet.address } public async getBalanceOfMainChain(tokenId?: number): Promise<BigNumber> { tokenId = tokenId || 0 if (tokenId === 0) { return this.wallet.getBalance() } else { // had better to use cache? const address = this.getAvailableTokens() .filter(t => t.id === tokenId) .map(t => t.address)[0] const contract = new ethers.Contract(address, ERC20abi, this.httpProvider) const ERC20 = contract.connect(this.wallet) const resultBalanceOf = await ERC20.balanceOf(this.getAddress()) return resultBalanceOf } } /** * get balance of specified tokenId * @param _tokenId tokenId ETH id 0 */ public getBalance(tokenId?: number) { tokenId = tokenId || 0 let balance = ethers.utils.bigNumberify(0) this.getUTXOArray().forEach(tx => { const segment = tx.getOutput().getSegment() if (segment.getTokenId().toNumber() === tokenId) { balance = balance.add( tx .getOutput() .getSegment() .getAmount() ) } }) return balance } /** * verifyHistory is history verification method for UTXO * @param tx The tx be verified history */ public async verifyHistory(tx: SignedTransactionWithProof): Promise<boolean> { const key = tx.getOutput().hash() // verify history between deposit and latest tx // segmentHistoryManager.verifyHistory should return current UTXO const utxos = await this.segmentHistoryManager.verifyHistory(key) if (utxos.length > 0) { tx.checkVerified(true) // update this.stateManager.insert(tx) this.flushCurrentState() this.emit('updated', { wallet: this }) return true } else { return false } } /** * * @param ether 1.0 */ public async deposit(ether: string): Promise<ChamberResult<StateUpdate>> { const result = await this.rootChainContract.deposit({ value: ethers.utils.parseEther(ether) }) return this._deposit(result) } /** * @dev require to approve before depositERC20 * @param token token address * @param amount */ public async depositERC20( token: Address, amount: number ): Promise<ChamberResult<StateUpdate>> { const contract = new ethers.Contract(token, ERC20abi, this.httpProvider) const ERC20 = contract.connect(this.wallet) const resultApprove = await ERC20.approve( this.rootChainContract.address, amount ) await resultApprove.wait() const result = await this.rootChainContract.depositERC20(token, amount) return this._deposit(result) } public async exit( tx: SignedTransactionWithProof ): Promise<ChamberResult<Exit>> { const result = await this.rootChainContract.exit( tx.blkNum.mul(100), tx .getOutput() .getSegment() .toBigNumber(), tx.getTxBytes(), tx.getProofAsHex(), { value: constants.EXIT_BOND } ) await result.wait() const receipt = await this.httpProvider.getTransactionReceipt(result.hash) if (receipt.logs && receipt.logs[0]) { const logDesc = this.rootChainInterface.parseLog(receipt.logs[0]) // delete exiting UTXO from UTXO list. const exitOrNull = this.handleExit( logDesc.values._exitId, logDesc.values._exitStateHash, logDesc.values._exitableAt, logDesc.values._segment ) if (exitOrNull) { return new ChamberOk(exitOrNull) } else { return new ChamberResultError(WalletErrorFactory.InvalidReceipt()) } } else { return new ChamberResultError(WalletErrorFactory.InvalidReceipt()) } } public async getExit(exitId: string) { return this.rootChainContract.getExit(exitId) } public async finalizeExit(exitId: string): Promise<ChamberResult<Exit>> { const exit = this.storage.getExit(exitId) if (exit == null) { return new ChamberResultError(WalletErrorFactory.ExitNotFound()) } const result = await this.rootChainContract.finalizeExit( this.exitableRangeManager.getExitableEnd( exit.segment.start, exit.segment.end ), exitId, exit.getStateBytes() ) await result.wait() this.storage.deleteExit(exit.getId()) return new ChamberOk(exit) } /** * searchMergable search mergable stateUpdates * @param targetBlockNumber is target block number */ public searchMergable(targetBlockNumber: BigNumber): StateUpdate | null { return DefragAlgorithm.searchMergable( this.getUTXOArray(), targetBlockNumber, this.predicatesManager.getNativePredicate('OwnershipPredicate'), this.wallet.address ) } /** * * @param to The recipient address * @param tokenId tokenId * @param amountStr ex) '1.0' * @param feeTo The recipient address of fee * @param feeAmountStr ex) '0.01' * * ### Example * * sender * ```typescript * await wallet.transfer('0x....', '1.0') * ``` * * recipient * ```typescript * wallet.on('receive', (e) => { * console.log(e.tx) * }) * ``` */ public async transfer( to: Address, tokenId: number, amountStr: string, feeTo?: Address, feeAmountStr?: string ): Promise<ChamberResult<boolean>> { const amount = ethers.utils.bigNumberify(amountStr) const feeAmount = feeAmountStr ? ethers.utils.bigNumberify(feeAmountStr) : undefined const signedTx = this.searchUtxo(to, tokenId, amount, feeTo, feeAmount) if (signedTx == null) { return new ChamberResultError(WalletErrorFactory.TooLargeAmount()) } signedTx.sign(this.wallet.privateKey) return this.client.sendTransaction(signedTx) } /** * fast transfer method * @param to The recipient address * @param tokenId tokenId * @param amountStr ex) '1.0' * @param feeTo The recipient address of fee * @param feeAmountStr ex) '0.01' */ public sendFastTransferToMerchant( to: Address, tokenId: number, amountStr: string, feeTo?: Address, feeAmountStr?: string ): ChamberResult<boolean> { const amount = ethers.utils.bigNumberify(amountStr) const feeAmount = feeAmountStr ? ethers.utils.bigNumberify(feeAmountStr) : undefined const signedTx = this.searchUtxo(to, tokenId, amount, feeTo, feeAmount) if (signedTx == null) { return new ChamberResultError(WalletErrorFactory.TooLargeAmount()) } signedTx.sign(this.wallet.privateKey) this.client.fastTransferToMerchant(to, signedTx) return new ChamberOk(true) } public async merge() { const targetBlock = ethers.utils.bigNumberify(this.getTargetBlockNumber()) const tx = this.searchMergable(targetBlock) if (tx == null) { return new ChamberResultError(WalletErrorFactory.TooLargeAmount()) } const signedTx = new SignedTransaction([tx]) signedTx.sign(this.wallet.privateKey) return this.client.sendTransaction(signedTx) } public async swapRequest() { const swapRequest = DefragAlgorithm.makeSwapRequest(this.getUTXOArray()) if (swapRequest) { return this.client.swapRequest(swapRequest) } else { return new ChamberResultError(WalletErrorFactory.SwapRequestError()) } } public async swapRequestRespond() { const targetBlock = ethers.utils.bigNumberify(this.getTargetBlockNumber()) const ownershipPredicateAddress = this.predicatesManager.getNativePredicate( 'OwnershipPredicate' ) const swapRequests = await this.client.getSwapRequest() if (swapRequests.isError()) { return new ChamberResultError(WalletErrorFactory.SwapRequestError()) } const tasks = swapRequests .ok() .map(swapRequest => { const neighbors = DefragAlgorithm.searchNeighbors( this.getUTXOArray(), swapRequest ) const neighbor = neighbors[0] if (neighbor) { swapRequest.setTarget(neighbor) return swapRequest } else { return null } }) .filter(swapRequest => !!swapRequest) .map(swapRequest => { if (swapRequest) { const tx = swapRequest.getSignedSwapTx( targetBlock, ownershipPredicateAddress ) if (tx) { tx.sign(this.wallet.privateKey) return this.client.swapRequestResponse(swapRequest.getOwner(), tx) } } return Promise.resolve( new ChamberResultError<boolean>(WalletErrorFactory.SwapRequestError()) ) }) .filter(p => !!p) return Promise.all(tasks) } public async sendSwap() { const swapTxResult = await this.client.getSwapRequestResponse( this.getAddress() ) if (swapTxResult.isOk()) { const swapTx = swapTxResult.ok() if (this.checkSwapTx(swapTx)) { swapTx.sign(this.wallet.privateKey) const result = await this.client.sendTransaction(swapTx) if (result.isOk()) { await this.client.clearSwapRequestResponse(this.getAddress()) } return result } } return new ChamberResultError(WalletErrorFactory.SwapRequestError()) } public async startDefragmentation(handler: (message: string) => void) { handler('start defragmentation') const result = await this.merge() handler('merge phase is finished') if (result.isOk()) { return } await this.swapRequest() handler('swap request phase is finished') await this.swapRequestRespond() handler('swap respond phase is finished') await this.sendSwap() handler('all steps are finished') } /** * @ignore */ private async updateBlock(block: Block) { const tasksForExistingStates = this.getUTXOArray().map(async tx => { const segmentedBlock = block.getSegmentedBlock( tx.getOutput().getSegment() ) const key = tx.getOutput().hash() return this.segmentHistoryManager.appendSegmentedBlock( key, segmentedBlock ) }) await Promise.all(tasksForExistingStates) const tasks = block .getUserTransactionAndProofs(this.wallet.address, this.predicatesManager) .map(async tx => { if (this.stateManager.spend(tx).length > 0) { this.emit('send', { tx }) this.storage.addUserAction( tx.blkNum.toNumber(), UserActionUtil.createSend(tx) ) } if ( tx.getOutput().isOwnedBy(this.wallet.address, this.predicatesManager) ) { this.segmentHistoryManager.init( tx.getOutput().hash(), tx.getOutput().getSegment() ) const verified = await this.verifyHistory(tx) if (verified) { this.stateManager.insert(tx) this.flushCurrentState() this.emit('receive', { tx }) this.storage.addUserAction( tx.blkNum.toNumber(), UserActionUtil.createReceive(tx) ) } } }) .filter(p => !!p) this.loadedBlockNumber = block.getBlockNumber() this.storage.setLoadedPlasmaBlockNumber(this.loadedBlockNumber) this.flushCurrentState() return tasks } /** * @description flush current stateUpdates to storage */ private flushCurrentState() { this.storage.setState(this.stateManager.serialize()) } private async _deposit(result: any): Promise<ChamberResult<StateUpdate>> { await result.wait() const receipt = await this.httpProvider.getTransactionReceipt(result.hash) if (receipt.logs && receipt.logs[0]) { const rootChainAddress = ethers.utils.getAddress( this.rootChainContract.address ) const log = receipt.logs.filter( log => log.address === rootChainAddress )[0] const logDesc = this.rootChainInterface.parseLog(log) return new ChamberOk( this.handleDeposit( logDesc.values._depositer, logDesc.values._tokenId, logDesc.values._start, logDesc.values._end, logDesc.values._blkNum ) ) } else { return new ChamberResultError(WalletErrorFactory.InvalidReceipt()) } } /** * @ignore */ private searchUtxo( to: Address, tokenId: number, amount: BigNumber, feeTo?: Address, fee?: BigNumber ): SignedTransaction | null { return TransferAlgorithm.searchUtxo( this.getUTXOArray(), this.getTargetBlockNumber(), this.predicatesManager.getNativePredicate('OwnershipPredicate'), to, tokenId, amount, feeTo, fee ) } private checkSwapTx(swapTx: SignedTransaction) { const input = swapTx .getStateUpdates() .filter(i => i.getOwner() === this.getAddress())[0] if (input) { return ( this.getUTXOArray().filter(tx => { // check input spent tx which user has return tx .getOutput() .verifyDeprecation( swapTx.hash(), input, swapTx.getTransactionWitness(), this.predicatesManager ) }).length > 0 ) } else { return false } } /** * @ignore * @param signedTx */ private async sendFastTransferToOperator( signedTx: SignedTransaction ): Promise<ChamberResult<FastTransferResponse>> { const fastTransferResponse = await this.client.fastTransfer(signedTx) // should check operator's signature: fastTransferResponse.sig // should count bandwidth: fastTransferResponse.tx if (fastTransferResponse.isOk()) { this.emit('receive', { tx: fastTransferResponse.ok().tx, isFast: true }) } return fastTransferResponse } }
the_stack
import React, { useState, useEffect, useCallback, useMemo, } from 'react'; import { pagePathUtils } from '@growi/core'; import { useTranslation } from 'react-i18next'; import { Collapse, Modal, ModalHeader, ModalBody, ModalFooter, } from 'reactstrap'; import { debounce } from 'throttle-debounce'; import { toastError } from '~/client/util/apiNotification'; import { apiv3Get, apiv3Put } from '~/client/util/apiv3-client'; import { isIPageInfoForEntity } from '~/interfaces/page'; import { useSiteUrl, useIsSearchServiceReachable } from '~/stores/context'; import { usePageRenameModal } from '~/stores/modal'; import { useSWRxPageInfo } from '~/stores/page'; import DuplicatedPathsTable from './DuplicatedPathsTable'; import ApiErrorMessageList from './PageManagement/ApiErrorMessageList'; import PagePathAutoComplete from './PagePathAutoComplete'; const isV5Compatible = (meta: unknown): boolean => { return isIPageInfoForEntity(meta) ? meta.isV5Compatible : true; }; const PageRenameModal = (): JSX.Element => { const { t } = useTranslation(); const { isUsersHomePage } = pagePathUtils; const { data: siteUrl } = useSiteUrl(); const { data: renameModalData, close: closeRenameModal } = usePageRenameModal(); const { data: isReachable } = useIsSearchServiceReachable(); const isOpened = renameModalData?.isOpened ?? false; const page = renameModalData?.page; const shouldFetch = isOpened && page != null && !isIPageInfoForEntity(page.meta); const { data: pageInfo } = useSWRxPageInfo(shouldFetch ? page?.data._id : null); if (page != null && pageInfo != null) { page.meta = pageInfo; } const [pageNameInput, setPageNameInput] = useState(''); const [errs, setErrs] = useState(null); const [subordinatedPages, setSubordinatedPages] = useState([]); const [existingPaths, setExistingPaths] = useState<string[]>([]); const [canRename, setCanRename] = useState(false); const [isRenameRecursively, setIsRenameRecursively] = useState(true); const [isRenameRedirect, setIsRenameRedirect] = useState(false); const [isRemainMetadata, setIsRemainMetadata] = useState(false); const [expandOtherOptions, setExpandOtherOptions] = useState(false); const [subordinatedError] = useState(null); const [isMatchedWithUserHomePagePath, setIsMatchedWithUserHomePagePath] = useState(false); const updateSubordinatedList = useCallback(async() => { if (page == null) { return; } const { path } = page.data; try { const res = await apiv3Get('/pages/subordinated-list', { path }); setSubordinatedPages(res.data.subordinatedPages); } catch (err) { setErrs(err); toastError(t('modal_rename.label.Failed to get subordinated pages')); } }, [page, t]); useEffect(() => { if (page != null && isOpened) { updateSubordinatedList(); setPageNameInput(page.data.path); } }, [isOpened, page, updateSubordinatedList]); const rename = useCallback(async() => { if (page == null || !canRename) { return; } const _isV5Compatible = isV5Compatible(page.meta); setErrs(null); const { _id, path, revision } = page.data; try { const response = await apiv3Put('/pages/rename', { pageId: _id, revisionId: revision, isRecursively: !_isV5Compatible ? isRenameRecursively : undefined, isRenameRedirect, updateMetadata: !isRemainMetadata, newPagePath: pageNameInput, path, }); const { page } = response.data; const url = new URL(page.path, 'https://dummy'); if (isRenameRedirect) { url.searchParams.append('withRedirect', 'true'); } const onRenamed = renameModalData?.opts?.onRenamed; if (onRenamed != null) { onRenamed(path); } closeRenameModal(); } catch (err) { setErrs(err); } }, [closeRenameModal, canRename, isRemainMetadata, isRenameRecursively, isRenameRedirect, page, pageNameInput, renameModalData?.opts?.onRenamed]); const checkExistPaths = useCallback(async(fromPath, toPath) => { if (page == null) { return; } try { const res = await apiv3Get<{ existPaths: string[]}>('/page/exist-paths', { fromPath, toPath }); const { existPaths } = res.data; if (existPaths.length === 0) { setCanRename(true); } setExistingPaths(existPaths); } catch (err) { setErrs(err); toastError(t('modal_rename.label.Failed to get exist path')); } }, [page, t]); const checkExistPathsDebounce = useMemo(() => { return debounce(1000, checkExistPaths); }, [checkExistPaths]); const checkIsUsersHomePageDebounce = useMemo(() => { const checkIsPagePathRenameable = () => { setIsMatchedWithUserHomePagePath(isUsersHomePage(pageNameInput)); }; return debounce(1000, checkIsPagePathRenameable); }, [isUsersHomePage, pageNameInput]); useEffect(() => { if (page != null && pageNameInput !== page.data.path) { checkExistPathsDebounce(page.data.path, pageNameInput); checkIsUsersHomePageDebounce(pageNameInput); } }, [pageNameInput, subordinatedPages, checkExistPathsDebounce, page, checkIsUsersHomePageDebounce]); useEffect(() => { setCanRename(false); }, [pageNameInput]); function ppacInputChangeHandler(value) { setErrs(null); setPageNameInput(value); } /** * change pageNameInput * @param {string} value */ function inputChangeHandler(value) { setErrs(null); setPageNameInput(value); } useEffect(() => { if (isOpened) { return; } // reset states after the modal closed setTimeout(() => { setPageNameInput(''); setErrs(null); setSubordinatedPages([]); setExistingPaths([]); setIsRenameRecursively(true); setIsRenameRedirect(false); setIsRemainMetadata(false); setExpandOtherOptions(false); }, 1000); }, [isOpened]); if (page == null) { return <></>; } const { path } = page.data; const isTargetPageDuplicate = existingPaths.includes(pageNameInput); let submitButtonDisabled = false; if (isMatchedWithUserHomePagePath) { submitButtonDisabled = true; } else if (!canRename) { submitButtonDisabled = true; } else if (isV5Compatible(page.meta)) { submitButtonDisabled = existingPaths.length !== 0; // v5 data } else { submitButtonDisabled = !isRenameRecursively; // v4 data } return ( <Modal size="lg" isOpen={isOpened} toggle={closeRenameModal} data-testid="page-rename-modal" autoFocus={false}> <ModalHeader tag="h4" toggle={closeRenameModal} className="bg-primary text-light"> { t('modal_rename.label.Move/Rename page') } </ModalHeader> <ModalBody> <div className="form-group"> <label>{ t('modal_rename.label.Current page name') }</label><br /> <code>{ path }</code> </div> <div className="form-group"> <label htmlFor="newPageName">{ t('modal_rename.label.New page name') }</label><br /> <div className="input-group"> <div className="input-group-prepend"> <span className="input-group-text">{siteUrl}</span> </div> <form className="flex-fill" onSubmit={(e) => { e.preventDefault(); rename() }}> {isReachable ? ( <PagePathAutoComplete initializedPath={path} onSubmit={rename} onInputChange={ppacInputChangeHandler} autoFocus /> ) : ( <input type="text" value={pageNameInput} className="form-control" onChange={e => inputChangeHandler(e.target.value)} required autoFocus /> )} </form> </div> </div> { isTargetPageDuplicate && ( <p className="text-danger">Error: Target path is duplicated.</p> ) } { isMatchedWithUserHomePagePath && ( <p className="text-danger">Error: Cannot move to directory under /user page.</p> ) } { !isV5Compatible(page.meta) && ( <> <div className="custom-control custom-radio custom-radio-warning"> <input className="custom-control-input" name="recursively" id="cbRenameThisPageOnly" type="radio" checked={!isRenameRecursively} onChange={() => setIsRenameRecursively(!isRenameRecursively)} /> <label className="custom-control-label" htmlFor="cbRenameThisPageOnly"> { t('modal_rename.label.Rename this page only') } </label> </div> <div className="custom-control custom-radio custom-radio-warning mt-1"> <input className="custom-control-input" name="withoutExistRecursively" id="cbForceRenameRecursively" type="radio" checked={isRenameRecursively} onChange={() => setIsRenameRecursively(!isRenameRecursively)} /> <label className="custom-control-label" htmlFor="cbForceRenameRecursively"> { t('modal_rename.label.Force rename all child pages') } <p className="form-text text-muted mt-0">{ t('modal_rename.help.recursive') }</p> </label> {isRenameRecursively && existingPaths.length !== 0 && ( <DuplicatedPathsTable existingPaths={existingPaths} fromPath={path} toPath={pageNameInput} /> ) } </div> </> ) } <p className="mt-2"> <button type="button" className="btn btn-link mt-2 p-0" aria-expanded="false" onClick={() => setExpandOtherOptions(!expandOtherOptions)}> <i className={`fa fa-fw fa-arrow-right ${expandOtherOptions ? 'fa-rotate-90' : ''}`}></i> { t('modal_rename.label.Other options') } </button> </p> <Collapse isOpen={expandOtherOptions}> <div className="custom-control custom-checkbox custom-checkbox-success"> <input className="custom-control-input" name="create_redirect" id="cbRenameRedirect" type="checkbox" checked={isRenameRedirect} onChange={() => setIsRenameRedirect(!isRenameRedirect)} /> <label className="custom-control-label" htmlFor="cbRenameRedirect"> { t('modal_rename.label.Redirect') } <p className="form-text text-muted mt-0">{ t('modal_rename.help.redirect') }</p> </label> </div> <div className="custom-control custom-checkbox custom-checkbox-primary"> <input className="custom-control-input" name="remain_metadata" id="cbRemainMetadata" type="checkbox" checked={isRemainMetadata} onChange={() => setIsRemainMetadata(!isRemainMetadata)} /> <label className="custom-control-label" htmlFor="cbRemainMetadata"> { t('modal_rename.label.Do not update metadata') } <p className="form-text text-muted mt-0">{ t('modal_rename.help.metadata') }</p> </label> </div> <div> {subordinatedError} </div> </Collapse> </ModalBody> <ModalFooter> <ApiErrorMessageList errs={errs} targetPath={pageNameInput} /> <button type="button" className="btn btn-primary" onClick={rename} disabled={submitButtonDisabled} >Rename </button> </ModalFooter> </Modal> ); }; export default PageRenameModal;
the_stack
import React, { useEffect, useRef, useCallback } from 'react' import G6, { Graph } from '@antv/g6/dist/g6.min.js' import { withoutUndo } from 'mobx-keystone' import { useSize } from 'ahooks' import { useMst } from '../context' import register from './item' import { observer } from 'mobx-react-lite' import ToolBar from '../components/model-toolbar' import './model.scss' import GraphEvent from './event' import { initStyle } from './item/style' import { useUpdateItem } from './hooks' import { RootInstance } from '../type' // import { debounce } from 'lodash' // import mst from 'test/mst' export default observer(() => { // const mst = useMst() const { setRef, erdGraph, containerRef } = useLocal() // const size = useSize(containerRef); return ( <> {/* <div>{mst.sys.checkedKeys.length}</div> */} {/* {JSON.stringify(size)} */} <ToolBar graph={erdGraph} /> <div ref={setRef} className='graph' /> </> ) }) const useLocal = () => { const mst = useMst() // window.kkk = mst const containerRef = useRef(null) const erdGraphRef = useRef<Graph>(null) const miniMapRef = useRef<any>(null) useEffect(() => { register(mst) }, []) const checkRef = useRef(+new Date()) const size = useSize(containerRef); useEffect(() => { // alert() // const { Nodes , edges } = mst if (!erdGraphRef.current) { // alert(mst.Nodes.length) // alert(mst === window.kkk) //alert('erdGraphRef.current = render') const Obj = render(containerRef.current, mst.Nodes, mst.edges, mst) erdGraphRef.current = Obj.graph miniMapRef.current = Obj.miniMap //alert('erdGraphRef.current') // alert(mst.graph.$modelId) async(() => { mst.graph.setG6Graph(erdGraphRef.current) // layout(erdGraphRef.current, Nodes , edges, mst) }) // window.kkk1 = mst } else { //alert(' layout(erdGraphRef.current, mst.Nodes ' + mst.Nodes.length) layout(erdGraphRef.current, mst.Nodes, mst.edges, mst) // erdGraphRef.current.fitView(0) } }, [JSON.stringify(mst.sys.checkedKeys), mst]) useEffect(() => { if (erdGraphRef.current && size.width && size.height) { // alert(erdGraphRef.current['isLayouting']) if (!erdGraphRef.current['isLayouting']) { const documentHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight const height = mst.sys.height === '100%' ? documentHeight - 45 : (mst.sys.height as number) - 45 erdGraphRef.current.changeSize(size.width, height) erdGraphRef.current.fitView(0) } } }, [size.height, size.width]) const setRef = useCallback( ref => { containerRef.current = ref }, [containerRef] ) useEffect(() => { // debounce(()=> { const graph = erdGraphRef.current if (graph) { const gwidth = graph.get('width') const gheight = graph.get('height') const point = graph.getCanvasByPoint(gwidth / 2, gheight / 2) graph.zoomTo(mst.graph.zoom, point) } // } // }, 100)() }, [mst.graph.zoom]) const reloadRef = useRef(false) useEffect(() => { // debounce(()=> { const graph = erdGraphRef.current if (graph) { if (!reloadRef.current) { reloadRef.current = true return } // alert() // graph.clear() // graph.data({ nodes: mst.Nodes, edges: mst.edges }) // graph.render() const isLargar = graph.getNodes().length > 50 graph.updateLayout({ type: mst.sys.dagreLayout ? 'dagre' : 'fruchterman', // condense: true, // cols: 3, workerEnabled: true, linkDistance: 0, pixelRatio: 2, // alphaDecay: isLargar ? 0.3 : 0.15, // preventOverlap: true, // clustering: true, clusterGravity: 100, speed: 2, gravity: 100, gpuEnabled: true, // collideStrength: 0.5, // type: 'dagre', // // controlPoints: true, // // nodeSize: [40, 20], // nodesep: 1, // ranksep: 1, // align: 'DL', // nodesep: 100, // 节点水平间距(px) // ranksep: 200, // 每一层节点之间间距 // nodeSpacing: isLargar ? -100 : -180, onLayoutEnd: () => { async(() => { // alert() graph['isLayouting'] = false // graph['isLayouting'] = false // alert('endlayout') graph.fitView(0) withoutUndo(() => { mst.graph.setZoom(graph.getZoom()) }) // alert('onLayoutEnd') }, 1000) } }) if (mst.sys.dagreLayout) { async(() => { // alert() graph.fitView(0) }, 1000) } } }, [mst.sys.dagreLayout]) // alert('useUpdateItem' + mst.graph.zoom) useUpdateItem({ currentModel: mst.sys.currentModel, graph: erdGraphRef.current as any, showNameOrLabel: mst.sys.showNameOrLabel, zoom: mst.graph.zoom, checkNum: checkRef.current, themeColor: mst.Ui.themeColor, darkness: mst.Ui.darkness }) useEffect(() => { if (erdGraphRef.current && miniMapRef.current) { // alert() if (!mst.sys.disableMiniMap) { erdGraphRef.current?.removePlugin(miniMapRef.current) } else { const miniMap = new G6.Minimap({ type: 'delegate', viewportClassName: 'g6-minimap-viewport-erd', delegateStyle: { fill: 'rgba(0,0,0,0.10)' } }) miniMapRef.current = miniMap erdGraphRef.current?.addPlugin(miniMap) } } }, [mst.sys.disableMiniMap]) return { containerRef, setRef, erdGraph: erdGraphRef.current } } // const MINZOOM = 0.01 // const toolbar = new G6.ToolBar(); // const edgeBundling = new G6.Bundling({ // bundleThreshold: 0.6, // K: 100, // }); const render = (container: any, nodes: any, edges: any, mst: RootInstance) => { const documentHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight const height = mst.sys.height === '100%' ? documentHeight - 45 : (mst.sys.height as number) - 45 // const height = mst.sys.height // alert(height) // alert(height) const styleConfig = initStyle({ primaryColor: mst.Ui.themeColor }).style const isLargar = nodes.length > 50 // alert(isLargar) const miniMap = new G6.Minimap({ type: 'delegate', viewportClassName: 'g6-minimap-viewport-erd', delegateStyle: { fill: 'rgba(0,0,0,0.10)' } }) const graph = new G6.Graph({ height, width: container.offsetWidth - 20, container, fitView: true, // workerEnabled: true, fitCenter: true, enabledStack: true, animate: true, gpuEnabled: true, pixelRatio: 2, // pixelRatio: 1, // animate: true, defaultEdge: styleConfig.default.edge, edgeStateStyles: { default: styleConfig.default.edge, active: { opacity: 1, size: 3 } }, minZoom: 0.01, maxZoom: 1.1, layout: { type: mst.sys.dagreLayout ? 'dagre' : 'force', condense: true, cols: 3, // gpuEnabled: true, workerEnabled: true, // workerScriptURL:'', linkDistance: 0, alphaDecay: isLargar ? 0.3 : undefined, preventOverlap: true, // collideStrength: 0.5, nodeSpacing: isLargar ? -100 : -180, onLayoutEnd: () => { graph['isLayouting'] = false graph['endLayout'] = true graph.fitView(0) graph['endLayout'] = false withoutUndo(() => { mst.graph.setZoom(graph.getZoom()) }) } }, modes: { default: [ 'drag-canvas', { type: 'zoom-canvas', minZoom: 0.0001, // enableOptimize: true, // optimizeZoom: true, maxZoom: 2.1 // enableOptimize: true, }, { type: 'drag-node' // enableDelegate: true, }, { type: 'edge-tooltip', formatText: model => { return model.tooltip as string }, offset: 10 } // { // type: 'activate-relations', // resetSelected: true, // trigger: 'click' // }, ] }, plugins: [ // toolbar, // ...[mst.sys.disableMiniMap ? [] : [miniMap]] ] }) // alert(mst === window.kkk) GraphEvent(graph, mst) // miniMap.init // const x = nodes[0].x // edgeBundling.bundling({ nodes, edges }); graph.data({ nodes, edges }) graph['isLayouting'] = true graph.render() graph.fitView(0) if (mst.sys.dagreLayout) { async(() => { // alert() graph.fitView(0) withoutUndo(() => { mst.graph.setZoom(graph.getZoom()) }) }) } // layout(graph, nodes) return { graph, miniMap } } const layout = (graph: Graph, nodes: any, edges, mst: RootInstance) => { // graph.clear() graph.changeData({ nodes, edges }) // graph.getNodes().filter((a) => !a.isSys).forEach((node: any) => { // // node.x = undefined // // node.y = undefined // const model = node.getModel() // if (!model.visible) { // // node.getContainer().hide() // graph.hideItem(node) // // return // } // }) // const _edges = graph.getEdges() // _edges.forEach((edge: any) => { // let sourceNode = edge.get('sourceNode') // let targetNode = edge.get('targetNode') // const targetModel = targetNode.getModel() // if (!targetModel.visible || !sourceNode.getModel().visible) { // edge.hide() // // return // } // }) // alert(graph.getNodes().length) // const isLargar = graph.getNodes().length > 50 // // alert(isLargar) // graph.isLayouting = true // async(() => graph.updateLayout({ // type: 'force', // condense: true, // // cols: 3, // workerEnabled: true, // linkDistance: 0, // alphaDecay: isLargar ? 0.1 : 0.3, // // preventOverlap: false, // // collideStrength: 0.5, // // nodeSpacing: -1000, // onLayoutEnd: () => { // graph.isLayouting = false // // graph.fitView(0) // alert() // // mst.graph.setZoom(graph.getZoom()) // } // })) // graph.fitView(0) return graph } const async = (fun, time = 500) => { setTimeout(fun, time) }
the_stack
import sinon, { SinonSandbox } from "sinon"; import test, { ExecutionContext } from "ava"; import { HttpHttpsEnvironment, TestEnvironment, TestEnvironmentConfig } from '../../../support/sdk/TestEnvironment'; import { ConfigIntegrationKind } from '../../../../src/models/AppConfig'; import { NotificationPermission } from "../../../../src/models/NotificationPermission"; import { PromptsManager } from '../../../../src/managers/PromptsManager'; import Slidedown from "../../../../src/slidedown/Slidedown"; import EventsTestHelper from "../../../support/tester/EventsTestHelper"; import { SlidedownManager } from "../../../../src/managers/slidedownManager/SlidedownManager"; import { SlidedownPromptingTestHelper } from "./_SlidedownPromptingTestHelpers"; import { mockGetIcon } from "../../../support/tester/utils"; import ConfirmationToast from "../../../../src/slidedown/ConfirmationToast"; import { stubServiceWorkerInstallation } from "../../../support/tester/sinonSandboxUtils"; /** * PROMPTING LOGIC UNIT TESTS FOR WEB PROMPTS FEATURE * Tests prompting behavior of things like * - showing multiple slidedowns * - slidedown queues * - slidedown configuration * - slidedown behavior * - slidedown manager behavior * - ...etc */ const sinonSandbox: SinonSandbox = sinon.sandbox.create(); const testHelper = new SlidedownPromptingTestHelper(sinonSandbox); const minimalPushSlidedownOptions = testHelper.getMinimalPushSlidedownOptions(); const minimalCategorySlidedownOptions = testHelper.getMinimalCategorySlidedownOptions(); const minimalSmsSlidedownOptions = testHelper.getMinimalSmsOptions(); const minimalEmailSlidedownOptions = testHelper.getMinimalEmailOptions(); const minimalSmsAndEmailOptions = testHelper.getMinimalSmsAndEmailOptions(); test.beforeEach(() => { mockGetIcon(); }); test.afterEach(function (_t: ExecutionContext) { sinonSandbox.restore(); OneSignal._initCalled = false; OneSignal.__initAlreadyCalled = false; OneSignal._sessionInitAlreadyRunning = false; }); const testConfig: TestEnvironmentConfig = { httpOrHttps: HttpHttpsEnvironment.Https, integration: ConfigIntegrationKind.Custom, permission: NotificationPermission.Default, pushIdentifier: 'granted', stubSetTimeout: true }; test("singular push slidedown prompts successfully", async t => { await testHelper.setupWithStubs(testConfig, t); const showSlidedownSpy = sinonSandbox.spy(PromptsManager.prototype as any, "internalShowSlidedownPrompt"); await testHelper.initWithPromptOptions([ minimalPushSlidedownOptions ]); t.is(showSlidedownSpy.callCount, 1); }); test("singular category slidedown prompts successfully", async t => { await testHelper.setupWithStubs(testConfig, t); const showCatSlidedownSpy = sinonSandbox.spy(PromptsManager.prototype, "internalShowCategorySlidedown"); await testHelper.initWithPromptOptions([ minimalCategorySlidedownOptions ]); t.is(showCatSlidedownSpy.callCount, 1); }); test("singular sms slidedown prompts successfully", async t => { await testHelper.setupWithStubs(testConfig, t); const showSmsSlidedownSpy = sinonSandbox.spy(PromptsManager.prototype, "internalShowSmsSlidedown"); await testHelper.initWithPromptOptions([ minimalSmsSlidedownOptions ]); t.is(showSmsSlidedownSpy.callCount, 1); }); test("singular email slidedown prompts successfully", async t => { await testHelper.setupWithStubs(testConfig, t); const showEmailSlidedownSpy = sinonSandbox.spy(PromptsManager.prototype, "internalShowEmailSlidedown"); await testHelper.initWithPromptOptions([ minimalEmailSlidedownOptions ]); t.is(showEmailSlidedownSpy.callCount, 1); }); test("singular sms & email slidedown prompts successfully", async t => { await testHelper.setupWithStubs(testConfig, t); const showSmsAndEmailSpy = sinonSandbox.spy(PromptsManager.prototype, "internalShowSmsAndEmailSlidedown"); await testHelper.initWithPromptOptions([ minimalSmsAndEmailOptions ]); t.is(showSmsAndEmailSpy.callCount, 1); }); test("session init 'spawns' as many autoPrompts as configured: 1", async t => { await testHelper.setupWithStubs(testConfig, t); const spawnAutopromptsSpy = sinonSandbox.spy(PromptsManager.prototype, "spawnAutoPrompts"); const showDelayedPromptsSpy = sinonSandbox.stub(PromptsManager.prototype, "internalShowDelayedPrompt"); await testHelper.initWithPromptOptions([ minimalPushSlidedownOptions ]); t.true(spawnAutopromptsSpy.called); t.is(showDelayedPromptsSpy.callCount, 1); }); test("session init 'spawns' as many autoPrompts as configured: 2", async t => { await testHelper.setupWithStubs(testConfig, t); const spawnAutopromptsSpy = sinonSandbox.spy(PromptsManager.prototype, "spawnAutoPrompts"); const showDelayedPromptsSpy = sinonSandbox.stub(PromptsManager.prototype, "internalShowDelayedPrompt"); await testHelper.initWithPromptOptions([ minimalPushSlidedownOptions, minimalCategorySlidedownOptions ]); t.true(spawnAutopromptsSpy.called); t.is(showDelayedPromptsSpy.callCount, 2); }); test("session init 'spawns' as many autoPrompts as configured: 3", async t => { await testHelper.setupWithStubs(testConfig, t); const spawnAutopromptsSpy = sinonSandbox.spy(PromptsManager.prototype, "spawnAutoPrompts"); const showDelayedPromptsSpy = sinonSandbox.stub(PromptsManager.prototype, "internalShowDelayedPrompt"); await testHelper.initWithPromptOptions([ minimalPushSlidedownOptions, minimalCategorySlidedownOptions, minimalSmsAndEmailOptions ]); t.true(spawnAutopromptsSpy.called); t.is(showDelayedPromptsSpy.callCount, 3); }); test("correct number of slidedowns are enqueued: once", async t => { await TestEnvironment.setupOneSignalPageWithStubs(sinonSandbox, testConfig, t); const enqueueSpy = sinonSandbox.spy(SlidedownManager.prototype, "enqueue"); const eventsHelper = new EventsTestHelper(sinonSandbox); const queuedPromise = new Promise<void>(resolve => { OneSignal.on(Slidedown.EVENTS.QUEUED, () => { eventsHelper.eventCounts.queued+=1; if (eventsHelper.eventCounts.queued === 1) { resolve(); } }); }); await testHelper.initWithPromptOptions([ testHelper.addPromptDelays(minimalCategorySlidedownOptions, 1, 0), testHelper.addPromptDelays(minimalPushSlidedownOptions, 1, 0), ]); await queuedPromise; t.is(enqueueSpy.callCount, 1); }); test("correct number of slidedowns are enqueued: twice", async t => { await TestEnvironment.setupOneSignalPageWithStubs(sinonSandbox, testConfig, t); const enqueueSpy = sinonSandbox.spy(SlidedownManager.prototype, "enqueue"); const eventsHelper = new EventsTestHelper(sinonSandbox); const queuedPromise = new Promise<void>(resolve => { OneSignal.on(Slidedown.EVENTS.QUEUED, () => { eventsHelper.eventCounts.queued+=1; if (eventsHelper.eventCounts.queued === 2) { resolve(); } }); }); await testHelper.initWithPromptOptions([ testHelper.addPromptDelays(minimalCategorySlidedownOptions, 1, 0), testHelper.addPromptDelays(minimalPushSlidedownOptions, 1, 0), testHelper.addPromptDelays(minimalSmsAndEmailOptions, 1, 0) ]); await queuedPromise; t.is(enqueueSpy.callCount, 2); }); test("on slidedown dismiss with slidedown queue non-empty, show next slidedown", async t => { await TestEnvironment.setupOneSignalPageWithStubs(sinonSandbox, testConfig, t); sinonSandbox.stub(SlidedownManager.prototype as any, "checkIfSlidedownShouldBeShown").resolves(true); const eventsHelper = new EventsTestHelper(sinonSandbox); const enqueueSpy = sinonSandbox.spy(SlidedownManager.prototype, "enqueue"); const showQueuedSpy = sinonSandbox.spy(SlidedownManager.prototype, "showQueued"); const queuedPromise = new Promise<void>(resolve => { OneSignal.on(Slidedown.EVENTS.QUEUED, () => { eventsHelper.eventCounts.queued+=1; if (eventsHelper.eventCounts.queued === 1) { EventsTestHelper.simulateSlidedownAllow(); resolve(); } }); }); const closedPromise = eventsHelper.getClosedPromiseWithEventCounts(); const shownPromise = eventsHelper.getShownPromiseWithEventCounts(2); await testHelper.initWithPromptOptions([ testHelper.addPromptDelays(minimalPushSlidedownOptions, 1, 0), testHelper.addPromptDelays(minimalCategorySlidedownOptions, 1, 1) ]); await queuedPromise; await closedPromise; await shownPromise; t.is(eventsHelper.eventCounts.shown, 2); t.is(enqueueSpy.callCount, 1); t.is(showQueuedSpy.callCount, 1); }); test("push & cat slidedowns configured -> cat shown first -> push slidedown not shown", async t => { await TestEnvironment.setupOneSignalPageWithStubs(sinonSandbox, testConfig, t); stubServiceWorkerInstallation(sinonSandbox); const eventsHelper = new EventsTestHelper(sinonSandbox); const enqueueSpy = sinonSandbox.spy(SlidedownManager.prototype, "enqueue"); const showQueuedSpy = sinonSandbox.spy(SlidedownManager.prototype, "showQueued"); const queuedPromise = new Promise<void>(resolve => { OneSignal.on(Slidedown.EVENTS.QUEUED, () => { eventsHelper.eventCounts.queued+=1; if (eventsHelper.eventCounts.queued === 1) { EventsTestHelper.simulateSlidedownAllow(); resolve(); } }); }); const closedPromise = eventsHelper.getClosedPromiseWithEventCounts(); const shownPromise = eventsHelper.getShownPromiseWithEventCounts(1); await testHelper.initWithPromptOptions([ testHelper.addPromptDelays(minimalCategorySlidedownOptions, 1, 0), testHelper.addPromptDelays(minimalPushSlidedownOptions, 1, 1) ]); await queuedPromise; await closedPromise; await shownPromise; t.is(eventsHelper.eventCounts.shown, 1); t.is(enqueueSpy.callCount, 1); t.is(showQueuedSpy.callCount, 1); }); test("confirmation toast shown and closed after allow", async t => { await TestEnvironment.setupOneSignalPageWithStubs(sinonSandbox, testConfig, t); const eventsHelper = new EventsTestHelper(sinonSandbox); const toastShownSpy = sinonSandbox.spy(ConfirmationToast.prototype, "show"); const toastCloseSpy = sinonSandbox.spy(ConfirmationToast.prototype, "close"); const slidedownShownPromise = eventsHelper.getShownPromiseWithEventCounts(1); const toastShownPromise = EventsTestHelper.getToastShownPromise(); const toastClosePromise = EventsTestHelper.getToastClosedPromise(); await testHelper.initWithPromptOptions([ testHelper.addPromptDelays(minimalEmailSlidedownOptions, 1, 0), ]); await slidedownShownPromise; // simulate typing in a valid email testHelper.inputEmail("rodrigo@onesignal.com"); EventsTestHelper.simulateSlidedownAllow(); await toastShownPromise; await toastClosePromise; t.is(toastShownSpy.callCount, 1); t.is(toastCloseSpy.callCount, 1); });
the_stack
import { Segmentation, SortedArray } from '../../../../mol-data/int'; import { Structure, Unit } from '../../structure'; import { StructureQuery } from '../query'; import { StructureSelection } from '../selection'; import { UniqueStructuresBuilder } from '../utils/builders'; import { StructureUniqueSubsetBuilder } from '../../structure/util/unique-subset-builder'; import { QueryContext, QueryFn } from '../context'; import { structureIntersect, structureSubtract, structureUnion } from '../utils/structure-set'; import { UniqueArray } from '../../../../mol-data/generic'; import { StructureSubsetBuilder } from '../../structure/util/subset-builder'; import { StructureElement } from '../../structure/element'; import { MmcifFormat } from '../../../../mol-model-formats/structure/mmcif'; import { ResidueSet, ResidueSetEntry } from '../../model/properties/utils/residue-set'; import { StructureProperties } from '../../structure/properties'; import { arraySetAdd } from '../../../../mol-util/array'; function getWholeResidues(ctx: QueryContext, source: Structure, structure: Structure) { const builder = source.subsetBuilder(true); for (const unit of structure.units) { if (unit.kind !== Unit.Kind.Atomic) { // just copy non-atomic units. builder.setUnit(unit.id, unit.elements); continue; } const { residueAtomSegments } = unit.model.atomicHierarchy; const sourceElements = source.unitMap.get(unit.id).elements; const elements = unit.elements; builder.beginUnit(unit.id); const residuesIt = Segmentation.transientSegments(residueAtomSegments, elements); while (residuesIt.hasNext) { const rI = residuesIt.move().index; for (let j = residueAtomSegments.offsets[rI], _j = residueAtomSegments.offsets[rI + 1]; j < _j; j++) { if (SortedArray.has(sourceElements, j)) builder.addElement(j); } } builder.commitUnit(); ctx.throwIfTimedOut(); } return builder.getStructure(); } export function wholeResidues(query: StructureQuery): StructureQuery { return function query_wholeResidues(ctx) { const inner = query(ctx); if (StructureSelection.isSingleton(inner)) { return StructureSelection.Singletons(ctx.inputStructure, getWholeResidues(ctx, ctx.inputStructure, inner.structure)); } else { const builder = new UniqueStructuresBuilder(ctx.inputStructure); for (const s of inner.structures) { builder.add(getWholeResidues(ctx, ctx.inputStructure, s)); } return builder.getSelection(); } }; } export interface IncludeSurroundingsParams { radius: number, elementRadius?: QueryFn<number>, wholeResidues?: boolean } function getIncludeSurroundings(ctx: QueryContext, source: Structure, structure: Structure, params: IncludeSurroundingsParams) { const builder = new StructureUniqueSubsetBuilder(source); const lookup = source.lookup3d; const r = params.radius; for (const unit of structure.units) { const { x, y, z } = unit.conformation; const elements = unit.elements; for (let i = 0, _i = elements.length; i < _i; i++) { const e = elements[i]; lookup.findIntoBuilder(x(e), y(e), z(e), r, builder); } ctx.throwIfTimedOut(); } return !!params.wholeResidues ? getWholeResidues(ctx, source, builder.getStructure()) : builder.getStructure(); } interface IncludeSurroundingsParamsWithRadius extends IncludeSurroundingsParams { elementRadius: QueryFn<number>, elementRadiusClosure: StructureElement.Property<number>, sourceMaxRadius: number } function getIncludeSurroundingsWithRadius(ctx: QueryContext, source: Structure, structure: Structure, params: IncludeSurroundingsParamsWithRadius) { const builder = new StructureUniqueSubsetBuilder(source); const lookup = source.lookup3d; const { elementRadius, elementRadiusClosure, sourceMaxRadius, radius } = params; ctx.pushCurrentElement(); ctx.element.structure = structure; for (const unit of structure.units) { ctx.element.unit = unit; const { x, y, z } = unit.conformation; const elements = unit.elements; for (let i = 0, _i = elements.length; i < _i; i++) { const e = elements[i]; ctx.element.element = e; const eRadius = elementRadius(ctx); lookup.findIntoBuilderWithRadius(x(e), y(e), z(e), eRadius, sourceMaxRadius, radius, elementRadiusClosure, builder); } ctx.throwIfTimedOut(); } ctx.popCurrentElement(); return !!params.wholeResidues ? getWholeResidues(ctx, source, builder.getStructure()) : builder.getStructure(); } function createElementRadiusFn(ctx: QueryContext, eRadius: QueryFn<number>): StructureElement.Property<number> { return e => { ctx.element.structure = e.structure; ctx.element.unit = e.unit; ctx.element.element = e.element; return eRadius(ctx); }; } function findStructureRadius(ctx: QueryContext, eRadius: QueryFn<number>) { let r = 0; ctx.element.structure = ctx.inputStructure; for (const unit of ctx.inputStructure.units) { ctx.element.unit = unit; const elements = unit.elements; for (let i = 0, _i = elements.length; i < _i; i++) { const e = elements[i]; ctx.element.element = e; const eR = eRadius(ctx); if (eR > r) r = eR; } } ctx.throwIfTimedOut(); return r; } export function includeSurroundings(query: StructureQuery, params: IncludeSurroundingsParams): StructureQuery { return function query_includeSurroundings(ctx) { const inner = query(ctx); if (params.elementRadius) { const prms: IncludeSurroundingsParamsWithRadius = { ...params, elementRadius: params.elementRadius, elementRadiusClosure: createElementRadiusFn(ctx, params.elementRadius), sourceMaxRadius: findStructureRadius(ctx, params.elementRadius) }; if (StructureSelection.isSingleton(inner)) { const surr = getIncludeSurroundingsWithRadius(ctx, ctx.inputStructure, inner.structure, prms); const ret = StructureSelection.Singletons(ctx.inputStructure, surr); return ret; } else { const builder = new UniqueStructuresBuilder(ctx.inputStructure); for (const s of inner.structures) { builder.add(getIncludeSurroundingsWithRadius(ctx, ctx.inputStructure, s, prms)); } return builder.getSelection(); } } if (StructureSelection.isSingleton(inner)) { const surr = getIncludeSurroundings(ctx, ctx.inputStructure, inner.structure, params); const ret = StructureSelection.Singletons(ctx.inputStructure, surr); return ret; } else { const builder = new UniqueStructuresBuilder(ctx.inputStructure); for (const s of inner.structures) { builder.add(getIncludeSurroundings(ctx, ctx.inputStructure, s, params)); } return builder.getSelection(); } }; } export function querySelection(selection: StructureQuery, query: StructureQuery): StructureQuery { return function query_querySelection(ctx) { const targetSel = selection(ctx); if (StructureSelection.structureCount(targetSel) === 0) return targetSel; const ret = StructureSelection.UniqueBuilder(ctx.inputStructure); const add = (s: Structure) => ret.add(s); StructureSelection.forEach(targetSel, (s, sI) => { ctx.pushInputStructure(s); StructureSelection.forEach(query(ctx), add); ctx.popInputStructure(); if (sI % 10 === 0) ctx.throwIfTimedOut(); }); return ret.getSelection(); }; } export function intersectBy(query: StructureQuery, by: StructureQuery): StructureQuery { return function query_intersectBy(ctx) { const selection = query(ctx); if (StructureSelection.structureCount(selection) === 0) return selection; const bySel = by(ctx); if (StructureSelection.structureCount(bySel) === 0) return StructureSelection.Empty(ctx.inputStructure); const unionBy = StructureSelection.unionStructure(bySel); const ret = StructureSelection.UniqueBuilder(ctx.inputStructure); StructureSelection.forEach(selection, (s, sI) => { const ii = structureIntersect(unionBy, s); if (ii.elementCount !== 0) ret.add(ii); if (sI % 50 === 0) ctx.throwIfTimedOut(); }); return ret.getSelection(); }; } export function exceptBy(query: StructureQuery, by: StructureQuery): StructureQuery { return function query_exceptBy(ctx) { const selection = query(ctx); if (StructureSelection.structureCount(selection) === 0) return selection; const bySel = by(ctx); if (StructureSelection.structureCount(bySel) === 0) return selection; const subtractBy = StructureSelection.unionStructure(bySel); const ret = StructureSelection.UniqueBuilder(ctx.inputStructure); StructureSelection.forEach(selection, (s, sI) => { const diff = structureSubtract(s, subtractBy); if (diff.elementCount !== 0) ret.add(diff); if (sI % 50 === 0) ctx.throwIfTimedOut(); }); return ret.getSelection(); }; } export function union(query: StructureQuery): StructureQuery { return function query_union(ctx) { const ret = StructureSelection.LinearBuilder(ctx.inputStructure); ret.add(StructureSelection.unionStructure(query(ctx))); return ret.getSelection(); }; } export function expandProperty(query: StructureQuery, property: QueryFn): StructureQuery { return function query_expandProperty(ctx) { const src = query(ctx); const propertyToStructureIndexMap = new Map<any, UniqueArray<number>>(); const builders: StructureSubsetBuilder[] = []; ctx.pushCurrentElement(); StructureSelection.forEach(src, (s, sI) => { ctx.element.structure = s; for (const unit of s.units) { ctx.element.unit = unit; const elements = unit.elements; for (let i = 0, _i = elements.length; i < _i; i++) { ctx.element.element = elements[i]; const p = property(ctx); let arr: UniqueArray<number>; if (propertyToStructureIndexMap.has(p)) arr = propertyToStructureIndexMap.get(p)!; else { arr = UniqueArray.create<number>(); propertyToStructureIndexMap.set(p, arr); } UniqueArray.add(arr, sI, sI); } } builders[sI] = ctx.inputStructure.subsetBuilder(true); if (sI % 10 === 0) ctx.throwIfTimedOut(); }); ctx.element.structure = ctx.inputStructure; for (const unit of ctx.inputStructure.units) { ctx.element.unit = unit; const elements = unit.elements; for (let i = 0, _i = elements.length; i < _i; i++) { ctx.element.element = elements[i]; const p = property(ctx); if (!propertyToStructureIndexMap.has(p)) continue; const indices = propertyToStructureIndexMap.get(p)!.array; for (let _sI = 0, __sI = indices.length; _sI < __sI; _sI++) { builders[indices[_sI]].addToUnit(unit.id, elements[i]); } } } ctx.popCurrentElement(); const ret = StructureSelection.UniqueBuilder(ctx.inputStructure); for (const b of builders) ret.add(b.getStructure()); return ret.getSelection(); }; } export interface IncludeConnectedParams { query: StructureQuery, bondTest?: QueryFn<boolean>, layerCount: number, wholeResidues: boolean, fixedPoint: boolean } export function includeConnected({ query, layerCount, wholeResidues, bondTest, fixedPoint }: IncludeConnectedParams): StructureQuery { const lc = Math.max(layerCount, 0); return function query_includeConnected(ctx) { const builder = StructureSelection.UniqueBuilder(ctx.inputStructure); const src = query(ctx); ctx.pushCurrentBond(); ctx.atomicBond.setTestFn(bondTest); StructureSelection.forEach(src, (s, sI) => { let incl = s; if (fixedPoint) { while (true) { const prevCount = incl.elementCount; incl = includeConnectedStep(ctx, wholeResidues, incl); if (incl.elementCount === prevCount) break; } } else { for (let i = 0; i < lc; i++) { incl = includeConnectedStep(ctx, wholeResidues, incl); } } builder.add(incl); if (sI % 10 === 0) ctx.throwIfTimedOut(); }); ctx.popCurrentBond(); return builder.getSelection(); }; } function includeConnectedStep(ctx: QueryContext, wholeResidues: boolean, structure: Structure) { const expanded = expandConnected(ctx, structure); if (wholeResidues) return getWholeResidues(ctx, ctx.inputStructure, expanded); return expanded; } function expandConnected(ctx: QueryContext, structure: Structure) { const inputStructure = ctx.inputStructure; const interBonds = inputStructure.interUnitBonds; const builder = new StructureUniqueSubsetBuilder(inputStructure); const atomicBond = ctx.atomicBond; // Process intra unit bonds for (const unit of structure.units) { if (unit.kind !== Unit.Kind.Atomic) { // add the whole unit builder.beginUnit(unit.id); for (let i = 0, _i = unit.elements.length; i < _i; i++) { builder.addElement(unit.elements[i]); } builder.commitUnit(); continue; } const inputUnitA = inputStructure.unitMap.get(unit.id) as Unit.Atomic; const { offset: intraBondOffset, b: intraBondB, edgeProps: { flags, order } } = inputUnitA.bonds; atomicBond.setStructure(inputStructure); // Process intra unit bonds atomicBond.a.unit = inputUnitA; atomicBond.b.unit = inputUnitA; for (let i = 0, _i = unit.elements.length; i < _i; i++) { // add the current element builder.addToUnit(unit.id, unit.elements[i]); const aIndex = SortedArray.indexOf(inputUnitA.elements, unit.elements[i]) as StructureElement.UnitIndex; // check intra unit bonds for (let lI = intraBondOffset[aIndex], _lI = intraBondOffset[aIndex + 1]; lI < _lI; lI++) { const bIndex = intraBondB[lI] as StructureElement.UnitIndex; const bElement = inputUnitA.elements[bIndex]; // Check if the element is already present: if (SortedArray.has(unit.elements, bElement) || builder.has(unit.id, bElement)) continue; atomicBond.aIndex = aIndex; atomicBond.a.element = unit.elements[i]; atomicBond.bIndex = bIndex; atomicBond.b.element = bElement; atomicBond.type = flags[lI]; atomicBond.order = order[lI]; if (atomicBond.test(ctx, true)) { builder.addToUnit(unit.id, bElement); } } } // Process inter unit bonds for (const bondedUnit of interBonds.getConnectedUnits(inputUnitA.id)) { const currentUnitB = structure.unitMap.get(bondedUnit.unitB); const inputUnitB = inputStructure.unitMap.get(bondedUnit.unitB) as Unit.Atomic; for (const aI of bondedUnit.connectedIndices) { // check if the element is in the expanded structure if (!SortedArray.has(unit.elements, inputUnitA.elements[aI])) continue; for (const bond of bondedUnit.getEdges(aI)) { const bElement = inputUnitB.elements[bond.indexB]; // Check if the element is already present: if ((currentUnitB && SortedArray.has(currentUnitB.elements, bElement)) || builder.has(bondedUnit.unitB, bElement)) continue; atomicBond.a.unit = inputUnitA; atomicBond.aIndex = aI; atomicBond.a.element = inputUnitA.elements[aI]; atomicBond.b.unit = inputUnitB; atomicBond.bIndex = bond.indexB; atomicBond.b.element = bElement; atomicBond.type = bond.props.flag; atomicBond.order = bond.props.order; if (atomicBond.test(ctx, true)) { builder.addToUnit(bondedUnit.unitB, bElement); } } } } } return builder.getStructure(); } export interface SurroundingLigandsParams { query: StructureQuery, radius: number, includeWater: boolean } /** * Includes expanded surrounding ligands based on radius from the source, struct_conn entries & pdbx_molecule entries. */ export function surroundingLigands({ query, radius, includeWater }: SurroundingLigandsParams): StructureQuery { return function query_surroundingLigands(ctx) { const inner = StructureSelection.unionStructure(query(ctx)); const surroundings = getWholeResidues(ctx, ctx.inputStructure, getIncludeSurroundings(ctx, ctx.inputStructure, inner, { radius })); const prd = getPrdAsymIdx(ctx.inputStructure); const graph = getStructConnInfo(ctx.inputStructure); const l = StructureElement.Location.create(surroundings); const includedPrdChains = new Map<string, string[]>(); const componentResidues = new ResidueSet({ checkOperator: true }); for (const unit of surroundings.units) { if (unit.kind !== Unit.Kind.Atomic) continue; l.unit = unit; const { elements } = unit; const chainsIt = Segmentation.transientSegments(unit.model.atomicHierarchy.chainAtomSegments, elements); const residuesIt = Segmentation.transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements); while (chainsIt.hasNext) { const chainSegment = chainsIt.move(); l.element = elements[chainSegment.start]; const asym_id = StructureProperties.chain.label_asym_id(l); const op_name = StructureProperties.unit.operator_name(l); // check for PRD molecules if (prd.has(asym_id)) { if (includedPrdChains.has(asym_id)) { arraySetAdd(includedPrdChains.get(asym_id)!, op_name); } else { includedPrdChains.set(asym_id, [op_name]); } continue; } const entityType = StructureProperties.entity.type(l); // test entity and chain if (entityType === 'water' || entityType === 'polymer') continue; residuesIt.setSegment(chainSegment); while (residuesIt.hasNext) { const residueSegment = residuesIt.move(); l.element = elements[residueSegment.start]; graph.addComponent(ResidueSet.getEntryFromLocation(l), componentResidues); } } ctx.throwIfTimedOut(); } // assemble the core structure const builder = ctx.inputStructure.subsetBuilder(true); for (const unit of ctx.inputStructure.units) { if (unit.kind !== Unit.Kind.Atomic) continue; l.unit = unit; const { elements } = unit; const chainsIt = Segmentation.transientSegments(unit.model.atomicHierarchy.chainAtomSegments, elements); const residuesIt = Segmentation.transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements); builder.beginUnit(unit.id); while (chainsIt.hasNext) { const chainSegment = chainsIt.move(); l.element = elements[chainSegment.start]; const asym_id = StructureProperties.chain.label_asym_id(l); const op_name = StructureProperties.unit.operator_name(l); if (includedPrdChains.has(asym_id) && includedPrdChains.get(asym_id)!.indexOf(op_name) >= 0) { builder.addElementRange(elements, chainSegment.start, chainSegment.end); continue; } if (!componentResidues.hasLabelAsymId(asym_id)) { continue; } residuesIt.setSegment(chainSegment); while (residuesIt.hasNext) { const residueSegment = residuesIt.move(); l.element = elements[residueSegment.start]; if (!componentResidues.has(l)) continue; builder.addElementRange(elements, residueSegment.start, residueSegment.end); } } builder.commitUnit(); ctx.throwIfTimedOut(); } const components = structureUnion(ctx.inputStructure, [builder.getStructure(), inner]); // add water if (includeWater) { const finalBuilder = new StructureUniqueSubsetBuilder(ctx.inputStructure); const lookup = ctx.inputStructure.lookup3d; for (const unit of components.units) { const { x, y, z } = unit.conformation; const elements = unit.elements; for (let i = 0, _i = elements.length; i < _i; i++) { const e = elements[i]; lookup.findIntoBuilderIf(x(e), y(e), z(e), radius, finalBuilder, testIsWater); finalBuilder.addToUnit(unit.id, e); } ctx.throwIfTimedOut(); } return StructureSelection.Sequence(ctx.inputStructure, [finalBuilder.getStructure()]); } else { return StructureSelection.Sequence(ctx.inputStructure, [components]); } }; } const _entity_type = StructureProperties.entity.type; function testIsWater(l: StructureElement.Location) { return _entity_type(l) === 'water'; } function getPrdAsymIdx(structure: Structure) { const model = structure.models[0]; const ids = new Set<string>(); if (!MmcifFormat.is(model.sourceData)) return ids; const { _rowCount, asym_id } = model.sourceData.data.db.pdbx_molecule; for (let i = 0; i < _rowCount; i++) { ids.add(asym_id.value(i)); } return ids; } function getStructConnInfo(structure: Structure) { const model = structure.models[0]; const graph = new StructConnGraph(); if (!MmcifFormat.is(model.sourceData)) return graph; const struct_conn = model.sourceData.data.db.struct_conn; const { conn_type_id } = struct_conn; const { ptnr1_label_asym_id, ptnr1_label_comp_id, ptnr1_label_seq_id, ptnr1_symmetry, pdbx_ptnr1_label_alt_id, pdbx_ptnr1_PDB_ins_code } = struct_conn; const { ptnr2_label_asym_id, ptnr2_label_comp_id, ptnr2_label_seq_id, ptnr2_symmetry, pdbx_ptnr2_label_alt_id, pdbx_ptnr2_PDB_ins_code } = struct_conn; for (let i = 0; i < struct_conn._rowCount; i++) { const bondType = conn_type_id.value(i); if (bondType !== 'covale' && bondType !== 'metalc') continue; const a: ResidueSetEntry = { label_asym_id: ptnr1_label_asym_id.value(i), label_comp_id: ptnr1_label_comp_id.value(i), label_seq_id: ptnr1_label_seq_id.value(i), label_alt_id: pdbx_ptnr1_label_alt_id.value(i), ins_code: pdbx_ptnr1_PDB_ins_code.value(i), operator_name: ptnr1_symmetry.value(i) ?? '1_555' }; const b: ResidueSetEntry = { label_asym_id: ptnr2_label_asym_id.value(i), label_comp_id: ptnr2_label_comp_id.value(i), label_seq_id: ptnr2_label_seq_id.value(i), label_alt_id: pdbx_ptnr2_label_alt_id.value(i), ins_code: pdbx_ptnr2_PDB_ins_code.value(i), operator_name: ptnr2_symmetry.value(i) ?? '1_555' }; graph.addEdge(a, b); } return graph; } class StructConnGraph { vertices = new Map<string, ResidueSetEntry>(); edges = new Map<string, string[]>(); private addVertex(e: ResidueSetEntry, label: string) { if (this.vertices.has(label)) return; this.vertices.set(label, e); this.edges.set(label, []); } addEdge(a: ResidueSetEntry, b: ResidueSetEntry) { const al = ResidueSet.getLabel(a); const bl = ResidueSet.getLabel(b); this.addVertex(a, al); this.addVertex(b, bl); arraySetAdd(this.edges.get(al)!, bl); arraySetAdd(this.edges.get(bl)!, al); } addComponent(start: ResidueSetEntry, set: ResidueSet) { const startLabel = ResidueSet.getLabel(start); if (!this.vertices.has(startLabel)) { set.add(start); return; } const visited = new Set<string>(); const added = new Set<string>(); const stack = [startLabel]; added.add(startLabel); set.add(start); while (stack.length > 0) { const a = stack.pop()!; visited.add(a); const u = this.vertices.get(a)!; for (const b of this.edges.get(a)!) { if (visited.has(b)) continue; stack.push(b); if (added.has(b)) continue; added.add(b); const v = this.vertices.get(b)!; if (u.operator_name === v.operator_name) { set.add({ ...v, operator_name: start.operator_name }); } else { set.add(v); } } } } } // TODO: unionBy (skip this one?), cluster
the_stack
import * as sl from "../socketLib/socketLib"; import { QRFunction, QRServerFunction, TypedEvent } from "../socketLib/socketLib"; import * as types from "../common/types"; import { AvailableProjectConfig } from "../common/types"; /** * Consists of the following contracts * * a contract on how the client --calls--> server * a contract on how the server --calls--> the client that is calling the server * a contract on how the server --anycasts-> all clients */ export var server = { echo: {} as QRServerFunction<{ text: string, num: number }, { text: string, num: number }, typeof client>, filePaths: {} as QRFunction<{}, { filePaths: types.FilePath[], rootDir: string, completed: boolean }>, makeAbsolute: {} as QRFunction<{ relativeFilePath: string }, { filePath: string }>, /** * File stuff */ openFile: {} as QRFunction<{ filePath: string }, { contents: string, saved: boolean, editorOptions: types.EditorOptions }>, closeFile: {} as QRFunction<{ filePath: string }, {}>, editFile: {} as QRFunction<{ filePath: string, edits: CodeEdit[] }, { saved: boolean }>, saveFile: {} as QRFunction<{ filePath: string }, {}>, getFileStatus: {} as QRFunction<{ filePath: string }, { saved: boolean }>, /** File Tree */ addFile: {} as QRFunction<{ filePath: string }, { error?: string }>, addFolder: {} as QRFunction<{ filePath: string }, { error?: string }>, deleteFromDisk: {} as QRFunction<{ files: string[], dirs: string[] }, { errors?: { filePath: string, error: string }[] }>, duplicateFile: {} as QRFunction<{ src: string, dest: string }, { error: string }>, duplicateDir: {} as QRFunction<{ src: string, dest: string }, { error: string }>, movePath: {} as QRFunction<{ src: string, dest: string }, { error: string }>, // both files / folders launchDirectory: {} as QRFunction<{ filePath: string }, { error?: Error }>, // both files / folders launchTerminal: {} as QRFunction<{ filePath: string }, { error?: Error }>, // both files / folders /** * config stuff */ availableProjects: {} as QRFunction<{}, AvailableProjectConfig[]>, getActiveProjectConfigDetails: {} as QRFunction<{}, AvailableProjectConfig>, setActiveProjectConfigDetails: {} as QRFunction<AvailableProjectConfig, {}>, isFilePathInActiveProject: {} as QRFunction<{ filePath: string }, { inActiveProject: boolean }>, setOpenUITabs: {} as QRFunction<{ sessionId: string, tabLayout: types.TabLayout, selectedTabId: string | null }, {}>, getOpenUITabs: {} as QRFunction<{ sessionId: string }, { tabLayout: types.TabLayout, selectedTabId: string | null }>, activeProjectFilePaths: {} as QRFunction<{}, { filePaths: string[] }>, sync: {} as QRFunction<{}, {}>, setSetting: {} as QRFunction<{ sessionId: string, settingId: string, value: any }, {}>, getSetting: {} as QRFunction<{ sessionId: string, settingId: string }, any>, getValidSessionId: {} as QRFunction<{ sessionId: string }, { sessionId: string; }>, /** * Error stuff */ getErrors: {} as QRFunction<{}, types.ErrorsByFilePath>, /** * Tested */ getTestResults: {} as QRFunction<{}, types.TestSuitesByFilePath>, /** * Project Service */ getCompletionsAtPosition: {} as QRFunction<Types.GetCompletionsAtPositionQuery, Types.GetCompletionsAtPositionResponse>, getCompletionEntryDetails: {} as QRFunction<Types.GetCompletionEntryDetailsQuery, Types.GetCompletionEntryDetailsResponse>, quickInfo: {} as QRFunction<Types.QuickInfoQuery, Types.QuickInfoResponse>, getRenameInfo: {} as QRFunction<Types.GetRenameInfoQuery, Types.GetRenameInfoResponse>, getDefinitionsAtPosition: {} as QRFunction<Types.GetDefinitionsAtPositionQuery, Types.GetDefinitionsAtPositionResponse>, getReferences: {} as QRFunction<Types.GetReferencesQuery, Types.GetReferencesResponse>, getDoctorInfo: {} as QRFunction<Types.GetDoctorInfoQuery, Types.GetDoctorInfoResponse>, formatDocument: {} as QRFunction<Types.FormatDocumentQuery, Types.FormatDocumentResponse>, formatDocumentRange: {} as QRFunction<Types.FormatDocumentRangeQuery, Types.FormatDocumentRangeResponse>, getNavigateToItems: {} as QRFunction<{}, types.GetNavigateToItemsResponse>, getNavigateToItemsForFilePath: {} as QRFunction<{ filePath: string }, types.GetNavigateToItemsResponse>, getDependencies: {} as QRFunction<{}, Types.GetDependenciesResponse>, getAST: {} as QRFunction<Types.GetASTQuery, Types.GetASTResponse>, getQuickFixes: {} as QRFunction<Types.GetQuickFixesQuery, Types.GetQuickFixesResponse>, applyQuickFix: {} as QRFunction<Types.ApplyQuickFixQuery, Types.ApplyQuickFixResponse>, getSemanticTree: {} as QRFunction<Types.GetSemanticTreeQuery, Types.GetSemanticTreeReponse>, getOccurrencesAtPosition: {} as QRFunction<Types.GetOccurancesAtPositionQuery, Types.GetOccurancesAtPositionResponse>, getFormattingEditsAfterKeystroke: {} as QRFunction<Types.FormattingEditsAfterKeystrokeQuery, Types.FormattingEditsAfterKeystrokeResponse>, removeUnusedImports: {} as QRFunction<Types.FilePathQuery, types.RefactoringsByFilePath>, /** * Documentation Browser */ getTopLevelModuleNames: {} as QRFunction<{}, types.GetTopLevelModuleNamesResponse>, getUpdatedModuleInformation: {} as QRFunction<{ filePath: string }, types.DocumentedType>, /** UML Diagram */ getUmlDiagramForFile: {} as QRFunction<{ filePath: string }, { classes: types.UMLClass[] }>, /** tsFlow */ getFlowRoots: {} as QRFunction<types.TsFlowRootQuery, types.TsFlowRootResponse>, /** live analysis */ getLiveAnalysis: {} as QRFunction<types.LiveAnalysisQuery, types.LiveAnalysisResponse>, /** * Output Status */ getCompleteOutputStatusCache: {} as QRFunction<{}, types.JSOutputStatusCache>, getLiveBuildResults: {} as QRFunction<{}, types.LiveBuildResults>, build: {} as QRFunction<{}, {}>, getJSOutputStatus: {} as QRFunction<Types.FilePathQuery, types.GetJSOutputStatusResponse>, /** * Live demo */ enableLiveDemo: {} as QRFunction<{ filePath: string }, {}>, disableLiveDemo: {} as QRFunction<{}, {}>, enableLiveDemoReact: {} as QRFunction<{ filePath: string }, {}>, disableLiveDemoReact: {} as QRFunction<{}, {}>, /** * Git service */ gitStatus: {} as QRFunction<{}, string>, gitReset: {} as QRFunction<{ filePath: string }, string>, gitDiff: {} as QRFunction<{ filePath: string }, types.GitDiff>, gitAddAllCommitAndPush: {} as QRFunction<types.GitAddAllCommitAndPushQuery, types.GitAddAllCommitAndPushResult>, gitFetchLatestAndRebase: {} as QRFunction<{}, types.GitAddAllCommitAndPushResult>, /** * NPM Service */ npmLatest: {} as QRFunction<{ pack: string }, { description?: string, version?: string }>, /** * FARM */ startFarming: {} as QRFunction<Types.FarmConfig, {}>, stopFarmingIfRunning: {} as QRFunction<{}, {}>, farmResults: {} as QRFunction<{}, Types.FarmNotification>, /** * Config creator */ createEditorconfig: {} as QRFunction<{}, { alreadyPresent: string }>, /** * Settings */ getSettingsFilePath: {} as QRFunction<{}, { filePath: string }>, /** * Server Disk Service */ getDirItems: {} as QRFunction<{ dirPath: string }, { dirItems: types.FilePath[] }>, } export var client = { increment: {} as QRFunction<{ num: number }, { num: number }>, } export var cast = { /** for testing */ hello: new TypedEvent<{ text: string }>(), /** If the file worker notices a change */ filePathsUpdated: new TypedEvent<{ filePaths: types.FilePath[]; rootDir: string; completed: boolean }>(), /** If an open and already saved file changes on disk */ savedFileChangedOnDisk: new TypedEvent<{ filePath: string; contents: string }>(), /** If a user does a code edit */ didEdits: new TypedEvent<{ filePath: string, edits: CodeEdit[] }>(), /** If any of the file status changes */ didStatusChange: new TypedEvent<{ filePath: string, saved: boolean, eol: string }>(), /** If file editor options change */ editorOptionsChanged: new TypedEvent<{ filePath: string, editorOptions: types.EditorOptions }>(), /** Errors for a file path */ errorsDelta: new TypedEvent<types.ErrorCacheDelta>(), /** Tested */ testResultsDelta: new TypedEvent<types.TestResultsDelta>(), testedWorking: new TypedEvent<types.Working>(), /** TS analysis taking place */ tsWorking: new TypedEvent<types.Working>(), /** Available projects updated */ availableProjectsUpdated: new TypedEvent<AvailableProjectConfig[]>(), /** Active project name updated */ activeProjectConfigDetailsUpdated: new TypedEvent<AvailableProjectConfig>(), /** Active project files */ activeProjectFilePathsUpdated: new TypedEvent<{ filePaths: string[] }>(), /** FARM */ farmResultsUpdated: new TypedEvent<Types.FarmNotification>(), /** JS Ouput status */ fileOutputStatusUpdated: new TypedEvent<types.JSOutputStatus>(), completeOutputStatusCacheUpdated: new TypedEvent<types.JSOutputStatusCache>(), liveBuildResults: new TypedEvent<types.LiveBuildResults>(), /** Live demo */ liveDemoData: new TypedEvent<types.LiveDemoData>(), liveDemoBuildComplete: new TypedEvent<types.LiveDemoBundleResult>(), /** Server quit */ serverExiting: new TypedEvent<{}>(), } /** * General utility interfaces */ export namespace Types { /** Used a lot in project service */ export interface FilePathQuery { filePath: string; } /** Used a lot in project service */ export interface FilePathPositionQuery { filePath: string; position: number; } /** Used a lot in project service */ export interface FilePathEditorPositionQuery { filePath: string; editorPosition: EditorPosition; } /** * FARM: * Find and Replace Multiple */ export type FarmResultsByFilePath = { [filePath: string]: FarmResultDetails[] }; export interface FarmResultDetails { filePath: string; /** 1 based at the moment ... todo Change it to 0 based */ line: number; preview: string; } export interface FarmConfig { query: string; isRegex: boolean; isFullWord: boolean; isCaseSensitive: boolean; globs: string[]; } export interface FarmNotification { completed: boolean; results: Types.FarmResultDetails[]; /** Might be null if no query */ config: Types.FarmConfig | null; } /** * Completions stuff */ export interface GetCompletionsAtPositionQuery extends FilePathPositionQuery { prefix: string; } export type Completion = types.Completion; export interface GetCompletionsAtPositionResponse { completions: Completion[]; endsInPunctuation: boolean; } export interface GetCompletionEntryDetailsQuery { filePath: string, position: number, label: string } export interface GetCompletionEntryDetailsResponse { display: string, comment: string } /** * Mouse hover */ export interface QuickInfoQuery extends FilePathPositionQuery { } export interface QuickInfoResponse { valid: boolean; // Do we have a valid response for this query info?: { name: string; comment: string; range?: { from: EditorPosition, to: EditorPosition } }, errors?: types.CodeError[] } /** * Rename refactoring */ export interface GetRenameInfoQuery extends FilePathPositionQuery { } export interface GetRenameInfoResponse { canRename: boolean; localizedErrorMessage?: string; displayName?: string; fullDisplayName?: string; // this includes the namespace name kind?: string; kindModifiers?: string; triggerSpan?: ts.TextSpan; locations?: { /** Note that the Text Spans are from bottom of file to top of file */ [filePath: string]: ts.TextSpan[] }; } /** * Goto definition */ export interface GetDefinitionsAtPositionQuery extends FilePathPositionQuery { } export interface GetDefinitionsAtPositionResponse { projectFileDirectory: string; definitions: { filePath: string; position: EditorPosition; span: ts.TextSpan; }[] } /** * Doctor */ export interface LangHelp { displayName: string; help: string; } export interface GetDoctorInfoQuery extends FilePathEditorPositionQuery { } export interface GetDoctorInfoResponse { valid: boolean; definitions: { filePath: string; position: EditorPosition; span: ts.TextSpan; }[]; quickInfo?: { name: string; comment: string; }; langHelp?: LangHelp; references: ReferenceDetails[]; } /** * References */ export interface GetReferencesQuery extends FilePathPositionQuery { } export interface GetReferencesResponse { references: ReferenceDetails[]; } /** * Formatting */ export interface FormatDocumentQuery extends FilePathQuery { editorOptions: types.EditorOptions; } export interface FormatDocumentResponse { edits: FormattingEdit[]; } export interface FormatDocumentRangeQuery extends FilePathQuery { editorOptions: types.EditorOptions; from: EditorPosition; to: EditorPosition; } export interface FormatDocumentRangeResponse { edits: FormattingEdit[]; } export interface FormattingEditsAfterKeystrokeQuery extends FilePathEditorPositionQuery { key: string editorOptions: types.EditorOptions; } export interface FormattingEdit { from: EditorPosition, to: EditorPosition, newText: string } export interface FormattingEditsAfterKeystrokeResponse { edits: FormattingEdit[] } /** * Dependency View */ export interface FileDependency { sourcePath: string; targetPath: string; } export interface GetDependenciesResponse { links: FileDependency[] } /** * AST View */ export enum ASTMode { /** ts.forEachChild() */ visitor, /** node.getChildren() */ children, } export interface GetASTQuery extends FilePathQuery { mode: ASTMode; } export interface GetASTResponse { root?: NodeDisplay } export interface NodeDisplay { kind: string; children: NodeDisplay[]; pos: number; end: number; /** Represents how many parents it has */ depth: number; /** If we had a flat structure this is where this item would belong */ nodeIndex: number; /** Key Details I understand */ details?: any; /** * Best attempt serialization of original node * We remove `parent` */ rawJson: any; } /** * Quick Fix */ /** Query interfaces */ export interface GetQuickFixesQuery extends FilePathPositionQuery { indentSize: number; } export interface QuickFixDisplay { /** Uniquely identifies which function will be called to carry out the fix */ key: string; /** What will be displayed in the UI */ display: string; } /** Apply interfaces */ export interface GetQuickFixesResponse { fixes: QuickFixDisplay[]; } export interface ApplyQuickFixQuery extends Types.GetQuickFixesQuery { key: string; // This will need to be special cased additionalData?: any; } export interface ApplyQuickFixResponse { refactorings: types.RefactoringsByFilePath; } /** * Semantic view */ export interface GetSemanticTreeQuery extends FilePathQuery { } export interface SemanticTreeNode { text: string; kind: string; kindModifiers: string; start: EditorPosition; end: EditorPosition; subNodes: SemanticTreeNode[]; } export interface GetSemanticTreeReponse { nodes: SemanticTreeNode[]; } /** * Get occurances */ export interface GetOccurancesAtPositionQuery extends FilePathEditorPositionQuery { } export interface GetOccurancesAtPositionResult { filePath: string; start: EditorPosition; end: EditorPosition; isWriteAccess: boolean; } export interface GetOccurancesAtPositionResponse { results: GetOccurancesAtPositionResult[]; } }
the_stack
import { expect } from 'chai'; import { each, every } from '@phosphor/algorithm'; import { IMessageHandler, IMessageHook, Message, MessageLoop } from '@phosphor/messaging'; import { SplitLayout, Widget } from '@phosphor/widgets'; const renderer: SplitLayout.IRenderer = { createHandle: () => document.createElement('div') }; class LogSplitLayout extends SplitLayout { methods: string[] = []; protected init(): void { super.init(); this.methods.push('init'); } protected attachWidget(index: number, widget: Widget): void { super.attachWidget(index, widget); this.methods.push('attachWidget'); } protected moveWidget(fromIndex: number, toIndex: number, widget: Widget): void { super.moveWidget(fromIndex, toIndex, widget); this.methods.push('moveWidget'); } protected detachWidget(index: number, widget: Widget): void { super.detachWidget(index, widget); this.methods.push('detachWidget'); } protected onAfterShow(msg: Message): void { super.onAfterShow(msg); this.methods.push('onAfterShow'); } protected onAfterAttach(msg: Message): void { super.onAfterAttach(msg); this.methods.push('onAfterAttach'); } protected onChildShown(msg: Widget.ChildMessage): void { super.onChildShown(msg); this.methods.push('onChildShown'); } protected onChildHidden(msg: Widget.ChildMessage): void { super.onChildHidden(msg); this.methods.push('onChildHidden'); } protected onResize(msg: Widget.ResizeMessage): void { super.onResize(msg); this.methods.push('onResize'); } protected onUpdateRequest(msg: Message): void { super.onUpdateRequest(msg); this.methods.push('onUpdateRequest'); } protected onFitRequest(msg: Message): void { super.onFitRequest(msg); this.methods.push('onFitRequest'); } } class LogHook implements IMessageHook { messages: string[] = []; messageHook(target: IMessageHandler, msg: Message): boolean { this.messages.push(msg.type); return true; } } describe('@phosphor/widgets', () => { describe('SplitLayout', () => { describe('#constructor()', () => { it('should accept a renderer', () => { let layout = new SplitLayout({ renderer }); expect(layout).to.be.an.instanceof(SplitLayout); }); }); describe('#orientation', () => { it('should get the layout orientation for the split layout', () => { let layout = new SplitLayout({ renderer }); expect(layout.orientation).to.equal('horizontal'); }); it('should set the layout orientation for the split layout', () => { let layout = new SplitLayout({ renderer }); layout.orientation = 'vertical'; expect(layout.orientation).to.equal('vertical'); }); it('should set the orientation attribute of the parent widget', () => { let parent = new Widget(); let layout = new SplitLayout({ renderer }); parent.layout = layout; layout.orientation = 'vertical'; expect(parent.node.getAttribute('data-orientation')).to.equal('vertical'); layout.orientation = 'horizontal'; expect(parent.node.getAttribute('data-orientation')).to.equal('horizontal'); }); it('should post a fit request to the parent widget', (done) => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; layout.orientation = 'vertical'; requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); done(); }); }); it('should be a no-op if the value does not change', (done) => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; layout.orientation = 'horizontal'; requestAnimationFrame(() => { expect(layout.methods).to.not.contain('onFitRequest'); done(); }); }); }); describe('#spacing', () => { it('should get the inter-element spacing for the split layout', () => { let layout = new SplitLayout({ renderer }); expect(layout.spacing).to.equal(4); }); it('should set the inter-element spacing for the split layout', () => { let layout = new SplitLayout({ renderer }); layout.spacing = 10; expect(layout.spacing).to.equal(10); }); it('should post a fit rquest to the parent widget', (done) => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; layout.spacing = 10; requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); done(); }); }); it('should be a no-op if the value does not change', (done) => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; layout.spacing = 4; requestAnimationFrame(() => { expect(layout.methods).to.not.contain('onFitRequest'); done(); }); }); }); describe('#renderer', () => { it('should get the renderer for the layout', () => { let layout = new SplitLayout({ renderer }); expect(layout.renderer).to.equal(renderer); }); }); describe('#handles', () => { it('should be a read-only sequence of the split handles in the layout', () => { let layout = new SplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; each(widgets, w => { layout.addWidget(w); }); expect(every(layout.handles, h => h instanceof HTMLElement)); }); }); describe('#relativeSizes()', () => { it('should get the current sizes of the widgets in the layout', () => { let layout = new SplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; let parent = new Widget(); parent.layout = layout; each(widgets, w => { layout.addWidget(w); }); let sizes = layout.relativeSizes(); expect(sizes).to.deep.equal([1/3, 1/3, 1/3]); parent.dispose(); }); }); describe('#setRelativeSizes()', () => { it('should set the desired sizes for the widgets in the panel', () => { let layout = new SplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; let parent = new Widget(); parent.layout = layout; each(widgets, w => { layout.addWidget(w); }); layout.setRelativeSizes([10, 10, 10]); let sizes = layout.relativeSizes(); expect(sizes).to.deep.equal([10/30, 10/30, 10/30]); parent.dispose(); }); it('should ignore extra values', () => { let layout = new SplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; let parent = new Widget(); parent.layout = layout; each(widgets, w => { layout.addWidget(w); }); layout.setRelativeSizes([10, 15, 20, 20]); let sizes = layout.relativeSizes(); expect(sizes).to.deep.equal([10/45, 15/45, 20/45]); parent.dispose(); }); }); describe('#moveHandle()', () => { it('should set the offset position of a split handle', (done) => { let parent = new Widget(); let layout = new SplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; each(widgets, w => { layout.addWidget(w); }); each(widgets, w => { w.node.style.minHeight = '100px'; }); each(widgets, w => { w.node.style.minWidth = '100px'; }); parent.layout = layout; Widget.attach(parent, document.body); MessageLoop.flush(); let handle = layout.handles[1]; let left = handle.offsetLeft; layout.moveHandle(1, left + 20); requestAnimationFrame(() => { expect(handle.offsetLeft).to.not.equal(left); done(); }); }); }); describe('#init()', () => { it('should set the orientation attribute of the parent widget', () => { let parent = new Widget(); let layout = new LogSplitLayout({ renderer }); parent.layout = layout; expect(layout.methods).to.contain('init'); expect(parent.node.getAttribute('data-orientation')).to.equal('horizontal'); }); it('should attach all widgets to the DOM', () => { let parent = new Widget(); Widget.attach(parent, document.body); let layout = new LogSplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; each(widgets, w => { layout.addWidget(w); }); parent.layout = layout; expect(every(widgets, w => w.parent === parent)).to.equal(true); expect(every(widgets, w => w.isAttached)).to.equal(true); parent.dispose(); }); }); describe('#attachWidget()', () => { it("should attach a widget to the parent's DOM node", () => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; let widget = new Widget(); layout.addWidget(widget); expect(layout.methods).to.contain('attachWidget'); expect(parent.node.contains(widget.node)).to.equal(true); expect(layout.handles.length).to.equal(1); }); it("should send before/after attach messages if the parent is attached", () => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); let widget = new Widget(); let hook = new LogHook(); MessageLoop.installMessageHook(widget, hook); parent.layout = layout; Widget.attach(parent, document.body); layout.addWidget(widget); expect(hook.messages).to.contain('before-attach'); expect(hook.messages).to.contain('after-attach'); }); it('should post a layout request for the parent widget', (done) => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; let widget = new Widget(); Widget.attach(parent, document.body); layout.addWidget(widget); requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); done(); }); }); }); describe('#moveWidget()', () => { it("should move a widget in the parent's DOM node", () => { let layout = new LogSplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; let parent = new Widget(); parent.layout = layout; each(widgets, w => { layout.addWidget(w); }); let widget = widgets[0]; let handle = layout.handles[0]; layout.insertWidget(2, widget); expect(layout.methods).to.contain('moveWidget'); expect(layout.handles[2]).to.equal(handle); expect(layout.widgets[2]).to.equal(widget); }); it('should post a a layout request to the parent', (done) => { let layout = new LogSplitLayout({ renderer }); let widgets = [new Widget(), new Widget(), new Widget()]; let parent = new Widget(); parent.layout = layout; each(widgets, w => { layout.addWidget(w); }); let widget = widgets[0]; layout.insertWidget(2, widget); requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); done(); }); }); }); describe('#detachWidget()', () => { it("should detach a widget from the parent's DOM node", () => { let layout = new LogSplitLayout({ renderer }); let widget = new Widget(); let parent = new Widget(); parent.layout = layout; layout.addWidget(widget); layout.removeWidget(widget); expect(layout.methods).to.contain('detachWidget'); expect(parent.node.contains(widget.node)).to.equal(false); parent.dispose(); }); it("should send before/after detach message if the parent is attached", () => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); let widget = new Widget(); let hook = new LogHook(); MessageLoop.installMessageHook(widget, hook); parent.layout = layout; layout.addWidget(widget); Widget.attach(parent, document.body); layout.removeWidget(widget); expect(layout.methods).to.contain('detachWidget'); expect(hook.messages).to.contain('before-detach'); expect(hook.messages).to.contain('after-detach'); parent.dispose(); }); it('should post a a layout request to the parent', (done) => { let layout = new LogSplitLayout({ renderer }); let widget = new Widget(); let parent = new Widget(); parent.layout = layout; layout.addWidget(widget); Widget.attach(parent, document.body); layout.removeWidget(widget); requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); parent.dispose(); done(); }); }); }); describe('#onAfterShow()', () => { it('should post an update to the parent', (done) => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; parent.hide(); Widget.attach(parent, document.body); parent.show(); expect(layout.methods).to.contain('onAfterShow'); requestAnimationFrame(() => { expect(layout.methods).to.contain('onUpdateRequest'); parent.dispose(); done(); }); }); }); describe('#onAfterAttach()', () => { it('should post a layout request to the parent', (done) => { let layout = new LogSplitLayout({ renderer }); let parent = new Widget(); parent.layout = layout; Widget.attach(parent, document.body); expect(layout.methods).to.contain('onAfterAttach'); requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); parent.dispose(); done(); }); }); }); describe('#onChildShown()', () => { it('should post a fit request to the parent', (done) => { let parent = new Widget(); let layout = new LogSplitLayout({ renderer }); parent.layout = layout; let widgets = [new Widget(), new Widget(), new Widget()]; widgets[0].hide(); each(widgets, w => { layout.addWidget(w); }); Widget.attach(parent, document.body); widgets[0].show(); expect(layout.methods).to.contain('onChildShown'); requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); parent.dispose(); done(); }); }); }); describe('#onChildHidden()', () => { it('should post a fit request to the parent', (done) => { let parent = new Widget(); let layout = new LogSplitLayout({ renderer }); parent.layout = layout; let widgets = [new Widget(), new Widget(), new Widget()]; each(widgets, w => { layout.addWidget(w); }); Widget.attach(parent, document.body); widgets[0].hide(); expect(layout.methods).to.contain('onChildHidden'); requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); parent.dispose(); done(); }); }); }); describe('#onResize', () => { it('should be called when a resize event is sent to the parent', () => { let parent = new Widget(); let layout = new LogSplitLayout({ renderer }); parent.layout = layout; let widgets = [new Widget(), new Widget(), new Widget()]; each(widgets, w => { layout.addWidget(w); }); Widget.attach(parent, document.body); MessageLoop.sendMessage(parent, Widget.ResizeMessage.UnknownSize); expect(layout.methods).to.contain('onResize'); parent.dispose(); }); }); describe('.getStretch()', () => { it('should get the split layout stretch factor for the given widget', () => { let widget = new Widget(); expect(SplitLayout.getStretch(widget)).to.equal(0); }); }); describe('.setStretch()', () => { it('should set the split layout stretch factor for the given widget', () => { let widget = new Widget(); SplitLayout.setStretch(widget, 10); expect(SplitLayout.getStretch(widget)).to.equal(10); }); it('should post a fit request to the parent', (done) => { let parent = new Widget(); let widget = new Widget(); let layout = new LogSplitLayout({ renderer }); parent.layout = layout; layout.addWidget(widget); SplitLayout.setStretch(widget, 10); requestAnimationFrame(() => { expect(layout.methods).to.contain('onFitRequest'); done(); }); }); }); }); });
the_stack
import { URL } from "url"; import { Readable } from "stream"; import { Injectable, OnModuleInit } from "@nestjs/common"; import { InjectRepository, InjectConnection } from "@nestjs/typeorm"; import { Repository, Connection, EntityManager, In } from "typeorm"; import { v4 as UUID } from "uuid"; import { Client as MinioClient } from "minio"; import { logger } from "@/logger"; import { ConfigService } from "@/config/config.service"; import { FileEntity } from "./file.entity"; import { FileUploadInfoDto, SignedFileUploadRequestDto } from "./dto"; // 10 minutes upload expire time const FILE_UPLOAD_EXPIRE_TIME = 10 * 60; // 20 minutes download expire time const FILE_DOWNLOAD_EXPIRE_TIME = 20 * 60 * 60; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent function encodeRFC5987ValueChars(str: string) { return ( encodeURIComponent(str) // Note that although RFC3986 reserves "!", RFC5987 does not, // so we do not need to escape it .replace(/['()]/g, escape) // i.e., %27 %28 %29 .replace(/\*/g, "%2A") // The following are not required for percent-encoding per RFC5987, // so we can allow for a little better readability over the wire: |`^ .replace(/%(?:7C|60|5E)/g, unescape) ); } interface MinioEndpointConfig { endPoint: string; port: number; useSSL: boolean; } function parseMainEndpointUrl(endpoint: string): MinioEndpointConfig { const url = new URL(endpoint); const result: Partial<MinioEndpointConfig> = {}; if (url.pathname !== "/") throw new Error("Main MinIO endpoint URL of a sub-directory is not supported."); if (url.username || url.password || url.hash || url.search) throw new Error("Authorization, search parameters and hash are not supported for main MinIO endpoint URL."); if (url.protocol === "http:") result.useSSL = false; else if (url.protocol === "https:") result.useSSL = true; else throw new Error( `Invalid protocol "${url.protocol}" for main MinIO endpoint URL. Only HTTP and HTTPS are supported.` ); result.endPoint = url.hostname; result.port = url.port ? Number(url.port) : result.useSSL ? 443 : 80; return result as MinioEndpointConfig; } function parseAlternativeEndpointUrl(endpoint: string): (originalUrl: string) => string { if (!endpoint) return originalUrl => originalUrl; const url = new URL(endpoint); if (url.hash || url.search) throw new Error("Search parameters and hash are not supported for alternative MinIO endpoint URL."); if (!url.pathname.endsWith("/")) throw new Error("Alternative MinIO endpoint URL's pathname must ends with '/'."); return originalUrl => { const parsedOriginUrl = new URL(originalUrl); return new URL(parsedOriginUrl.pathname.slice(1) + parsedOriginUrl.search + parsedOriginUrl.hash, url).toString(); }; } export enum AlternativeUrlFor { User, Judge } @Injectable() export class FileService implements OnModuleInit { private readonly minioClient: MinioClient; private readonly bucket: string; private readonly replaceWithAlternativeUrlFor: Record<AlternativeUrlFor, (originalUrl: string) => string>; constructor( @InjectConnection() private readonly connection: Connection, @InjectRepository(FileEntity) private readonly fileRepository: Repository<FileEntity>, private readonly configService: ConfigService ) { const config = this.configService.config.services.minio; this.minioClient = new MinioClient({ ...parseMainEndpointUrl(config.endpoint), accessKey: config.accessKey, secretKey: config.secretKey }); this.bucket = config.bucket; this.replaceWithAlternativeUrlFor = { [AlternativeUrlFor.User]: parseAlternativeEndpointUrl(config.endpointForUser), [AlternativeUrlFor.Judge]: parseAlternativeEndpointUrl(config.endpointForJudge) }; } fileExistsInMinio(uuid: string): Promise<boolean> { return new Promise(resolve => this.minioClient .statObject(this.bucket, uuid) .then(() => resolve(true)) .catch(() => resolve(false)) ); } async uploadFile(uuid: string, streamOrBufferOrFile: string | Buffer | Readable, retryCount = 10): Promise<void> { for (let i = 0; i < retryCount; i++) { try { /* eslint-disable no-await-in-loop */ if (typeof streamOrBufferOrFile === "string") await this.minioClient.fPutObject(this.bucket, uuid, streamOrBufferOrFile, {}); else await this.minioClient.putObject(this.bucket, uuid, streamOrBufferOrFile, {}); /* eslint-enable no-await-in-loop */ } catch (e) { if (i === retryCount - 1) throw e; else { // eslint-disable-next-line no-await-in-loop await new Promise(resolve => setTimeout(resolve, 1000)); continue; } } } } async onModuleInit(): Promise<void> { let bucketExists: boolean; try { bucketExists = await this.minioClient.bucketExists(this.bucket); } catch (e) { throw new Error( `Error initializing the MinIO client. Please check your configuration file and MinIO server. ${e}` ); } if (!bucketExists) throw new Error( `MinIO bucket ${this.bucket} doesn't exist. Please check your configuration file and MinIO server.` ); } /** * Process the client's request about uploading a file. * * * If the user has not uploaded the file, return a signed upload info object. * * If the user has uploaded the file, check the file existance, file size and limits. * * @note * The `checkLimit` function may return different result for each call with the same upload info. * * e.g. When a user uploaded other files before upload this file, the quota is enough before uploading but * not enough after uploading. * * If the file is checked to be exceeding the limit after uploaded, it will be deleted. * * @return A `SignedFileUploadRequestDto` to return to the client if the file is not uploaded. * @return `string` error message if client says the file is uploaded but we do not accept it according to some errors. * @return A `FileEntity` if the file is uploaded successfully and saved to the database. */ async processUploadRequest<LimitCheckErrorType extends string>( uploadInfo: FileUploadInfoDto, checkLimit: (size: number) => Promise<LimitCheckErrorType> | LimitCheckErrorType, transactionalEntityManager: EntityManager ): Promise<FileEntity | SignedFileUploadRequestDto | LimitCheckErrorType | "FILE_UUID_EXISTS" | "FILE_NOT_UPLOADED"> { const limitCheckError = await checkLimit(uploadInfo.size); if (limitCheckError) { if (uploadInfo.uuid) this.deleteUnfinishedUploadedFile(uploadInfo.uuid); return limitCheckError; } if (uploadInfo.uuid) { // The client says the file is uploaded if ((await transactionalEntityManager.count(FileEntity, { uuid: uploadInfo.uuid })) !== 0) return "FILE_UUID_EXISTS"; // Check file existance try { await this.minioClient.statObject(this.bucket, uploadInfo.uuid); } catch (e) { if (e.message === "The specified key does not exist.") { return "FILE_NOT_UPLOADED"; } throw e; } // Save to the database const file = new FileEntity(); file.uuid = uploadInfo.uuid; file.size = uploadInfo.size; file.uploadTime = new Date(); await transactionalEntityManager.save(FileEntity, file); return file; } else { // The client says it want to upload a file for this request return await this.signUploadRequest(uploadInfo.size, uploadInfo.size); } } /** * Sign a upload request for given size. The alternative MinIO endpoint for user will be used in the POST URL. */ private async signUploadRequest(minSize?: number, maxSize?: number): Promise<SignedFileUploadRequestDto> { const uuid = UUID(); const policy = this.minioClient.newPostPolicy(); policy.setBucket(this.bucket); policy.setKey(uuid); policy.setExpires(new Date(Date.now() + FILE_UPLOAD_EXPIRE_TIME * 1000)); if (minSize != null || maxSize != null) { policy.setContentLengthRange(minSize || 0, maxSize || 0); } const policyResult = await this.minioClient.presignedPostPolicy(policy); return { uuid, method: "POST", url: this.replaceWithAlternativeUrlFor[AlternativeUrlFor.User](policyResult.postURL), extraFormData: policyResult.formData, fileFieldName: "file" }; } /** * @return A function to run after transaction, to delete the file(s) actually. */ async deleteFile(uuid: string | string[], transactionalEntityManager: EntityManager): Promise<() => void> { if (typeof uuid === "string") { await transactionalEntityManager.delete(FileEntity, { uuid }); return () => this.minioClient.removeObject(this.bucket, uuid).catch(e => { logger.error(`Failed to delete file ${uuid}: ${e}`); }); } if (uuid.length > 0) { await transactionalEntityManager.delete(FileEntity, { uuid: In(uuid) }); return () => this.minioClient.removeObjects(this.bucket, uuid).catch(e => { logger.error(`Failed to delete file [${uuid}]: ${e}`); }); } return () => { /* do nothing */ }; } /** * Delete a user-uploaded file before calling finishUpload() */ deleteUnfinishedUploadedFile(uuid: string): void { this.minioClient.removeObject(this.bucket, uuid).catch(e => { if (e.message === "The specified key does not exist.") return; logger.error(`Failed to delete unfinished uploaded file ${uuid}: ${e}`); }); } async getFileSizes(uuids: string[], transcationalEntityManager: EntityManager): Promise<number[]> { if (uuids.length === 0) return []; const uniqueUuids = Array.from(new Set(uuids)); const files = await transcationalEntityManager.find(FileEntity, { uuid: In(uniqueUuids) }); const map = Object.fromEntries(files.map(file => [file.uuid, file])); return uuids.map(uuid => map[uuid].size); } async signDownloadLink({ uuid, downloadFilename, noExpire, useAlternativeEndpointFor }: { uuid: string; downloadFilename?: string; noExpire?: boolean; useAlternativeEndpointFor?: AlternativeUrlFor; }): Promise<string> { const url = await this.minioClient.presignedGetObject( this.bucket, uuid, // The maximum expire time is 7 days noExpire ? 24 * 60 * 60 * 7 : FILE_DOWNLOAD_EXPIRE_TIME, !downloadFilename ? {} : { "response-content-disposition": `attachment; filename="${encodeRFC5987ValueChars(downloadFilename)}"` } ); if (useAlternativeEndpointFor != null) return this.replaceWithAlternativeUrlFor[useAlternativeEndpointFor](url); else return url; } async runMaintainceTasks(): Promise<void> { // Delete unused files // TODO: Use listObjectsV2 instead, which returns at most 1000 objects in a time const stream = this.minioClient.listObjects(this.bucket); const deleteList: string[] = []; await new Promise((resolve, reject) => { const promises: Promise<void>[] = []; stream.on("data", object => { promises.push( (async () => { const uuid = object.name; if (!(await this.fileRepository.count({ uuid }))) { deleteList.push(uuid); } })() ); }); stream.on("end", () => Promise.all(promises).then(resolve).catch(reject)); stream.on("error", reject); }); await this.minioClient.removeObjects(this.bucket, deleteList); } }
the_stack
module android.graphics{ import StringBuilder = java.lang.StringBuilder; /** * Rect holds four integer coordinates for a rectangle. The rectangle is * represented by the coordinates of its 4 edges (left, top, right bottom). * These fields can be accessed directly. Use width() and height() to retrieve * the rectangle's width and height. Note: most methods do not check to see that * the coordinates are sorted correctly (i.e. left <= right and top <= bottom). * AndroidUI NOTE: current impl not limit integer to set. */ export class Rect { left : number = 0; top : number = 0; right : number = 0; bottom : number = 0; /** * Create a new empty Rect. All coordinates are initialized to 0. */ constructor(); /** * Create a new rectangle, initialized with the values in the specified * rectangle (which is left unmodified). * * @param r The rectangle whose coordinates are copied into the new * rectangle. */ constructor(r : Rect); /** * Create a new rectangle with the specified coordinates. Note: no range * checking is performed, so the caller must ensure that left <= right and * top <= bottom. * * @param left The X coordinate of the left side of the rectangle * @param top The Y coordinate of the top of the rectangle * @param right The X coordinate of the right side of the rectangle * @param bottom The Y coordinate of the bottom of the rectangle */ constructor(left : number, top : number, right : number, bottom : number); constructor(...args){ if(args.length===1){ let rect : Rect = args[0]; this.left = rect.left; this.top = rect.top; this.right = rect.right; this.bottom = rect.bottom; }else if(args.length === 4 || args.length === 0){ let [left = 0, t = 0, right = 0, bottom = 0] = args; this.left = left || 0; this.top = t || 0; this.right = right || 0; this.bottom = bottom || 0; } } equals(r : Rect) : boolean{ if (this === r) return true; if (!r || !(r instanceof Rect)) return false; return this.left === r.left && this.top === r.top && this.right === r.right && this.bottom === r.bottom; } toString() : string { let sb = new StringBuilder(); sb.append("Rect("); sb.append(this.left); sb.append(", "); sb.append(this.top); sb.append(" - "); sb.append(this.right); sb.append(", "); sb.append(this.bottom); sb.append(")"); return sb.toString(); } /** * Return a string representation of the rectangle in a compact form. */ toShortString(sb = new StringBuilder()) : string { sb.setLength(0); sb.append('['); sb.append(this.left); sb.append(','); sb.append(this.top); sb.append("]["); sb.append(this.right); sb.append(','); sb.append(this.bottom); sb.append(']'); return sb.toString(); } /** * Return a string representation of the rectangle in a well-defined format. * * <p>You can later recover the Rect from this string through * {@link #unflattenFromString(String)}. * * @return Returns a new String of the form "left top right bottom" */ flattenToString() : string { let sb = new StringBuilder(32); // WARNING: Do not change the format of this string, it must be // preserved because Rects are saved in this flattened format. sb.append(this.left); sb.append(' '); sb.append(this.top); sb.append(' '); sb.append(this.right); sb.append(' '); sb.append(this.bottom); return sb.toString(); } /** * Returns a Rect from a string of the form returned by {@link #flattenToString}, * or null if the string is not of that form. */ static unflattenFromString(str : string) : Rect { let parts = str.split(" "); return new Rect(Number.parseInt(parts[0]), Number.parseInt(parts[1]), Number.parseInt(parts[2]), Number.parseInt(parts[3])); } /** * Returns true if the rectangle is empty (left >= right or top >= bottom) */ isEmpty() : boolean { return this.left >= this.right || this.top >= this.bottom; } /** * @return the rectangle's width. This does not check for a valid rectangle * (i.e. left <= right) so the result may be negative. */ width() : number { return this.right - this.left; } /** * @return the rectangle's height. This does not check for a valid rectangle * (i.e. top <= bottom) so the result may be negative. */ height() : number { return this.bottom - this.top; } /** * @return the horizontal center of the rectangle. If the computed value * is fractional, this method returns the largest integer that is * less than the computed value. */ centerX() : number { return (this.left + this.right) >> 1; } /** * @return the vertical center of the rectangle. If the computed value * is fractional, this method returns the largest integer that is * less than the computed value. */ centerY() : number { return (this.top + this.bottom) >> 1; } /** * @return the exact horizontal center of the rectangle as a float. */ exactCenterX() : number { return (this.left + this.right) * 0.5; } /** * @return the exact vertical center of the rectangle as a float. */ exactCenterY() : number { return (this.top + this.bottom) * 0.5; } /** * Set the rectangle to (0,0,0,0) */ setEmpty() { this.left = this.right = this.top = this.bottom = 0; } /** * Copy the coordinates from src into this rectangle. * * @param src The rectangle whose coordinates are copied into this * rectangle. */ set(src : Rect); /** * Set the rectangle's coordinates to the specified values. Note: no range * checking is performed, so it is up to the caller to ensure that * left <= right and top <= bottom. * * @param left The X coordinate of the left side of the rectangle * @param top The Y coordinate of the top of the rectangle * @param right The X coordinate of the right side of the rectangle * @param bottom The Y coordinate of the bottom of the rectangle */ set(left, top, right, bottom); set(...args){ if (args.length === 1) { let rect : Rect = args[0]; [this.left, this.top, this.right, this.bottom] = [rect.left, rect.top, rect.right, rect.bottom]; }else { let [left = 0, t = 0, right = 0, bottom = 0] = args; this.left = left || 0; this.top = t || 0; this.right = right || 0; this.bottom = bottom || 0; } } /** * Offset the rectangle by adding dx to its left and right coordinates, and * adding dy to its top and bottom coordinates. * * @param dx The amount to add to the rectangle's left and right coordinates * @param dy The amount to add to the rectangle's top and bottom coordinates */ offset(dx, dy) { this.left += dx; this.top += dy; this.right += dx; this.bottom += dy; } /** * Offset the rectangle to a specific (left, top) position, * keeping its width and height the same. * * @param newLeft The new "left" coordinate for the rectangle * @param newTop The new "top" coordinate for the rectangle */ offsetTo(newLeft, newTop) { this.right += newLeft - this.left; this.bottom += newTop - this.top; this.left = newLeft; this.top = newTop; } /** * Inset the rectangle by (dx,dy). If dx is positive, then the sides are * moved inwards, making the rectangle narrower. If dx is negative, then the * sides are moved outwards, making the rectangle wider. The same holds true * for dy and the top and bottom. * * @param dx The amount to add(subtract) from the rectangle's left(right) * @param dy The amount to add(subtract) from the rectangle's top(bottom) */ inset(dx, dy) { this.left += dx; this.top += dy; this.right -= dx; this.bottom -= dy; } /** * Returns true if (x,y) is inside the rectangle. The left and top are * considered to be inside, while the right and bottom are not. This means * that for a x,y to be contained: left <= x < right and top <= y < bottom. * An empty rectangle never contains any point. * * @param x The X coordinate of the point being tested for containment * @param y The Y coordinate of the point being tested for containment * @return true iff (x,y) are contained by the rectangle, where containment * means left <= x < right and top <= y < bottom */ contains(x : number , y : number) : boolean; /** * Returns true iff the 4 specified sides of a rectangle are inside or equal * to this rectangle. i.e. is this rectangle a superset of the specified * rectangle. An empty rectangle never contains another rectangle. * * @param left The left side of the rectangle being tested for containment * @param top The top of the rectangle being tested for containment * @param right The right side of the rectangle being tested for containment * @param bottom The bottom of the rectangle being tested for containment * @return true iff the the 4 specified sides of a rectangle are inside or * equal to this rectangle */ contains(left : number, top : number, right : number, bottom : number) :boolean; /** * Returns true iff the specified rectangle r is inside or equal to this * rectangle. An empty rectangle never contains another rectangle. * * @param r The rectangle being tested for containment. * @return true iff the specified rectangle r is inside or equal to this * rectangle */ contains(r:Rect) : boolean; contains(...args) : boolean{ if(args.length === 1){ let r : Rect = args[0]; // check for empty first return this.left < this.right && this.top < this.bottom // now check for containment && this.left <= r.left && this.top <= r.top && this.right >= r.right && this.bottom >= r.bottom; }else if(args.length === 2){ let [x, y] = args; return this.left < this.right && this.top < this.bottom // check for empty first && x >= this.left && x < this.right && y >= this.top && y < this.bottom; }else{ let [left = 0, t = 0, right = 0, bottom = 0] = args; // check for empty first return this.left < this.right && this.top < this.bottom // now check for containment && this.left <= left && this.top <= t && this.right >= right && this.bottom >= bottom; } } /** * If the specified rectangle intersects this rectangle, return true and set * this rectangle to that intersection, otherwise return false and do not * change this rectangle. No check is performed to see if either rectangle * is empty. To just test for intersection, use intersects() * * @param r The rectangle being intersected with this rectangle. * @return true if the specified rectangle and this rectangle intersect * (and this rectangle is then set to that intersection) else * return false and do not change this rectangle. */ intersect(r : Rect) : boolean; /** * If the rectangle specified by left,top,right,bottom intersects this * rectangle, return true and set this rectangle to that intersection, * otherwise return false and do not change this rectangle. No check is * performed to see if either rectangle is empty. Note: To just test for * intersection, use {@link #intersects(Rect, Rect)}. * * @param left The left side of the rectangle being intersected with this * rectangle * @param top The top of the rectangle being intersected with this rectangle * @param right The right side of the rectangle being intersected with this * rectangle. * @param bottom The bottom of the rectangle being intersected with this * rectangle. * @return true if the specified rectangle and this rectangle intersect * (and this rectangle is then set to that intersection) else * return false and do not change this rectangle. */ intersect(left : number, top : number, right : number, bottom : number) : boolean; intersect(...args) : boolean{ if(args.length===1){ let rect : Rect = args[0]; return this.intersect(rect.left, rect.top, rect.right, rect.bottom); }else{ let [left = 0, t = 0, right = 0, bottom = 0] = args; if (this.left < right && left < this.right && this.top < bottom && t < this.bottom) { if (this.left < left) this.left = left; if (this.top < t) this.top = t; if (this.right > right) this.right = right; if (this.bottom > bottom) this.bottom = bottom; return true; } return false; } } /** * If rectangles a and b intersect, return true and set this rectangle to * that intersection, otherwise return false and do not change this * rectangle. No check is performed to see if either rectangle is empty. * To just test for intersection, use intersects() * * @param a The first rectangle being intersected with * @param b The second rectangle being intersected with * @return true iff the two specified rectangles intersect. If they do, set * this rectangle to that intersection. If they do not, return * false and do not change this rectangle. */ public setIntersect(a:Rect, b:Rect):boolean { if (a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom) { this.left = Math.max(a.left, b.left); this.top = Math.max(a.top, b.top); this.right = Math.min(a.right, b.right); this.bottom = Math.min(a.bottom, b.bottom); return true; } return false; } /** * Returns true if this rectangle intersects the specified rectangle. * In no event is this rectangle modified. No check is performed to see * if either rectangle is empty. To record the intersection, use intersect() * or setIntersect(). * * @param rect the rect * @return true iff the specified rectangle intersects this rectangle. In * no event is this rectangle modified. */ intersects(rect : Rect) : boolean; /** * Returns true if this rectangle intersects the specified rectangle. * In no event is this rectangle modified. No check is performed to see * if either rectangle is empty. To record the intersection, use intersect() * or setIntersect(). * * @param left The left side of the rectangle being tested for intersection * @param top The top of the rectangle being tested for intersection * @param right The right side of the rectangle being tested for * intersection * @param bottom The bottom of the rectangle being tested for intersection * @return true iff the specified rectangle intersects this rectangle. In * no event is this rectangle modified. */ intersects(left : number, top : number, right : number, bottom : number) : boolean; intersects(...args) : boolean{ if(args.length===1){ let rect : Rect = args[0]; return this.intersects(rect.left, rect.top, rect.right, rect.bottom); }else{ let [left = 0, t = 0, right = 0, bottom = 0] = args; return this.left < right && left < this.right && this.top < bottom && t < this.bottom; } } /** * Returns true iff the two specified rectangles intersect. In no event are * either of the rectangles modified. To record the intersection, * use {@link #intersect(Rect)} or {@link #setIntersect(Rect, Rect)}. * * @param a The first rectangle being tested for intersection * @param b The second rectangle being tested for intersection * @return true iff the two specified rectangles intersect. In no event are * either of the rectangles modified. */ public static intersects(a:Rect, b:Rect):boolean { return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; } /** * Update this Rect to enclose itself and the specified rectangle. If the * specified rectangle is empty, nothing is done. If this rectangle is empty * it is set to the specified rectangle. * * @param r The rectangle being unioned with this rectangle */ union(r : Rect); /** * Update this Rect to enclose itself and the [x,y] coordinate. There is no * check to see that this rectangle is non-empty. * * @param x The x coordinate of the point to add to the rectangle * @param y The y coordinate of the point to add to the rectangle */ union(x : number, y : number); /** * Update this Rect to enclose itself and the specified rectangle. If the * specified rectangle is empty, nothing is done. If this rectangle is empty * it is set to the specified rectangle. * * @param left The left edge being unioned with this rectangle * @param top The top edge being unioned with this rectangle * @param right The right edge being unioned with this rectangle * @param bottom The bottom edge being unioned with this rectangle */ union(left : number, top : number, right : number, bottom :number); union(...args) { if(arguments.length === 1){ let rect : Rect = args[0]; this.union(rect.left, rect.top, rect.right, rect.bottom); }else if(arguments.length === 2){ let [x=0, y=0] = args; if (x < this.left) { this.left = x; } else if (x > this.right) { this.right = x; } if (y < this.top) { this.top = y; } else if (y > this.bottom) { this.bottom = y; } }else{ let left = args[0]; let top = args[1]; let right = args[2]; let bottom = args[3]; if ((left < right) && (top < bottom)) { if ((this.left < this.right) && (this.top < this.bottom)) { if (this.left > left) this.left = left; if (this.top > top) this.top = top; if (this.right < right) this.right = right; if (this.bottom < bottom) this.bottom = bottom; } else { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } } } } /** * Swap top/bottom or left/right if there are flipped (i.e. left > right * and/or top > bottom). This can be called if * the edges are computed separately, and may have crossed over each other. * If the edges are already correct (i.e. left <= right and top <= bottom) * then nothing is done. */ sort() { if (this.left > this.right) { [this.left, this.right] = [this.right, this.left]; } if (this.top > this.bottom) { [this.top, this.bottom] = [this.bottom, this.top]; } } /** * Scales up the rect by the given scale. * @hide */ scale(scale : number) { if (scale != 1) { this.left = this.left * scale; this.top = this.top * scale; this.right = this.right * scale; this.bottom = this.bottom * scale; } } } }
the_stack
import decodeUtf8 from "extlib/js/decodeUtf8"; import encodeUtf8 from "extlib/js/encodeUtf8"; import exists from "extlib/js/exists"; import { formatFromVarargs, MemoryWalker } from "wasm-sys"; import { CORS_HEADERS, responseError, responseNoResults, responsePreflight, } from "./http"; // Set by Cloudflare to the WebAssembly module that was uploaded alongside this script. declare var QUERY_RUNNER_WASM: WebAssembly.Module; // Set by Cloudflare if DATA_STORE is "kv". declare var KV: { get<T>(key: string, encoding: "json"): Promise<T>; get(key: string, encoding: "text"): Promise<string>; get(key: string, encoding: "arrayBuffer"): Promise<ArrayBuffer>; }; // Following variables are set by build/js.rs. // Total number of documents. declare var DOCUMENT_COUNT: number; // Maximum amount of terms a query can have across all modes. declare var MAX_QUERY_TERMS: number; // Maximum amount of results returned at once. declare var MAX_RESULTS: number; declare var DATA_STORE: "kv" | "url"; // Only set if DATA_STORE is "url". declare var DATASTORE_URL_PREFIX: string; let fetchChunk: ( chunkIdPrefix: string, chunkId: number ) => Promise<ArrayBuffer>; if (DATA_STORE == "kv") { fetchChunk = async ( chunkIdPrefix: string, chunkId: number ): Promise<ArrayBuffer> => { const chunkData = await KV.get(`${chunkIdPrefix}${chunkId}`, "arrayBuffer"); console.log("Fetched chunk from KV"); return chunkData; }; } else { fetchChunk = async ( chunkIdPrefix: string, chunkId: number ): Promise<ArrayBuffer> => { const res = await fetch( `${DATASTORE_URL_PREFIX}${chunkIdPrefix}${chunkId}` ); console.log("Fetched chunk from KV"); return res.arrayBuffer(); }; } const wasmMemory = new WebAssembly.Memory({ initial: 1024 }); const wasmInstance = new WebAssembly.Instance(QUERY_RUNNER_WASM, { env: { printf(ptrFmt: number, ptrVarargs: number) { // There's no way to print without line terminator in standard JS (the execution runtime is not Node.js). // Any printf calls without a line terminator will still be printed with a line terminator. console.log( formatFromVarargs( queryRunnerMemory.forkAndJump(ptrFmt), queryRunnerMemory.forkAndJump(ptrVarargs) ).replace(/\n$/, "") ); return 0; }, fprintf(fd: number, ptrFmt: number, ptrVarargs: number) { const msg = formatFromVarargs( queryRunnerMemory.forkAndJump(ptrFmt), queryRunnerMemory.forkAndJump(ptrVarargs) ).replace(/\n$/, ""); if (fd == 1) { console.log(msg); } else { throw new Error(`[fprintf] ${msg}`); } return 0; }, memory: wasmMemory, }, }); const queryRunner = wasmInstance.exports as { // Keep synchronised with function declarations wasm/*.c with WASM_EXPORT. reset(): void; malloc(size: number): number; index_query_malloc(): number; index_query(input: number): number; find_chunk_containing_term(termPtr: number, termLen: number): number; find_chunk_containing_doc(doc: number): number; }; const queryRunnerMemory = new MemoryWalker(wasmMemory.buffer); const allocateKey = (key: string | number) => { if (typeof key == "string") { const encoded = encodeUtf8(key); const len = encoded.length; const ptr = queryRunner.malloc(len); queryRunnerMemory.forkAndJump(ptr).writeAll(encoded); return { ptr, len }; } else { return key; } }; type ChunkRef = { id: number; midPos: number; }; const findContainingChunk = (key: string | number): ChunkRef | undefined => { let chunkRefPtr; let cKey = allocateKey(key); if (typeof cKey == "number") { chunkRefPtr = queryRunner.find_chunk_containing_doc(cKey); } else { chunkRefPtr = queryRunner.find_chunk_containing_term(cKey.ptr, cKey.len); } console.log("Found containing chunk"); if (chunkRefPtr === 0) { return undefined; } const chunkRef = queryRunnerMemory.forkAndJump(chunkRefPtr); const chunkId = chunkRef.readUInt32LE(); const chunkMidPos = chunkRef.readUInt32LE(); return { id: chunkId, midPos: chunkMidPos }; }; const compareKey = (a: string | number, b: string | number): number => { return typeof a == "number" ? a - (b as number) : (a as string).localeCompare(b as string); }; const extractKeyAtPosInBstChunkJs = ( chunk: MemoryWalker, type: "string" | "number" ): string | number => { if (type == "string") { // Keep in sync with build::chunks::ChunkStrKey. const len = chunk.readUInt8(); return decodeUtf8(chunk.readSliceView(len)); } else { // Keep in sync with build::ChunkU32Key. return chunk.readUInt32LE(); } }; const searchInBstChunkJs = ( chunk: MemoryWalker, targetKey: string | number ): ArrayBuffer | undefined => { while (true) { const currentKey = extractKeyAtPosInBstChunkJs( chunk, typeof targetKey as any ); // Keep in sync with build::chunks::bst::BST::_serialise_node. const leftPos = chunk.readInt32LE(); const rightPos = chunk.readInt32LE(); const valueLen = chunk.readUInt32LE(); const cmp = compareKey(targetKey, currentKey); if (cmp < 0) { if (leftPos == -1) { break; } chunk.jumpTo(leftPos); } else if (cmp == 0) { console.log("Found entry in chunk"); return chunk.readSliceCopy(valueLen); } else { if (rightPos == -1) { break; } chunk.jumpTo(rightPos); } } console.log("Searched failed to find entry in chunk"); return undefined; }; const findAllInChunks = async ( chunkIdPrefix: string, keys: (string | number)[] ): Promise<(ArrayBuffer | undefined)[]> => { const results = []; // Group by chunk to avoid repeated fetches and memory management. const chunks = new Map< number, { keys: [string | number, number][]; midPos: number; } >(); for (const key of keys) { const chunkRef = findContainingChunk(key); // We reserve a spot in `results` and keep track of it so that results are in the same order as `keys`, // and missing keys have `undefined` and can be detected. const resultIdx = results.push(undefined) - 1; if (!chunkRef) { continue; } if (!chunks.has(chunkRef.id)) { chunks.set(chunkRef.id, { keys: [], midPos: chunkRef.midPos, }); } chunks.get(chunkRef.id)!.keys.push([key, resultIdx]); } // We want to process chunks one by one as otherwise we will run into memory limits // from fetching and allocating memory for too many at once. for (const [chunkId, { keys, midPos }] of chunks.entries()) { const chunkData = await fetchChunk(chunkIdPrefix, chunkId); // We need to reset as otherwise we might overflow memory with unused previous chunks. // queryRunner.reset(); // const res = searchInBstChunk(chunkData, chunkRef.midPos, key); for (const [key, resultIdx] of keys) { const entry = searchInBstChunkJs( new MemoryWalker(chunkData).jumpTo(midPos), key ); if (!entry) { continue; } results[resultIdx] = entry; } } return results; }; // Keep order in sync with mode_t. type ParsedQuery = [ // Require. string[], // Contain. string[], // Exclude. string[] ]; // Take a raw query string and parse in into an array with three subarrays, each subarray representing terms for a mode. const parseQuery = (termsRaw: string[]): ParsedQuery | undefined => { const modeTerms: ParsedQuery = [ Array<string>(), Array<string>(), Array<string>(), ]; for (const value of termsRaw) { // Synchronise mode IDs with mode_t enum in wasm/index.c. const matches = /^([012])_([^&]+)(?:&|$)/.exec(value); if (!matches) { return; } const mode = Number.parseInt(matches[1], 10); const term = decodeURIComponent(matches[2]); modeTerms[mode].push(term); } return modeTerms; }; type QueryResult = { continuation: number | null; total: number; documents: number[]; }; const readResult = (result: MemoryWalker): QueryResult => { // Synchronise with `results_t` in wasm/index.c. const continuation = result.readInt32LE(); const total = result.readUInt32LE(); const count = result.readUInt8(); // Starts from next WORD_SIZE (uint32_t) due to alignment. result.skip(3); const documents: number[] = []; for (let resultNo = 0; resultNo < count; resultNo++) { // Synchronise with `doc_id_t` in wasm/index.c. const docId = result.readUInt32LE(); documents.push(docId); } return { continuation: continuation == -1 ? null : continuation, total, documents, }; }; const findSerialisedTermBitmaps = ( query: ParsedQuery ): Promise<(ArrayBuffer | undefined)[][]> => // Keep in sync with deploy/mod.rs. Promise.all(query.map((modeTerms) => findAllInChunks("terms/", modeTerms))); const buildIndexQuery = async ( firstRank: number, modeTermBitmaps: ArrayBuffer[][] ): Promise<Uint8Array> => { const bitmapCount = modeTermBitmaps.reduce( (count, modeTerms) => count + modeTerms.length, 0 ); // Synchronise with index_query_t. const input = new MemoryWalker(new ArrayBuffer(4 + (bitmapCount + 3) * 4)); input.writeUInt32LE(firstRank); for (const mode of modeTermBitmaps) { for (const bitmap of mode) { const ptr = queryRunner.malloc(bitmap.byteLength); queryRunnerMemory.forkAndJump(ptr).writeAll(new Uint8Array(bitmap)); // WASM is LE. input.writeUInt32LE(ptr); } input.writeUInt32LE(0); } return new Uint8Array(input.buffer); }; const executePostingsListQuery = ( queryData: Uint8Array ): QueryResult | undefined => { const inputPtr = queryRunner.index_query_malloc(); queryRunnerMemory.forkAndJump(inputPtr).writeAll(queryData); const outputPtr = queryRunner.index_query(inputPtr); return outputPtr == 0 ? undefined : readResult(queryRunnerMemory.forkAndJump(outputPtr)); }; const getAsciiBytes = (str: string) => new Uint8Array(str.split("").map((c) => c.charCodeAt(0))); const COMMA = getAsciiBytes(","); const handleSearch = async (url: URL) => { // NOTE: Just because there are no valid words does not mean that there are no valid results. // For example, excluding an invalid word actually results in all entries matching. const query = parseQuery(url.searchParams.getAll("t")); if (!query) { return responseError("Malformed query"); } const continuation = Math.max( 0, Number.parseInt(url.searchParams.get("c") || "", 10) || 0 ); const termCount = query.reduce( (count, modeTerms) => count + modeTerms.length, 0 ); if (termCount > MAX_QUERY_TERMS) { return responseError("Too many terms", 413); } const modeTermBitmaps = await findSerialisedTermBitmaps(query); console.log("Bit sets retrieved"); // Handling non-existent terms: // - If REQUIRE, then immediately return zero results, regardless of other terms of any mode. // - If CONTAIN, then simply omit. // - If EXCLUDE, then it depends; if there are other terms of any mode, then simply omit. If there are no other terms of any mode, then return default results. if (modeTermBitmaps[0].some((bm) => !bm)) { return responseNoResults(); } modeTermBitmaps[1] = modeTermBitmaps[1].filter((bm) => bm); modeTermBitmaps[2] = modeTermBitmaps[2].filter((bm) => bm); let result: QueryResult; if (modeTermBitmaps.every((modeTerms) => !modeTerms.length)) { console.log("Using default results"); const after = continuation + MAX_RESULTS; result = { continuation: DOCUMENT_COUNT > after ? after : null, documents: Array.from( { length: MAX_RESULTS }, (_, i) => continuation + i ).filter((docId) => docId >= 0 && docId < DOCUMENT_COUNT), total: DOCUMENT_COUNT, }; } else { queryRunner.reset(); const indexQueryData = await buildIndexQuery( continuation, modeTermBitmaps as ArrayBuffer[][] ); console.log("Query built"); const maybeResult = await executePostingsListQuery(indexQueryData); if (!maybeResult) { throw new Error(`Failed to execute query`); } result = maybeResult; console.log("Query executed"); } // We want to avoid JSON.{parse,stringify} as they take up a lot of CPU time and often cause timeout exceptions in CF Workers for large payloads. // So, we manually build our response with buffers, as that's how documents are stored. // The buffers represent parts of the UTF-8 encoded JSON serialised response bytes. const jsonResPrefix = getAsciiBytes( `{"total":${result.total},"continuation":${result.continuation},"results":[` ); const jsonResSuffix = getAsciiBytes(`]}`); // Each document should be a JSON serialised value encoded in UTF-8. const documents = (await findAllInChunks("documents/", result.documents)) .filter(exists) .map((d) => new Uint8Array(d)); console.log("Documents fetched"); const stream = new TransformStream(); const writer = stream.writable.getWriter(); writer.write(jsonResPrefix); for (let i = 0; i < documents.length; i++) { if (i !== 0) { writer.write(COMMA); } writer.write(documents[i]); } writer.write(jsonResSuffix); writer.releaseLock(); return new Response(stream.readable, { status: 200, headers: { "Content-Type": "application/json", ...CORS_HEADERS, }, }); }; const requestHandler = async (request: Request) => { if (request.method == "OPTIONS") { return responsePreflight(); } const url = new URL(request.url); return url.pathname === "/search" ? handleSearch(url) : new Response(null, { status: 404 }); }; // See https://github.com/Microsoft/TypeScript/issues/14877. (self as unknown as ServiceWorkerGlobalScope).addEventListener( "fetch", (event) => { event.respondWith(requestHandler(event.request)); } );
the_stack
import { ActionTypes } from 'app/containers/Display/constants' import actions from 'app/containers/Display/actions' import { mockDisplayId, mockSlideId, mockGraphLayerFormed, mockWidgetFormed, mockFormedViews, mockHttpError, mockCover, mockSlide, mockSlideCoverUploadImgSrc, mockSlideSize, mockLayerScale, mockGraphLayerId, mockDeltaSize, mockFinish, mockDeltaPosition, mockEventTrigger, mockOperation, mockAlignmentType, mockSelected, mockExclusive, mockChangedOperationInfo, mockBaseLines, mockLayerParamsUnChanged, mockChangedParams, mockShareLinkParams, mockShareToken, mockAuthShareToken, mockPasswordToken, mockPassword, mockDisplayTitle } from './fixtures' describe('Display Actions', () => { describe('loadSlideDetail', () => { it('should return the correct type and passed displayId', () => { const expectedResult = { type: ActionTypes.LOAD_SLIDE_DETAIL, payload: { displayId: mockDisplayId, slideId: mockSlideId } } expect(actions.loadSlideDetail(mockDisplayId, mockSlideId)).toEqual( expectedResult ) }) }) describe('slideDetailLoaded', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_SLIDE_DETAIL_SUCCESS, payload: { slideId: mockSlideId, layers: [mockGraphLayerFormed], widgets: [mockWidgetFormed], formedViews: mockFormedViews } } expect( actions.slideDetailLoaded( mockSlideId, [mockGraphLayerFormed], [mockWidgetFormed], mockFormedViews ) ).toEqual(expectedResult) }) }) describe('loadSlideDetailFail', () => { it('should return the correct type and error', () => { const expectedResult = { type: ActionTypes.LOAD_SLIDE_DETAIL_FAILURE, payload: { err: mockHttpError } } expect(actions.loadSlideDetailFail(mockHttpError)).toEqual(expectedResult) }) }) describe('uploadCurrentSlideCover', () => { it('should return the correct type and right cover, slide', () => { const expectedResult = { type: ActionTypes.UPLOAD_CURRENT_SLIDE_COVER, payload: { cover: mockCover, slide: mockSlide } } expect(actions.uploadCurrentSlideCover(mockCover, mockSlide)).toEqual( expectedResult ) }) }) describe('currentSlideCoverUploaded', () => { it('should return the correct type and passed result', () => { const expectedResult = { type: ActionTypes.UPLOAD_CURRENT_SLIDE_COVER_SUCCESS, payload: { result: mockSlideCoverUploadImgSrc } } expect( actions.currentSlideCoverUploaded(mockSlideCoverUploadImgSrc) ).toEqual(expectedResult) }) }) describe('uploadCurrentSlideCoverFail', () => { it('should return the correct type and throw err', () => { const expectedResult = { type: ActionTypes.UPLOAD_CURRENT_SLIDE_COVER_FAILURE, payload: { error: mockHttpError } } expect(actions.uploadCurrentSlideCoverFail(mockHttpError)).toEqual( expectedResult ) }) }) describe('resizeLayer', () => { it('should return the correct type and resize params', () => { const expectedResult = { type: ActionTypes.RESIZE_LAYER, payload: { slideSize: mockSlideSize, scale: mockLayerScale, layerId: mockGraphLayerId, deltaSize: mockDeltaSize, finish: mockFinish } } expect( actions.resizeLayer( mockSlideSize, mockLayerScale, mockGraphLayerId, mockDeltaSize, mockFinish ) ).toEqual(expectedResult) }) }) describe('resizeLayerAdjusted', () => { it('should return the correct type and passed deltaSize', () => { const expectedResult = { type: ActionTypes.RESIZE_LAYER_ADJUSTED, payload: { layerIds: [mockGraphLayerId], deltaSize: mockDeltaSize, finish: mockFinish } } expect( actions.resizeLayerAdjusted([mockGraphLayerId], mockDeltaSize, mockFinish) ).toEqual(expectedResult) }) }) describe('dragLayer', () => { it('should return the correct type and drag params', () => { const expectedResult = { type: ActionTypes.DRAG_LAYER, payload: { slideSize: mockSlideSize, scale: mockLayerScale, layerId: mockGraphLayerId, deltaPosition: mockDeltaPosition, eventTrigger: mockEventTrigger, finish: mockFinish } } expect( actions.dragLayer( mockSlideSize, mockLayerScale, mockDeltaPosition, mockEventTrigger, mockFinish, mockGraphLayerId ) ).toEqual(expectedResult) }) }) describe('dragLayerAdjusted', () => { it('should return the correct type and drag params', () => { const expectedResult = { type: ActionTypes.DRAG_LAYER_ADJUSTED, payload: { layerIds: [mockGraphLayerId], slideSize: mockSlideSize, deltaPosition: mockDeltaPosition, finish: mockFinish } } expect( actions.dragLayerAdjusted( [mockGraphLayerId], mockSlideSize, mockDeltaPosition, mockFinish ) ).toEqual(expectedResult) }) }) describe('changeLayersStack', () => { it('should return the correct type and passed operation', () => { const expectedResult = { type: ActionTypes.CHANGE_LAYERS_STACK, payload: { operation: mockOperation } } expect(actions.changeLayersStack(mockOperation)).toEqual(expectedResult) }) }) describe('setLayersAlignment', () => { it('should return the correct type and passed alignmentType', () => { const expectedResult = { type: ActionTypes.SET_LAYERS_ALIGNMENT, payload: { alignmentType: mockAlignmentType } } expect(actions.setLayersAlignment(mockAlignmentType)).toEqual( expectedResult ) }) }) describe('selectLayer', () => { it('should return the correct type and passed layer status', () => { const expectedResult = { type: ActionTypes.SELECT_LAYER, payload: { layerId: mockGraphLayerId, selected: mockSelected, exclusive: mockExclusive } } expect( actions.selectLayer(mockGraphLayerId, mockSelected, mockExclusive) ).toEqual(expectedResult) }) }) describe('clearLayersOperationInfo', () => { it('should return the correct type and passed changedInfo', () => { const expectedResult = { type: ActionTypes.CLEAR_LAYERS_OPERATION_INFO, payload: { changedInfo: mockChangedOperationInfo } } expect(actions.clearLayersOperationInfo(mockChangedOperationInfo)).toEqual( expectedResult ) }) }) describe('clearEditorBaselines', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.CLEAR_EDITOR_BASELINES, payload: {} } expect(actions.clearEditorBaselines()).toEqual(expectedResult) }) }) describe('showEditorBaselines', () => { it('should return the correct type and baselines', () => { const expectedResult = { type: ActionTypes.SHOW_EDITOR_BASELINES, payload: { baselines: [mockBaseLines] } } expect(actions.showEditorBaselines([mockBaseLines])).toEqual(expectedResult) }) }) describe('copySlideLayers', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.COPY_SLIDE_LAYERS, payload: {} } expect(actions.copySlideLayers()).toEqual(expectedResult) }) }) describe('slideLayersCopied', () => { it('should return the correct type and layer', () => { const expectedResult = { type: ActionTypes.COPY_SLIDE_LAYERS_SUCCESS, payload: { layers: [mockGraphLayerFormed] } } expect(actions.slideLayersCopied([mockGraphLayerFormed])).toEqual(expectedResult) }) }) describe('pasteSlideLayers', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.PASTE_SLIDE_LAYERS, payload: {} } expect(actions.pasteSlideLayers()).toEqual(expectedResult) }) }) describe('addSlideLayers', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_SLIDE_LAYERS, payload: { displayId: mockDisplayId, slideId: mockSlideId, layers: [mockGraphLayerFormed], widgets: [mockWidgetFormed] } } expect( actions.addSlideLayers( mockDisplayId, mockSlideId, [mockGraphLayerFormed], [mockWidgetFormed] ) ).toEqual(expectedResult) }) }) describe('slideLayersAdded', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_SLIDE_LAYERS_SUCCESS, payload: { slideId: mockSlideId, layers: [mockGraphLayerFormed], widgets: [mockWidgetFormed] } } expect( actions.slideLayersAdded(mockSlideId, [mockGraphLayerFormed], [mockWidgetFormed]) ).toEqual(expectedResult) }) }) describe('addSlideLayersFail', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_SLIDE_LAYERS_FAILURE, payload: {} } expect(actions.addSlideLayersFail()).toEqual(expectedResult) }) }) describe('editSlideLayers', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.EDIT_SLIDE_LAYERS, payload: { displayId: mockDisplayId, slideId: mockSlideId, layers: [mockGraphLayerFormed], layerParamsUnChanged: mockLayerParamsUnChanged } } expect( actions.editSlideLayers( mockDisplayId, mockSlideId, [mockGraphLayerFormed], mockLayerParamsUnChanged ) ).toEqual(expectedResult) }) }) describe('slideLayersEdited', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.EDIT_SLIDE_LAYERS_SUCCESS, payload: { slideId: mockSlideId, layers: [mockGraphLayerFormed] } } expect(actions.slideLayersEdited(mockSlideId, [mockGraphLayerFormed])).toEqual( expectedResult ) }) }) describe('editSlideLayersFail', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.EDIT_SLIDE_LAYERS_FAILURE, payload: {} } expect(actions.editSlideLayersFail()).toEqual(expectedResult) }) }) describe('editSlideLayerParams', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.EDIT_SLIDE_LAYER_PARAMS, payload: { layerId: mockGraphLayerId, changedParams: mockChangedParams } } expect( actions.editSlideLayerParams(mockGraphLayerId, mockChangedParams) ).toEqual(expectedResult) }) }) describe('deleteSlideLayers', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_SLIDE_LAYERS, payload: { displayId: mockDisplayId, slideId: mockSlideId } } expect(actions.deleteSlideLayers(mockDisplayId, mockSlideId)).toEqual( expectedResult ) }) }) describe('changeLayerOperationInfo', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.CHANGE_LAYER_OPERATION_INFO, payload: { layerId: mockGraphLayerId, changedInfo: mockChangedOperationInfo } } expect( actions.changeLayerOperationInfo(mockGraphLayerId, mockChangedOperationInfo) ).toEqual(expectedResult) }) }) describe('slideLayersDeleted', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_SLIDE_LAYERS_SUCCESS, payload: { slideId: mockSlideId, layerIds: [mockGraphLayerId] } } expect(actions.slideLayersDeleted(mockSlideId, [mockGraphLayerId])).toEqual( expectedResult ) }) }) describe('deleteSlideLayersFail', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_SLIDE_LAYERS_FAILURE, payload: {} } expect(actions.deleteSlideLayersFail()).toEqual(expectedResult) }) }) describe('loadDisplayShareLink', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_DISPLAY_SHARE_LINK, payload: { params: mockShareLinkParams } } expect(actions.loadDisplayShareLink(mockShareLinkParams)).toEqual( expectedResult ) }) }) describe('displayShareLinkLoaded', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_DISPLAY_SHARE_LINK_SUCCESS, payload: { shareToken: mockShareToken } } expect(actions.displayShareLinkLoaded(mockShareToken)).toEqual( expectedResult ) }) }) describe('displayAuthorizedShareLinkLoaded', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_DISPLAY_AUTHORIZED_SHARE_LINK_SUCCESS, payload: { authorizedShareToken: mockAuthShareToken } } expect( actions.displayAuthorizedShareLinkLoaded(mockAuthShareToken) ).toEqual(expectedResult) }) }) describe('displayPasswordShareLinkLoaded', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_DISPLAY_PASSWORD_SHARE_LINK_SUCCESS, payload: { passwordShareToken: mockPasswordToken, password: mockPassword } } expect( actions.displayPasswordShareLinkLoaded(mockPasswordToken, mockPassword) ).toEqual(expectedResult) }) }) describe('loadDisplayShareLinkFail', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_DISPLAY_SHARE_LINK_FAILURE, payload: {} } expect(actions.loadDisplayShareLinkFail()).toEqual(expectedResult) }) }) describe('openSharePanel', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.OPEN_SHARE_PANEL, payload: { id: mockDisplayId, title: mockDisplayTitle } } expect(actions.openSharePanel(mockDisplayId, mockDisplayTitle)).toEqual( expectedResult ) }) }) describe('closeSharePanel', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.CLOSE_SHARE_PANEL } expect(actions.closeSharePanel()).toEqual(expectedResult) }) }) describe('resetDisplayState', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.RESET_DISPLAY_STATE, payload: {} } expect(actions.resetDisplayState()).toEqual(expectedResult) }) }) describe('monitoredSyncDataAction', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.MONITORED_SYNC_DATA_ACTION, payload: {} } expect(actions.monitoredSyncDataAction()).toEqual(expectedResult) }) }) describe('monitoredSearchDataAction', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.MONITORED_SEARCH_DATA_ACTION, payload: {} } expect(actions.monitoredSearchDataAction()).toEqual(expectedResult) }) }) describe('monitoredLinkageDataAction', () => { it('should return the correct type', () => { const expectedResult = { type: ActionTypes.MONITORED_LINKAGE_DATA_ACTION, payload: {} } expect(actions.monitoredLinkageDataAction()).toEqual(expectedResult) }) }) })
the_stack
require('module-alias/register'); import * as _ from 'lodash'; import * as ABIDecoder from 'abi-decoder'; import * as chai from 'chai'; import { Address, SetProtocolTestUtils as SetTestUtils } from 'set-protocol-utils'; import { BigNumber } from 'bignumber.js'; import ChaiSetup from '@utils/chaiSetup'; import { BigNumberSetup } from '@utils/bigNumberSetup'; import { BadCTokenMockContract, ConstantAuctionPriceCurveContract, CoreMockContract, RebalanceAuctionModuleMockContract, RebalancingSetCTokenBidderContract, RebalancingSetTokenContract, RebalancingSetTokenFactoryContract, RebalancingSetTokenV3Contract, SetTokenContract, SetTokenFactoryContract, StandardTokenMockContract, TransferProxyContract, TWAPLiquidatorContract, VaultContract, WhiteListContract, } from '@utils/contracts'; import { ether } from '@utils/units'; import { DEFAULT_GAS, ONE_DAY_IN_SECONDS, DEFAULT_AUCTION_PRICE_NUMERATOR, DEFAULT_AUCTION_PRICE_DIVISOR, DEFAULT_REBALANCING_NATURAL_UNIT, ONE_HOUR_IN_SECONDS, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, ZERO, } from '@utils/constants'; import { expectRevertError } from '@utils/tokenAssertions'; import { Blockchain } from '@utils/blockchain'; import { getWeb3 } from '@utils/web3Helper'; import { BidPlacedCToken } from '@utils/contract_logs/rebalancingSetCTokenBidder'; import { getLinearAuction } from '@utils/auction'; import { CoreHelper } from '@utils/helpers/coreHelper'; import { CompoundHelper } from '@utils/helpers/compoundHelper'; import { ERC20Helper } from '@utils/helpers/erc20Helper'; import { OracleHelper } from 'set-protocol-oracles'; import { LiquidatorHelper } from '@utils/helpers/liquidatorHelper'; import { RebalancingSetV3Helper } from '@utils/helpers/rebalancingSetV3Helper'; import { RebalanceTestSetup } from '@utils/helpers/rebalanceTestSetup'; import { ValuationHelper } from '@utils/helpers/valuationHelper'; import { RebalancingSetBidderHelper } from '@utils/helpers/rebalancingSetBidderHelper'; BigNumberSetup.configure(); ChaiSetup.configure(); const web3 = getWeb3(); const blockchain = new Blockchain(web3); const setTestUtils = new SetTestUtils(web3); const { expect } = chai; contract('RebalancingSetCTokenBidder', accounts => { const [ deployerAccount, managerAccount, feeRecipient, ] = accounts; let coreMock: CoreMockContract; let transferProxy: TransferProxyContract; let vault: VaultContract; let rebalanceAuctionModuleMock: RebalanceAuctionModuleMockContract; let factory: SetTokenFactoryContract; let rebalancingComponentWhiteList: WhiteListContract; let rebalancingFactory: RebalancingSetTokenFactoryContract; let constantAuctionPriceCurve: ConstantAuctionPriceCurveContract; const coreHelper = new CoreHelper(deployerAccount, deployerAccount); const compoundHelper = new CompoundHelper(deployerAccount); const erc20Helper = new ERC20Helper(deployerAccount); const rebalancingHelper = new RebalancingSetV3Helper( deployerAccount, coreHelper, erc20Helper, blockchain ); const rebalancingSetBidderHelper = new RebalancingSetBidderHelper(deployerAccount); const oracleHelper = new OracleHelper(deployerAccount); const valuationHelper = new ValuationHelper(deployerAccount, coreHelper, erc20Helper, oracleHelper); const liquidatorHelper = new LiquidatorHelper(deployerAccount, erc20Helper, valuationHelper); before(async () => { ABIDecoder.addABI(CoreMockContract.getAbi()); ABIDecoder.addABI(RebalanceAuctionModuleMockContract.getAbi()); ABIDecoder.addABI(RebalancingSetCTokenBidderContract.getAbi()); transferProxy = await coreHelper.deployTransferProxyAsync(); vault = await coreHelper.deployVaultAsync(); coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault); rebalanceAuctionModuleMock = await coreHelper.deployRebalanceAuctionModuleMockAsync(coreMock, vault); await coreHelper.addModuleAsync(coreMock, rebalanceAuctionModuleMock.address); factory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address); rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync(); rebalancingFactory = await coreHelper.deployRebalancingSetTokenFactoryAsync( coreMock.address, rebalancingComponentWhiteList.address, ); constantAuctionPriceCurve = await rebalancingHelper.deployConstantAuctionPriceCurveAsync( DEFAULT_AUCTION_PRICE_NUMERATOR, DEFAULT_AUCTION_PRICE_DIVISOR, ); await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, factory); await coreHelper.addFactoryAsync(coreMock, rebalancingFactory); await rebalancingHelper.addPriceLibraryAsync(coreMock, constantAuctionPriceCurve); }); after(async () => { ABIDecoder.removeABI(CoreMockContract.getAbi()); ABIDecoder.removeABI(RebalanceAuctionModuleMockContract.getAbi()); ABIDecoder.removeABI(RebalancingSetCTokenBidderContract.getAbi()); }); beforeEach(async () => { await blockchain.saveSnapshotAsync(); }); afterEach(async () => { await blockchain.revertAsync(); }); describe('#constructor', async () => { let cUSDCInstance: StandardTokenMockContract; let usdcInstance: StandardTokenMockContract; let cDAIInstance: StandardTokenMockContract; let daiInstance: StandardTokenMockContract; let rebalancingSetCTokenBidder: RebalancingSetCTokenBidderContract; let dataDescription: string; before(async () => { // Set up Compound USDC token usdcInstance = await erc20Helper.deployTokenAsync( deployerAccount, 6, ); const cUSDCAddress = await compoundHelper.deployMockCUSDC(usdcInstance.address, deployerAccount); await compoundHelper.enableCToken(cUSDCAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cUSDCAddress, new BigNumber('43084603999')); await erc20Helper.approveTransferAsync( usdcInstance, cUSDCAddress, deployerAccount ); cUSDCInstance = await erc20Helper.getTokenInstanceAsync(cUSDCAddress); // Set up Compound DAI token daiInstance = await erc20Helper.deployTokenAsync( deployerAccount, 18, ); const cDAIAddress = await compoundHelper.deployMockCDAI(daiInstance.address, deployerAccount); await compoundHelper.enableCToken(cDAIAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cDAIAddress, new BigNumber('29313252165')); await erc20Helper.approveTransferAsync( daiInstance, cDAIAddress, deployerAccount ); cDAIInstance = await erc20Helper.getTokenInstanceAsync(cDAIAddress); dataDescription = 'cDAI cUSDC Bidder Contract'; rebalancingSetCTokenBidder = await rebalancingSetBidderHelper.deployRebalancingSetCTokenBidderAsync( rebalanceAuctionModuleMock.address, transferProxy.address, [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address], dataDescription, ); }); it('should contain the correct address of the rebalance auction module', async () => { const actualRebalanceAuctionModuleAddress = await rebalancingSetCTokenBidder.rebalanceAuctionModule.callAsync(); expect(actualRebalanceAuctionModuleAddress).to.equal(rebalanceAuctionModuleMock.address); }); it('should contain the correct address of the transfer proxy', async () => { const actualProxyAddress = await rebalancingSetCTokenBidder.transferProxy.callAsync(); expect(actualProxyAddress).to.equal(transferProxy.address); }); it('should contain the correct cTokens to underlying', async () => { const actualDAIAddress = await rebalancingSetCTokenBidder.cTokenToUnderlying.callAsync(cDAIInstance.address); const actualUSDCAddress = await rebalancingSetCTokenBidder.cTokenToUnderlying.callAsync(cUSDCInstance.address); expect(actualDAIAddress).to.equal(daiInstance.address); expect(actualUSDCAddress).to.equal(usdcInstance.address); }); it('should contain the correct data description', async () => { const actualDataDescription = await rebalancingSetCTokenBidder.dataDescription.callAsync(); expect(actualDataDescription).to.equal(dataDescription); }); it('should have unlimited allowance for underlying to cToken contract', async () => { const underlyingUSDCAllowance = await usdcInstance.allowance.callAsync( rebalancingSetCTokenBidder.address, cUSDCInstance.address, ); const underlyingDAIAllowance = await daiInstance.allowance.callAsync( rebalancingSetCTokenBidder.address, cDAIInstance.address, ); const expectedUnderlyingAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS; expect(underlyingUSDCAllowance).to.bignumber.equal(expectedUnderlyingAllowance); expect(underlyingDAIAllowance).to.bignumber.equal(expectedUnderlyingAllowance); }); it('should have unlimited allowance for cToken to transferProxy contract', async () => { const cUSDCAllowance = await cUSDCInstance.allowance.callAsync( rebalancingSetCTokenBidder.address, transferProxy.address, ); const cDAIAllowance = await cUSDCInstance.allowance.callAsync( rebalancingSetCTokenBidder.address, transferProxy.address, ); const expectedCTokenAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS; expect(cUSDCAllowance).to.bignumber.equal(expectedCTokenAllowance); expect(cDAIAllowance).to.bignumber.equal(expectedCTokenAllowance); }); describe('when cToken array and underlying array are not the same length', async () => { it('should revert', async () => { await expectRevertError( rebalancingSetBidderHelper.deployRebalancingSetCTokenBidderAsync( rebalanceAuctionModuleMock.address, transferProxy.address, [cUSDCInstance.address], // Missing cDAI address [usdcInstance.address, daiInstance.address], dataDescription, ) ); }); }); }); describe('#bidAndWithdraw', async () => { let cUSDCInstance: StandardTokenMockContract; let usdcInstance: StandardTokenMockContract; let cDAIInstance: StandardTokenMockContract; let daiInstance: StandardTokenMockContract; let rebalancingSetCTokenBidder: RebalancingSetCTokenBidderContract; let dataDescription: string; let badCUSDCInstance: BadCTokenMockContract; let subjectRebalancingSetToken: Address; let subjectQuantity: BigNumber; let subjectExecutePartialQuantity: boolean; let subjectCaller: Address; let proposalPeriod: BigNumber; let defaultBaseSetNaturalUnit: BigNumber; let defaultBaseSetComponent: StandardTokenMockContract; let defaultBaseSetComponent2: StandardTokenMockContract; let cTokenBaseSetNaturalUnit: BigNumber; let cTokenBaseSetComponent: StandardTokenMockContract; let cTokenBaseSetComponent2: StandardTokenMockContract; let cTokenComponentUnits: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let defaultSetToken: SetTokenContract; let cTokenSetToken: SetTokenContract; let rebalancingSetTokenQuantityToIssue: BigNumber; let minBid: BigNumber; beforeEach(async () => { // Set up Compound USDC token usdcInstance = await erc20Helper.deployTokenAsync( deployerAccount, 6, ); const cUSDCAddress = await compoundHelper.deployMockCUSDC(usdcInstance.address, deployerAccount); await compoundHelper.enableCToken(cUSDCAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cUSDCAddress, new BigNumber('43084603999')); await erc20Helper.approveTransferAsync( usdcInstance, cUSDCAddress, deployerAccount ); cUSDCInstance = badCUSDCInstance || await erc20Helper.getTokenInstanceAsync(cUSDCAddress); // Set up Compound DAI token daiInstance = await erc20Helper.deployTokenAsync( deployerAccount, 18, ); const cDAIAddress = await compoundHelper.deployMockCDAI(daiInstance.address, deployerAccount); await compoundHelper.enableCToken(cDAIAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cDAIAddress, new BigNumber('29313252165')); await erc20Helper.approveTransferAsync( daiInstance, cDAIAddress, deployerAccount ); cDAIInstance = await erc20Helper.getTokenInstanceAsync(cDAIAddress); dataDescription = 'cDAI cUSDC Bidder Contract'; rebalancingSetCTokenBidder = await rebalancingSetBidderHelper.deployRebalancingSetCTokenBidderAsync( rebalanceAuctionModuleMock.address, transferProxy.address, [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address], dataDescription, ); // ---------------------------------------------------------------------- // Create Set with no cToken component // ---------------------------------------------------------------------- // Create component tokens for default Set defaultBaseSetComponent = await erc20Helper.deployTokenAsync(deployerAccount); defaultBaseSetComponent2 = await erc20Helper.deployTokenAsync(deployerAccount); // Create the Set (default is 2 components) const defaultComponentAddresses = [ defaultBaseSetComponent.address, defaultBaseSetComponent2.address, ]; const defaultComponentUnits = [ ether(0.01), ether(0.01), ]; defaultBaseSetNaturalUnit = ether(0.001); defaultSetToken = await coreHelper.createSetTokenAsync( coreMock, factory.address, defaultComponentAddresses, defaultComponentUnits, defaultBaseSetNaturalUnit, ); // ---------------------------------------------------------------------- // Create Set with 2 cToken components // ---------------------------------------------------------------------- // Create component tokens for Set containing the target cToken cTokenBaseSetComponent = cUSDCInstance; cTokenBaseSetComponent2 = cDAIInstance; // Create the Set (default is 2 components) const nextComponentAddresses = [ cTokenBaseSetComponent.address, cTokenBaseSetComponent2.address, ]; cTokenComponentUnits = ether(0.001); const nextComponentUnits = [ cTokenComponentUnits, ether(1), ]; cTokenBaseSetNaturalUnit = ether(0.0001); cTokenSetToken = await coreHelper.createSetTokenAsync( coreMock, factory.address, nextComponentAddresses, nextComponentUnits, cTokenBaseSetNaturalUnit, ); }); async function subject(): Promise<string> { return rebalancingSetCTokenBidder.bidAndWithdraw.sendTransactionAsync( subjectRebalancingSetToken, subjectQuantity, subjectExecutePartialQuantity, { from: subjectCaller, gas: DEFAULT_GAS } ); } describe('when target cToken is an inflow in a bid', async () => { beforeEach(async () => { // Create the Rebalancing Set without cToken component proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingUnitShares = ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, defaultSetToken.address, proposalPeriod, rebalancingUnitShares ); // Approve tokens and issue defaultSetToken const baseSetIssueQuantity = ether(1); await erc20Helper.approveTransfersAsync([ defaultBaseSetComponent, defaultBaseSetComponent2, ], transferProxy.address); await coreMock.issue.sendTransactionAsync( defaultSetToken.address, baseSetIssueQuantity, {from: deployerAccount} ); // Use issued defaultSetToken to issue rebalancingSetToken await erc20Helper.approveTransfersAsync([defaultSetToken], transferProxy.address); rebalancingSetTokenQuantityToIssue = baseSetIssueQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue); // Determine minimum bid const decOne = await defaultSetToken.naturalUnit.callAsync(); const decTwo = await cTokenSetToken.naturalUnit.callAsync(); minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000); subjectCaller = deployerAccount; subjectQuantity = minBid; subjectRebalancingSetToken = rebalancingSetToken.address; subjectExecutePartialQuantity = false; // Transition to rebalance await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, cTokenSetToken, constantAuctionPriceCurve.address, managerAccount ); // Approve underlying tokens to rebalancingSetCTokenBidder contract await erc20Helper.approveTransfersAsync([ usdcInstance, daiInstance, ], rebalancingSetCTokenBidder.address); }); it("transfers the correct amount of tokens to the bidder's wallet", async () => { const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); // Get current exchange rate const cUSDCExchangeRate = await compoundHelper.getExchangeRateCurrent(cUSDCInstance.address); const cDAIExchangeRate = await compoundHelper.getExchangeRateCurrent(cDAIInstance.address); // Replace expected token flow arrays with cToken underlying const expectedTokenFlowsUnderlying = rebalancingSetBidderHelper.replaceFlowsWithCTokenUnderlyingAsync( expectedTokenFlows, combinedTokenArray, [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address], [cUSDCExchangeRate, cDAIExchangeRate], ); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverTokenBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const oldUnderlyingTokenBalances = await erc20Helper.getTokenBalances( [usdcInstance, daiInstance], subjectCaller ); // Replace cToken balance with underlying token balance const oldReceiverTokenUnderlyingBalances = _.map(oldReceiverTokenBalances, (balance, index) => { if (combinedTokenArray[index] === cUSDCInstance.address) { return oldUnderlyingTokenBalances[0]; } else if (combinedTokenArray[index] === cDAIInstance.address) { return oldUnderlyingTokenBalances[1]; } else { return balance; } }); await subject(); const newReceiverTokenBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const newUnderlyingTokenBalances = await erc20Helper.getTokenBalances( [usdcInstance, daiInstance], subjectCaller ); // Replace cToken balance with underlying token balance const newReceiverTokenUnderlyingBalances = _.map(newReceiverTokenBalances, (balance, index) => { if (combinedTokenArray[index] === cUSDCInstance.address) { return newUnderlyingTokenBalances[0]; } else if (combinedTokenArray[index] === cDAIInstance.address) { return newUnderlyingTokenBalances[1]; } else { return balance; } }); const expectedReceiverBalances = _.map(oldReceiverTokenUnderlyingBalances, (balance, index) => balance .add(expectedTokenFlowsUnderlying['outflowArray'][index]) .sub(expectedTokenFlowsUnderlying['inflowArray'][index]) ); expect(JSON.stringify(newReceiverTokenUnderlyingBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => { const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); await subject(); const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) => balance.add(expectedTokenFlows['inflowArray'][index]).sub(expectedTokenFlows['outflowArray'][index]) ); expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances)); }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); it('emits a BidPlacedCToken event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = BidPlacedCToken( rebalancingSetToken.address, subjectCaller, subjectQuantity, rebalancingSetCTokenBidder.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('but quantity is zero', async () => { beforeEach(async () => { subjectQuantity = ZERO; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('but quantity is more than remainingCurrentSets', async () => { beforeEach(async () => { subjectQuantity = rebalancingSetTokenQuantityToIssue.add(minBid); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('partial fills is true but amount is less than remainingCurrentSets', async () => { beforeEach(async () => { subjectExecutePartialQuantity = true; }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); describe('but quantity is zero', async () => { beforeEach(async () => { subjectQuantity = ZERO; }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('and quantity is greater than remainingCurrentSets', async () => { const roundedQuantity = ether(1); beforeEach(async () => { subjectQuantity = ether(2); subjectExecutePartialQuantity = true; }); it("transfers the correct amount of tokens to the bidder's wallet", async () => { const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const cUSDCExchangeRate = await compoundHelper.getExchangeRateCurrent(cUSDCInstance.address); const cDAIExchangeRate = await compoundHelper.getExchangeRateCurrent(cDAIInstance.address); // Replace expected token flow arrays with cToken underlying const expectedTokenFlowsUnderlying = rebalancingSetBidderHelper.replaceFlowsWithCTokenUnderlyingAsync( expectedTokenFlows, combinedTokenArray, [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address], [cUSDCExchangeRate, cDAIExchangeRate], ); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverTokenBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const oldUnderlyingTokenBalances = await erc20Helper.getTokenBalances( [usdcInstance, daiInstance], subjectCaller ); // Replace cToken balance with underlying token balance const oldReceiverTokenUnderlyingBalances = _.map(oldReceiverTokenBalances, (balance, index) => { if (combinedTokenArray[index] === cUSDCInstance.address) { return oldUnderlyingTokenBalances[0]; } else if (combinedTokenArray[index] === cDAIInstance.address) { return oldUnderlyingTokenBalances[1]; } else { return balance; } }); await subject(); const newReceiverTokenBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const newUnderlyingTokenBalances = await erc20Helper.getTokenBalances( [usdcInstance, daiInstance], subjectCaller ); // Replace cToken balance with underlying token balance const newReceiverTokenUnderlyingBalances = _.map(newReceiverTokenBalances, (balance, index) => { if (combinedTokenArray[index] === cUSDCInstance.address) { return newUnderlyingTokenBalances[0]; } else if (combinedTokenArray[index] === cDAIInstance.address) { return newUnderlyingTokenBalances[1]; } else { return balance; } }); const expectedReceiverBalances = _.map(oldReceiverTokenUnderlyingBalances, (balance, index) => balance .add(expectedTokenFlowsUnderlying['outflowArray'][index]) .sub(expectedTokenFlowsUnderlying['inflowArray'][index]) ); expect(JSON.stringify(newReceiverTokenUnderlyingBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => { const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); await subject(); const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) => balance.add(expectedTokenFlows['inflowArray'][index]).sub(expectedTokenFlows['outflowArray'][index]) ); expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances)); }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(roundedQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); it('emits a BidPlacedCToken event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = BidPlacedCToken( rebalancingSetToken.address, subjectCaller, subjectQuantity, rebalancingSetCTokenBidder.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); }); describe('but quantity is not multiple of natural unit', async () => { beforeEach(async () => { subjectQuantity = minBid.add(1); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when minting a cToken is returning a nonzero response', async () => { before(async () => { badCUSDCInstance = await compoundHelper.deployCTokenWithInvalidMintAndRedeemAsync(deployerAccount); }); after(async () => { badCUSDCInstance = undefined; }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('when target cToken is an outflow in a bid', async () => { beforeEach(async () => { // Create the Rebalancing Set with the cToken component proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingUnitShares = ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, cTokenSetToken.address, proposalPeriod, rebalancingUnitShares ); // Approve tokens, mint cToken and issue cTokenSetToken const baseSetIssueQuantity = ether(1); await erc20Helper.approveTransfersAsync([usdcInstance], cTokenBaseSetComponent.address); await erc20Helper.approveTransfersAsync([daiInstance], cTokenBaseSetComponent2.address); await compoundHelper.mintCToken( cTokenBaseSetComponent.address, new BigNumber(10 ** 18) ); await compoundHelper.mintCToken( cTokenBaseSetComponent2.address, new BigNumber(10 ** 22) ); await erc20Helper.approveTransfersAsync( [cTokenBaseSetComponent, cTokenBaseSetComponent2], transferProxy.address ); await coreMock.issue.sendTransactionAsync( cTokenSetToken.address, baseSetIssueQuantity, {from: deployerAccount} ); // Use issued cTokenSetToken to issue rebalancingSetToken await erc20Helper.approveTransfersAsync([cTokenSetToken], transferProxy.address); rebalancingSetTokenQuantityToIssue = baseSetIssueQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue); // Determine minimum bid const decOne = await defaultSetToken.naturalUnit.callAsync(); const decTwo = await cTokenSetToken.naturalUnit.callAsync(); minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000); subjectCaller = deployerAccount; subjectQuantity = minBid; subjectRebalancingSetToken = rebalancingSetToken.address; subjectExecutePartialQuantity = false; // Transition to rebalance await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, defaultSetToken, constantAuctionPriceCurve.address, managerAccount ); // Approve tokens to rebalancingSetCTokenBidder contract await erc20Helper.approveTransfersAsync([ defaultBaseSetComponent, defaultBaseSetComponent2, ], rebalancingSetCTokenBidder.address); }); it("transfers the correct amount of tokens to the bidder's wallet", async () => { const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const cUSDCExchangeRate = await compoundHelper.getExchangeRateCurrent(cUSDCInstance.address); const cDAIExchangeRate = await compoundHelper.getExchangeRateCurrent(cDAIInstance.address); // Replace expected token flow arrays with cToken underlying const expectedTokenFlowsUnderlying = rebalancingSetBidderHelper.replaceFlowsWithCTokenUnderlyingAsync( expectedTokenFlows, combinedTokenArray, [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address], [cUSDCExchangeRate, cDAIExchangeRate], ); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverTokenBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const oldUnderlyingTokenBalances = await erc20Helper.getTokenBalances( [usdcInstance, daiInstance], subjectCaller ); // Replace cToken balance with underlying token balance const oldReceiverTokenUnderlyingBalances = _.map(oldReceiverTokenBalances, (balance, index) => { if (combinedTokenArray[index] === cUSDCInstance.address) { return oldUnderlyingTokenBalances[0]; } else if (combinedTokenArray[index] === cDAIInstance.address) { return oldUnderlyingTokenBalances[1]; } else { return balance; } }); await subject(); const newReceiverTokenBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const newUnderlyingTokenBalances = await erc20Helper.getTokenBalances( [usdcInstance, daiInstance], subjectCaller ); // Replace cToken balance with underlying token balance const newReceiverTokenUnderlyingBalances = _.map(newReceiverTokenBalances, (balance, index) => { if (combinedTokenArray[index] === cUSDCInstance.address) { return newUnderlyingTokenBalances[0]; } else if (combinedTokenArray[index] === cDAIInstance.address) { return newUnderlyingTokenBalances[1]; } else { return balance; } }); const expectedReceiverBalances = _.map(oldReceiverTokenUnderlyingBalances, (balance, index) => balance .add(expectedTokenFlowsUnderlying['outflowArray'][index]) .sub(expectedTokenFlowsUnderlying['inflowArray'][index]) ); expect(JSON.stringify(newReceiverTokenUnderlyingBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); describe('when redeeming a cToken is returning a nonzero response', async () => { before(async () => { badCUSDCInstance = await compoundHelper.deployCTokenWithInvalidMintAndRedeemAsync(deployerAccount); }); after(async () => { badCUSDCInstance = undefined; }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('when cTokens are neither inflow nor outflow in a bid', async () => { beforeEach(async () => { // Create the Rebalancing Set with the default component proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingUnitShares = ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, defaultSetToken.address, proposalPeriod, rebalancingUnitShares ); // Approve tokens and issue defaultSetToken const baseSetIssueQuantity = ether(1); await erc20Helper.approveTransfersAsync([ defaultBaseSetComponent, defaultBaseSetComponent2, ], transferProxy.address); await coreMock.issue.sendTransactionAsync( defaultSetToken.address, baseSetIssueQuantity, {from: deployerAccount} ); // Use issued defaultSetToken to issue rebalancingSetToken await erc20Helper.approveTransfersAsync([defaultSetToken], transferProxy.address); rebalancingSetTokenQuantityToIssue = baseSetIssueQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue); // Determine minimum bid const decOne = await defaultSetToken.naturalUnit.callAsync(); const decTwo = await cTokenSetToken.naturalUnit.callAsync(); minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000); subjectCaller = deployerAccount; subjectQuantity = minBid; subjectRebalancingSetToken = rebalancingSetToken.address; subjectExecutePartialQuantity = false; // Create new next Set with no cToken component const defaultNextBaseSetComponent = await erc20Helper.deployTokenAsync(deployerAccount); const defaultNextBaseSetComponent2 = await erc20Helper.deployTokenAsync(deployerAccount); const defaultNextComponentAddresses = [ defaultNextBaseSetComponent.address, defaultNextBaseSetComponent2.address, ]; const defaultNextComponentUnits = [ ether(0.01), ether(0.01), ]; const defaultBaseSetNaturalUnit = ether(0.001); const defaultNextSetToken = await coreHelper.createSetTokenAsync( coreMock, factory.address, defaultNextComponentAddresses, defaultNextComponentUnits, defaultBaseSetNaturalUnit, ); // Transition to rebalance await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, defaultNextSetToken, constantAuctionPriceCurve.address, managerAccount ); // Approve tokens to rebalancingSetCTokenBidder contract await erc20Helper.approveTransfersAsync([ defaultNextBaseSetComponent, defaultNextBaseSetComponent2, ], rebalancingSetCTokenBidder.address); }); it("transfers the correct amount of tokens to the bidder's wallet", async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); await subject(); const newReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const expectedReceiverBalances = _.map(oldReceiverBalances, (balance, index) => balance.add(expectedTokenFlow['outflowArray'][index]).sub(expectedTokenFlow['inflowArray'][index]) ); expect(JSON.stringify(newReceiverBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); }); }); describe('#bidAndWithdrawTWAP', async () => { const setup: RebalanceTestSetup = new RebalanceTestSetup(deployerAccount); let rebalancingSetToken: RebalancingSetTokenV3Contract; let rebalancingSetCTokenBidder: RebalancingSetCTokenBidderContract; let liquidator: TWAPLiquidatorContract; const scenario: any = { name: 'ETH 20 MA Set Rebalances 100% WETH to 100% USD', rebalancingSet: { unitShares: new BigNumber(2076796), naturalUnit: new BigNumber(1000000), supply: new BigNumber('20556237207015075000000'), }, currentSet: { components: ['component1'], // ETH units: [new BigNumber(1000000)], naturalUnit: new BigNumber(1000000), }, nextSet: { components: ['component2'], // USDC units: [new BigNumber(307)], naturalUnit: new BigNumber(1000000000000), }, components: { component1Price: ether(188), component2Price: ether(1), component1Decimals: 18, component2Decimals: 6, }, auction: { chunkSize: ether(2000000), chunkAuctionPeriod: new BigNumber(3600), // 1 hour }, }; const name: string = 'liquidator'; const auctionPeriod: BigNumber = ONE_HOUR_IN_SECONDS.mul(4); const rangeStart: BigNumber = ether(.01); const rangeEnd: BigNumber = ether(.21); let subjectRebalancingSetToken: Address; let subjectQuantity: BigNumber; let subjectLastChunkTimestamp: BigNumber; let subjectExecutePartialQuantity: boolean; let subjectCaller: Address; beforeEach(async () => { await setup.initializeCore(); await setup.initializeComponents(scenario.components); await setup.initializeBaseSets({ set1Components: _.map(scenario.currentSet.components, component => setup[component].address), set2Components: _.map(scenario.nextSet.components, component => setup[component].address), set1Units: scenario.currentSet.units, set2Units: scenario.nextSet.units, set1NaturalUnit: scenario.currentSet.naturalUnit, set2NaturalUnit: scenario.nextSet.naturalUnit, }); const assetPairVolumeBounds = [ { assetOne: setup.component1.address, assetTwo: setup.component2.address, bounds: {lower: ether(10 ** 4), upper: ether(10 ** 7)}, }, { assetOne: setup.component2.address, assetTwo: setup.component3.address, bounds: {lower: ZERO, upper: ether(10 ** 6)}, }, ]; liquidator = await liquidatorHelper.deployTWAPLiquidatorAsync( setup.core.address, setup.oracleWhiteList.address, auctionPeriod, rangeStart, rangeEnd, assetPairVolumeBounds, name, ); await coreHelper.addAddressToWhiteList(liquidator.address, setup.liquidatorWhitelist); const failPeriod = ONE_DAY_IN_SECONDS; const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest'); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV3Async( setup.core, setup.rebalancingFactory.address, managerAccount, liquidator.address, feeRecipient, setup.fixedFeeCalculator.address, setup.set1.address, failPeriod, lastRebalanceTimestamp, ZERO, // entry fee ZERO, // rebalance fee scenario.rebalancingSet.unitShares ); await setup.setRebalancingSet(rebalancingSetToken); await setup.mintRebalancingSets(scenario.rebalancingSet.supply); const { chunkSize, chunkAuctionPeriod } = scenario.auction; const liquidatorData = liquidatorHelper.generateTWAPLiquidatorCalldata(chunkSize, chunkAuctionPeriod); await rebalancingHelper.transitionToRebalanceV2Async( setup.core, setup.rebalancingComponentWhiteList, setup.rebalancingSetToken, setup.set2, managerAccount, liquidatorData, ); const dataDescription = 'TWAP CToken Bidder Contract'; rebalancingSetCTokenBidder = await rebalancingSetBidderHelper.deployRebalancingSetCTokenBidderAsync( setup.rebalanceAuctionModule.address, setup.transferProxy.address, [], [], dataDescription, ); await setup.approveComponentsToAddress(rebalancingSetCTokenBidder.address); const remainingBids = await liquidator.remainingCurrentSets.callAsync(setup.rebalancingSetToken.address); subjectRebalancingSetToken = rebalancingSetToken.address; subjectQuantity = remainingBids; subjectLastChunkTimestamp = ZERO; subjectExecutePartialQuantity = false; subjectCaller = deployerAccount; }); async function subject(): Promise<string> { return rebalancingSetCTokenBidder.bidAndWithdrawTWAP.sendTransactionAsync( subjectRebalancingSetToken, subjectQuantity, subjectLastChunkTimestamp, subjectExecutePartialQuantity, { from: subjectCaller, gas: DEFAULT_GAS } ); } describe('when auction is in first chunk and last chunk timestamp is the same', async () => { it("transfers the correct amount of tokens to the bidder's wallet", async () => { const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); await subject(); const auction = await liquidator.auctions.callAsync(subjectRebalancingSetToken); const chunkAuction = auction[0]; const linearAuction = getLinearAuction(chunkAuction); const { timestamp } = await web3.eth.getBlock('latest'); const currentPrice = await liquidatorHelper.calculateCurrentPrice( linearAuction, new BigNumber(timestamp), auctionPeriod, ); const expectedTokenFlow = liquidatorHelper.constructTokenFlow( linearAuction, subjectQuantity, currentPrice, ); const newReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const expectedReceiverBalances = _.map(oldReceiverBalances, (balance, index) => balance.add(expectedTokenFlow['outflow'][index]).sub(expectedTokenFlow['inflow'][index]) ); expect(JSON.stringify(newReceiverBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); }); describe('when auction is iterated to the next chunk', async () => { // Bids and iterates to the next auction beforeEach(async () => { const timeToFV = ONE_HOUR_IN_SECONDS.div(6); await blockchain.increaseTimeAsync(timeToFV); await blockchain.mineBlockAsync(); // Bid the entire quantity const remainingBids = await liquidator.remainingCurrentSets.callAsync(setup.rebalancingSetToken.address); await rebalancingHelper.bidAndWithdrawAsync( setup.rebalanceAuctionModule, setup.rebalancingSetToken.address, remainingBids, ); await blockchain.increaseTimeAsync(scenario.auction.chunkAuctionPeriod); await liquidator.iterateChunkAuction.sendTransactionAsync( setup.rebalancingSetToken.address, { from: deployerAccount, gas: DEFAULT_GAS } ); }); describe('when timestamp is the same', async () => { beforeEach(async () => { const timestamp = await liquidator.getLastChunkAuctionEnd.callAsync(rebalancingSetToken.address); subjectLastChunkTimestamp = timestamp; }); it("transfers the correct amount of tokens to the bidder's wallet", async () => { const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); await subject(); const auction = await liquidator.auctions.callAsync(subjectRebalancingSetToken); const chunkAuction = auction[0]; const linearAuction = getLinearAuction(chunkAuction); const { timestamp } = await web3.eth.getBlock('latest'); const currentPrice = await liquidatorHelper.calculateCurrentPrice( linearAuction, new BigNumber(timestamp), auctionPeriod, ); const expectedTokenFlow = liquidatorHelper.constructTokenFlow( linearAuction, subjectQuantity, currentPrice, ); const newReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const expectedReceiverBalances = _.map(oldReceiverBalances, (balance, index) => balance.add(expectedTokenFlow['outflow'][index]).sub(expectedTokenFlow['inflow'][index]) ); expect(JSON.stringify(newReceiverBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); }); describe('when timestamp is different', async () => { it('should revert', async () => { await expectRevertError(subject()); }); }); }); }); describe('#getAddressAndBidPriceArray', async () => { let cUSDCInstance: StandardTokenMockContract; let usdcInstance: StandardTokenMockContract; let cDAIInstance: StandardTokenMockContract; let daiInstance: StandardTokenMockContract; let rebalancingSetCTokenBidder: RebalancingSetCTokenBidderContract; let dataDescription: string; let subjectRebalancingSetToken: Address; let subjectQuantity: BigNumber; let proposalPeriod: BigNumber; let defaultBaseSetNaturalUnit: BigNumber; let defaultBaseSetComponent: StandardTokenMockContract; let defaultBaseSetComponent2: StandardTokenMockContract; let cTokenBaseSetNaturalUnit: BigNumber; let cTokenBaseSetComponent: StandardTokenMockContract; let cTokenBaseSetComponent2: StandardTokenMockContract; let cTokenComponentUnits: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let defaultSetToken: SetTokenContract; let cTokenSetToken: SetTokenContract; let rebalancingSetTokenQuantityToIssue: BigNumber; let minBid: BigNumber; beforeEach(async () => { // Set up Compound USDC token usdcInstance = await erc20Helper.deployTokenAsync( deployerAccount, 6, ); const cUSDCAddress = await compoundHelper.deployMockCUSDC(usdcInstance.address, deployerAccount); await compoundHelper.enableCToken(cUSDCAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cUSDCAddress, new BigNumber('43084603999')); await erc20Helper.approveTransferAsync( usdcInstance, cUSDCAddress, deployerAccount ); cUSDCInstance = await erc20Helper.getTokenInstanceAsync(cUSDCAddress); // Set up Compound DAI token daiInstance = await erc20Helper.deployTokenAsync( deployerAccount, 18, ); const cDAIAddress = await compoundHelper.deployMockCDAI(daiInstance.address, deployerAccount); await compoundHelper.enableCToken(cDAIAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cDAIAddress, new BigNumber('29313252165')); await erc20Helper.approveTransferAsync( daiInstance, cDAIAddress, deployerAccount ); cDAIInstance = await erc20Helper.getTokenInstanceAsync(cDAIAddress); dataDescription = 'cDAI cUSDC Bidder Contract'; rebalancingSetCTokenBidder = await rebalancingSetBidderHelper.deployRebalancingSetCTokenBidderAsync( rebalanceAuctionModuleMock.address, transferProxy.address, [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address], dataDescription, ); // ---------------------------------------------------------------------- // Create Set with no cToken component // ---------------------------------------------------------------------- // Create component tokens for default Set defaultBaseSetComponent = await erc20Helper.deployTokenAsync(deployerAccount); defaultBaseSetComponent2 = await erc20Helper.deployTokenAsync(deployerAccount); // Create the Set (default is 2 components) const defaultComponentAddresses = [ defaultBaseSetComponent.address, defaultBaseSetComponent2.address, ]; const defaultComponentUnits = [ ether(0.01), ether(0.01), ]; defaultBaseSetNaturalUnit = ether(0.001); defaultSetToken = await coreHelper.createSetTokenAsync( coreMock, factory.address, defaultComponentAddresses, defaultComponentUnits, defaultBaseSetNaturalUnit, ); // ---------------------------------------------------------------------- // Create Set with 2 cToken components // ---------------------------------------------------------------------- // Create component tokens for Set containing the target cToken cTokenBaseSetComponent = cUSDCInstance; cTokenBaseSetComponent2 = cDAIInstance; // Create the Set (default is 2 components) const nextComponentAddresses = [ cTokenBaseSetComponent.address, cTokenBaseSetComponent2.address, ]; cTokenComponentUnits = ether(0.001); const nextComponentUnits = [ cTokenComponentUnits, ether(1), ]; cTokenBaseSetNaturalUnit = ether(0.0001); cTokenSetToken = await coreHelper.createSetTokenAsync( coreMock, factory.address, nextComponentAddresses, nextComponentUnits, cTokenBaseSetNaturalUnit, ); // Create the Rebalancing Set without cToken component proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingUnitShares = ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, defaultSetToken.address, proposalPeriod, rebalancingUnitShares ); // Approve tokens and issue defaultSetToken const baseSetIssueQuantity = ether(1); await erc20Helper.approveTransfersAsync([ defaultBaseSetComponent, defaultBaseSetComponent2, ], transferProxy.address); await coreMock.issue.sendTransactionAsync( defaultSetToken.address, baseSetIssueQuantity, {from: deployerAccount} ); // Use issued defaultSetToken to issue rebalancingSetToken await erc20Helper.approveTransfersAsync([defaultSetToken], transferProxy.address); rebalancingSetTokenQuantityToIssue = baseSetIssueQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue); // Determine minimum bid const decOne = await defaultSetToken.naturalUnit.callAsync(); const decTwo = await cTokenSetToken.naturalUnit.callAsync(); minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000); subjectQuantity = minBid; subjectRebalancingSetToken = rebalancingSetToken.address; // Transition to rebalance await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, cTokenSetToken, constantAuctionPriceCurve.address, managerAccount ); }); async function subject(): Promise<any> { return rebalancingSetCTokenBidder.getAddressAndBidPriceArray.callAsync( subjectRebalancingSetToken, subjectQuantity, ); } it('should return the correct inflow, outflow and address arrays', async () => { const [ actualAddressArray, actualInflowUnitArray, actualOutflowUnitArray, ] = await subject(); const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const expectedCombinedTokenArray = _.map(combinedTokenArray, token => { if (token === cUSDCInstance.address) { return usdcInstance.address; } else if (token === cDAIInstance.address) { return daiInstance.address; } else { return token; } }); // Get exchange rate stored const cUSDCExchangeRate = await compoundHelper.getExchangeRate(cUSDCInstance.address); const cDAIExchangeRate = await compoundHelper.getExchangeRate(cDAIInstance.address); // Replace expected token flow arrays with cToken underlying const expectedTokenFlowsUnderlying = rebalancingSetBidderHelper.replaceFlowsWithCTokenUnderlyingAsync( expectedTokenFlows, combinedTokenArray, [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address], [cUSDCExchangeRate, cDAIExchangeRate], ); expect( JSON.stringify(actualInflowUnitArray) ).to.equal( JSON.stringify(expectedTokenFlowsUnderlying['inflowArray']) ); expect( JSON.stringify(actualOutflowUnitArray) ).to.equal( JSON.stringify(expectedTokenFlowsUnderlying['outflowArray']) ); expect( JSON.stringify(actualAddressArray) ).to.equal( JSON.stringify(expectedCombinedTokenArray) ); }); }); });
the_stack
import { MarshallingContext } from "../../MarshallingContext"; import { JavaArrayList, JavaBigDecimal, JavaBigInteger, JavaBoolean, JavaByte, JavaDate, JavaDouble, JavaFloat, JavaHashMap, JavaHashSet, JavaInteger, JavaLong, JavaOptional, JavaShort, JavaString } from "../../../java-wrappers"; import { ErraiObjectConstants } from "../../model/ErraiObjectConstants"; import { MarshallerProvider } from "../../MarshallerProvider"; import { Portable } from "../../Portable"; import { JavaOptionalMarshaller } from "../JavaOptionalMarshaller"; import { NumValBasedErraiObject } from "../../model/NumValBasedErraiObject"; import { ValueBasedErraiObject } from "../../model/ValueBasedErraiObject"; import { NumberUtils } from "../../../util/NumberUtils"; import { UnmarshallingContext } from "../../UnmarshallingContext"; import { JavaType } from "../../../java-wrappers/JavaType"; describe("marshall", () => { const encodedType = ErraiObjectConstants.ENCODED_TYPE; const objectId = ErraiObjectConstants.OBJECT_ID; const value = ErraiObjectConstants.VALUE; let context: MarshallingContext; beforeEach(() => { MarshallerProvider.initialize(); context = new MarshallingContext(); }); test("with empty optional, should serialize normally", () => { const input = new JavaOptional<string>(undefined); const output = new JavaOptionalMarshaller().marshall(input, context); expect(output).toStrictEqual(new ValueBasedErraiObject(JavaType.OPTIONAL, null).asErraiObject()); }); test("with JavaNumber optional, should wrap element into an errai object", () => { const input = new JavaOptional<JavaInteger>(new JavaInteger("1")); const output = new JavaOptionalMarshaller().marshall(input, context); expect(output).toStrictEqual( new ValueBasedErraiObject( JavaType.OPTIONAL, new NumValBasedErraiObject(JavaType.INTEGER, 1).asErraiObject() ).asErraiObject() ); }); test("with JavaBoolean optional, should wrap element into an errai object", () => { const input = new JavaOptional<JavaBoolean>(new JavaBoolean(false)); const output = new JavaOptionalMarshaller().marshall(input, context); expect(output).toStrictEqual( new ValueBasedErraiObject( JavaType.OPTIONAL, new NumValBasedErraiObject(JavaType.BOOLEAN, false).asErraiObject() ).asErraiObject() ); }); test("with JavaBigNumber optional, should serialize element normally", () => { const input = new JavaOptional<JavaBigInteger>(new JavaBigInteger("1")); const output = new JavaOptionalMarshaller().marshall(input, context); expect(output).toStrictEqual({ [encodedType]: JavaType.OPTIONAL, [objectId]: "-1", [value]: { [encodedType]: JavaType.BIG_INTEGER, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "1" } }); }); test("with custom object optional, should serialize element normally", () => { const input = new JavaOptional<MyPortable>(new MyPortable({ foo: "foo1", bar: "bar1" })); const output = new JavaOptionalMarshaller().marshall(input, context); expect(output).toStrictEqual({ [encodedType]: JavaType.OPTIONAL, [objectId]: "-1", [value]: { [encodedType]: "com.portable.my", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "foo1", bar: "bar1" } }); }); test("root null object, should serialize to null", () => { const input = null as any; const output = new JavaOptionalMarshaller().marshall(input, context); expect(output).toBeNull(); }); test("root undefined object, should serialize to null", () => { const input = undefined as any; const output = new JavaOptionalMarshaller().marshall(input, context); expect(output).toBeNull(); }); }); describe("unmarshall", () => { beforeEach(() => { MarshallerProvider.initialize(); }); test("with empty optional, should return an empty optional", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<string>(undefined); const marshalledInput = marshaller.marshall(input, new MarshallingContext()); const output = marshaller.unmarshall(marshalledInput!, new UnmarshallingContext(new Map())); expect(output).toEqual(input); }); test("with Array input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const arrayInput = new JavaOptional<string[]>(["str1", "str2"]); const arrayListInput = new JavaOptional<JavaArrayList<string>>(new JavaArrayList(["str1", "str2"])); [arrayInput, arrayListInput].forEach(input => { const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional(["str1", "str2"])); }); }); test("with Set input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const setInput = new JavaOptional<Set<string>>(new Set(["str1", "str2"])); const hashSetInput = new JavaOptional<JavaHashSet<string>>(new JavaHashSet(new Set(["str1", "str2"]))); [setInput, hashSetInput].forEach(input => { const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional(new Set(["str1", "str2"]))); }); }); test("with Map input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const mapInput = new JavaOptional<Map<string, string>>(new Map([["str1", "str2"]])); const hashMapInput = new JavaOptional<JavaHashMap<string, string>>(new JavaHashMap(new Map([["str1", "str2"]]))); [mapInput, hashMapInput].forEach(input => { const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional(new Map([["str1", "str2"]]))); }); }); test("with Date input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const baseDate = new Date(); const dateInput = new JavaOptional<Date>(new Date(baseDate)); const javaDateInput = new JavaOptional<JavaDate>(new JavaDate(baseDate)); [dateInput, javaDateInput].forEach(input => { const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<Date>(new Date(baseDate))); }); }); test("with Boolean input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const booleanInput = new JavaOptional<boolean>(false); const javaBooleanInput = new JavaOptional<JavaBoolean>(new JavaBoolean(false)); [booleanInput, javaBooleanInput].forEach(input => { const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<boolean>(false)); }); }); test("with String input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const stringInput = new JavaOptional<string>("foo"); const javaStringInput = new JavaOptional<JavaString>(new JavaString("foo")); [stringInput, javaStringInput].forEach(input => { const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<string>("foo")); }); }); test("with JavaOptional input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional(new JavaOptional<string>("foo")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional(new JavaOptional<string>("foo"))); }); test("with JavaBigDecimal input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaBigDecimal>(new JavaBigDecimal("1.1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaBigDecimal>(new JavaBigDecimal("1.1"))); }); test("with JavaBigInteger should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaBigInteger>(new JavaBigInteger("1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaBigInteger>(new JavaBigInteger("1"))); }); test("with JavaLong input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaLong>(new JavaLong("1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaLong>(new JavaLong("1"))); }); test("with JavaByte input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaByte>(new JavaByte("1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaByte>(new JavaByte("1"))); }); test("with JavaDouble input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaDouble>(new JavaDouble("1.1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaDouble>(new JavaDouble("1.1"))); }); test("with JavaFloat input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaFloat>(new JavaFloat("1.1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaFloat>(new JavaFloat("1.1"))); }); test("with JavaInteger input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaInteger>(new JavaInteger("1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaInteger>(new JavaInteger("1"))); }); test("with JavaShort input, should unmarshall correctly", () => { const marshaller = new JavaOptionalMarshaller(); const input = new JavaOptional<JavaShort>(new JavaShort("1")); const marshalledInput = marshaller.notNullMarshall(input, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional<JavaShort>(new JavaShort("1"))); }); test("with custom object optional, should unmarshall correctly", () => { const oracle = new Map([["com.portable.my", () => new MyPortable({} as any)]]); const marshaller = new JavaOptionalMarshaller(); const pojoInput = new MyPortable({ foo: "foo1", bar: "bar1" }); const optionalInput = new JavaOptional<MyPortable>(pojoInput); const marshalledInput = marshaller.notNullMarshall(optionalInput, new MarshallingContext()); const output = marshaller.notNullUnmarshall(marshalledInput, new UnmarshallingContext(oracle)); expect(output).toEqual(new JavaOptional<MyPortable>(pojoInput)); }); test("with root null object, should unmarshall to null", () => { const input = null as any; const output = new JavaOptionalMarshaller().unmarshall(input, new UnmarshallingContext(new Map())); expect(output).toBeUndefined(); }); test("with root undefined object, should unmarshall to undefined", () => { const input = undefined as any; const output = new JavaOptionalMarshaller().unmarshall(input, new UnmarshallingContext(new Map())); expect(output).toBeUndefined(); }); }); class MyPortable implements Portable<MyPortable> { private readonly _fqcn = "com.portable.my"; public readonly foo: string; public readonly bar: string; constructor(self: { foo: string; bar: string }) { Object.assign(this, self); } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class HealthLake extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: HealthLake.Types.ClientConfiguration) config: Config & HealthLake.Types.ClientConfiguration; /** * Creates a Data Store that can ingest and export FHIR formatted data. */ createFHIRDatastore(params: HealthLake.Types.CreateFHIRDatastoreRequest, callback?: (err: AWSError, data: HealthLake.Types.CreateFHIRDatastoreResponse) => void): Request<HealthLake.Types.CreateFHIRDatastoreResponse, AWSError>; /** * Creates a Data Store that can ingest and export FHIR formatted data. */ createFHIRDatastore(callback?: (err: AWSError, data: HealthLake.Types.CreateFHIRDatastoreResponse) => void): Request<HealthLake.Types.CreateFHIRDatastoreResponse, AWSError>; /** * Deletes a Data Store. */ deleteFHIRDatastore(params: HealthLake.Types.DeleteFHIRDatastoreRequest, callback?: (err: AWSError, data: HealthLake.Types.DeleteFHIRDatastoreResponse) => void): Request<HealthLake.Types.DeleteFHIRDatastoreResponse, AWSError>; /** * Deletes a Data Store. */ deleteFHIRDatastore(callback?: (err: AWSError, data: HealthLake.Types.DeleteFHIRDatastoreResponse) => void): Request<HealthLake.Types.DeleteFHIRDatastoreResponse, AWSError>; /** * Gets the properties associated with the FHIR Data Store, including the Data Store ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type version, and Data Store endpoint. */ describeFHIRDatastore(params: HealthLake.Types.DescribeFHIRDatastoreRequest, callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRDatastoreResponse) => void): Request<HealthLake.Types.DescribeFHIRDatastoreResponse, AWSError>; /** * Gets the properties associated with the FHIR Data Store, including the Data Store ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type version, and Data Store endpoint. */ describeFHIRDatastore(callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRDatastoreResponse) => void): Request<HealthLake.Types.DescribeFHIRDatastoreResponse, AWSError>; /** * Displays the properties of a FHIR export job, including the ID, ARN, name, and the status of the job. */ describeFHIRExportJob(params: HealthLake.Types.DescribeFHIRExportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRExportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRExportJobResponse, AWSError>; /** * Displays the properties of a FHIR export job, including the ID, ARN, name, and the status of the job. */ describeFHIRExportJob(callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRExportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRExportJobResponse, AWSError>; /** * Displays the properties of a FHIR import job, including the ID, ARN, name, and the status of the job. */ describeFHIRImportJob(params: HealthLake.Types.DescribeFHIRImportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRImportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRImportJobResponse, AWSError>; /** * Displays the properties of a FHIR import job, including the ID, ARN, name, and the status of the job. */ describeFHIRImportJob(callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRImportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRImportJobResponse, AWSError>; /** * Lists all FHIR Data Stores that are in the user’s account, regardless of Data Store status. */ listFHIRDatastores(params: HealthLake.Types.ListFHIRDatastoresRequest, callback?: (err: AWSError, data: HealthLake.Types.ListFHIRDatastoresResponse) => void): Request<HealthLake.Types.ListFHIRDatastoresResponse, AWSError>; /** * Lists all FHIR Data Stores that are in the user’s account, regardless of Data Store status. */ listFHIRDatastores(callback?: (err: AWSError, data: HealthLake.Types.ListFHIRDatastoresResponse) => void): Request<HealthLake.Types.ListFHIRDatastoresResponse, AWSError>; /** * Lists all FHIR export jobs associated with an account and their statuses. */ listFHIRExportJobs(params: HealthLake.Types.ListFHIRExportJobsRequest, callback?: (err: AWSError, data: HealthLake.Types.ListFHIRExportJobsResponse) => void): Request<HealthLake.Types.ListFHIRExportJobsResponse, AWSError>; /** * Lists all FHIR export jobs associated with an account and their statuses. */ listFHIRExportJobs(callback?: (err: AWSError, data: HealthLake.Types.ListFHIRExportJobsResponse) => void): Request<HealthLake.Types.ListFHIRExportJobsResponse, AWSError>; /** * Lists all FHIR import jobs associated with an account and their statuses. */ listFHIRImportJobs(params: HealthLake.Types.ListFHIRImportJobsRequest, callback?: (err: AWSError, data: HealthLake.Types.ListFHIRImportJobsResponse) => void): Request<HealthLake.Types.ListFHIRImportJobsResponse, AWSError>; /** * Lists all FHIR import jobs associated with an account and their statuses. */ listFHIRImportJobs(callback?: (err: AWSError, data: HealthLake.Types.ListFHIRImportJobsResponse) => void): Request<HealthLake.Types.ListFHIRImportJobsResponse, AWSError>; /** * Returns a list of all existing tags associated with a Data Store. */ listTagsForResource(params: HealthLake.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: HealthLake.Types.ListTagsForResourceResponse) => void): Request<HealthLake.Types.ListTagsForResourceResponse, AWSError>; /** * Returns a list of all existing tags associated with a Data Store. */ listTagsForResource(callback?: (err: AWSError, data: HealthLake.Types.ListTagsForResourceResponse) => void): Request<HealthLake.Types.ListTagsForResourceResponse, AWSError>; /** * Begins a FHIR export job. */ startFHIRExportJob(params: HealthLake.Types.StartFHIRExportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.StartFHIRExportJobResponse) => void): Request<HealthLake.Types.StartFHIRExportJobResponse, AWSError>; /** * Begins a FHIR export job. */ startFHIRExportJob(callback?: (err: AWSError, data: HealthLake.Types.StartFHIRExportJobResponse) => void): Request<HealthLake.Types.StartFHIRExportJobResponse, AWSError>; /** * Begins a FHIR Import job. */ startFHIRImportJob(params: HealthLake.Types.StartFHIRImportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.StartFHIRImportJobResponse) => void): Request<HealthLake.Types.StartFHIRImportJobResponse, AWSError>; /** * Begins a FHIR Import job. */ startFHIRImportJob(callback?: (err: AWSError, data: HealthLake.Types.StartFHIRImportJobResponse) => void): Request<HealthLake.Types.StartFHIRImportJobResponse, AWSError>; /** * Adds a user specifed key and value tag to a Data Store. */ tagResource(params: HealthLake.Types.TagResourceRequest, callback?: (err: AWSError, data: HealthLake.Types.TagResourceResponse) => void): Request<HealthLake.Types.TagResourceResponse, AWSError>; /** * Adds a user specifed key and value tag to a Data Store. */ tagResource(callback?: (err: AWSError, data: HealthLake.Types.TagResourceResponse) => void): Request<HealthLake.Types.TagResourceResponse, AWSError>; /** * Removes tags from a Data Store. */ untagResource(params: HealthLake.Types.UntagResourceRequest, callback?: (err: AWSError, data: HealthLake.Types.UntagResourceResponse) => void): Request<HealthLake.Types.UntagResourceResponse, AWSError>; /** * Removes tags from a Data Store. */ untagResource(callback?: (err: AWSError, data: HealthLake.Types.UntagResourceResponse) => void): Request<HealthLake.Types.UntagResourceResponse, AWSError>; } declare namespace HealthLake { export type AmazonResourceName = string; export type BoundedLengthString = string; export type ClientTokenString = string; export type CmkType = "CUSTOMER_MANAGED_KMS_KEY"|"AWS_OWNED_KMS_KEY"|string; export interface CreateFHIRDatastoreRequest { /** * The user generated name for the Data Store. */ DatastoreName?: DatastoreName; /** * The FHIR version of the Data Store. The only supported version is R4. */ DatastoreTypeVersion: FHIRVersion; /** * The server-side encryption key configuration for a customer provided encryption key specified for creating a Data Store. */ SseConfiguration?: SseConfiguration; /** * Optional parameter to preload data upon creation of the Data Store. Currently, the only supported preloaded data is synthetic data generated from Synthea. */ PreloadDataConfig?: PreloadDataConfig; /** * Optional user provided token used for ensuring idempotency. */ ClientToken?: ClientTokenString; /** * Resource tags that are applied to a Data Store when it is created. */ Tags?: TagList; } export interface CreateFHIRDatastoreResponse { /** * The AWS-generated Data Store id. This id is in the output from the initial Data Store creation call. */ DatastoreId: DatastoreId; /** * The datastore ARN is generated during the creation of the Data Store and can be found in the output from the initial Data Store creation call. */ DatastoreArn: DatastoreArn; /** * The status of the FHIR Data Store. Possible statuses are ‘CREATING’, ‘ACTIVE’, ‘DELETING’, ‘DELETED’. */ DatastoreStatus: DatastoreStatus; /** * The AWS endpoint for the created Data Store. For preview, only US-east-1 endpoints are supported. */ DatastoreEndpoint: BoundedLengthString; } export type DatastoreArn = string; export interface DatastoreFilter { /** * Allows the user to filter Data Store results by name. */ DatastoreName?: DatastoreName; /** * Allows the user to filter Data Store results by status. */ DatastoreStatus?: DatastoreStatus; /** * A filter that allows the user to set cutoff dates for records. All Data Stores created before the specified date will be included in the results. */ CreatedBefore?: Timestamp; /** * A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified date will be included in the results. */ CreatedAfter?: Timestamp; } export type DatastoreId = string; export type DatastoreName = string; export interface DatastoreProperties { /** * The AWS-generated ID number for the Data Store. */ DatastoreId: DatastoreId; /** * The Amazon Resource Name used in the creation of the Data Store. */ DatastoreArn: DatastoreArn; /** * The user-generated name for the Data Store. */ DatastoreName?: DatastoreName; /** * The status of the Data Store. Possible statuses are 'CREATING', 'ACTIVE', 'DELETING', or 'DELETED'. */ DatastoreStatus: DatastoreStatus; /** * The time that a Data Store was created. */ CreatedAt?: Timestamp; /** * The FHIR version. Only R4 version data is supported. */ DatastoreTypeVersion: FHIRVersion; /** * The AWS endpoint for the Data Store. Each Data Store will have it's own endpoint with Data Store ID in the endpoint URL. */ DatastoreEndpoint: String; /** * The server-side encryption key configuration for a customer provided encryption key (CMK). */ SseConfiguration?: SseConfiguration; /** * The preloaded data configuration for the Data Store. Only data preloaded from Synthea is supported. */ PreloadDataConfig?: PreloadDataConfig; } export type DatastorePropertiesList = DatastoreProperties[]; export type DatastoreStatus = "CREATING"|"ACTIVE"|"DELETING"|"DELETED"|string; export interface DeleteFHIRDatastoreRequest { /** * The AWS-generated ID for the Data Store to be deleted. */ DatastoreId?: DatastoreId; } export interface DeleteFHIRDatastoreResponse { /** * The AWS-generated ID for the Data Store to be deleted. */ DatastoreId: DatastoreId; /** * The Amazon Resource Name (ARN) that gives Amazon HealthLake access permission. */ DatastoreArn: DatastoreArn; /** * The status of the Data Store that the user has requested to be deleted. */ DatastoreStatus: DatastoreStatus; /** * The AWS endpoint for the Data Store the user has requested to be deleted. */ DatastoreEndpoint: BoundedLengthString; } export interface DescribeFHIRDatastoreRequest { /** * The AWS-generated Data Store id. This is part of the ‘CreateFHIRDatastore’ output. */ DatastoreId?: DatastoreId; } export interface DescribeFHIRDatastoreResponse { /** * All properties associated with a Data Store, including the Data Store ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type version, and Data Store endpoint. */ DatastoreProperties: DatastoreProperties; } export interface DescribeFHIRExportJobRequest { /** * The AWS generated ID for the Data Store from which files are being exported from for an export job. */ DatastoreId: DatastoreId; /** * The AWS generated ID for an export job. */ JobId: JobId; } export interface DescribeFHIRExportJobResponse { /** * Displays the properties of the export job, including the ID, Arn, Name, and the status of the job. */ ExportJobProperties: ExportJobProperties; } export interface DescribeFHIRImportJobRequest { /** * The AWS-generated ID of the Data Store. */ DatastoreId: DatastoreId; /** * The AWS-generated job ID. */ JobId: JobId; } export interface DescribeFHIRImportJobResponse { /** * The properties of the Import job request, including the ID, ARN, name, and the status of the job. */ ImportJobProperties: ImportJobProperties; } export type EncryptionKeyID = string; export interface ExportJobProperties { /** * The AWS generated ID for an export job. */ JobId: JobId; /** * The user generated name for an export job. */ JobName?: JobName; /** * The status of a FHIR export job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, or FAILED. */ JobStatus: JobStatus; /** * The time an export job was initiated. */ SubmitTime: Timestamp; /** * The time an export job completed. */ EndTime?: Timestamp; /** * The AWS generated ID for the Data Store from which files are being exported for an export job. */ DatastoreId: DatastoreId; /** * The output data configuration that was supplied when the export job was created. */ OutputDataConfig: OutputDataConfig; /** * The Amazon Resource Name used during the initiation of the job. */ DataAccessRoleArn?: IamRoleArn; /** * An explanation of any errors that may have occurred during the export job. */ Message?: Message; } export type ExportJobPropertiesList = ExportJobProperties[]; export type FHIRVersion = "R4"|string; export type IamRoleArn = string; export interface ImportJobProperties { /** * The AWS-generated id number for the Import job. */ JobId: JobId; /** * The user-generated name for an Import job. */ JobName?: JobName; /** * The job status for an Import job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, FAILED. */ JobStatus: JobStatus; /** * The time that the Import job was submitted for processing. */ SubmitTime: Timestamp; /** * The time that the Import job was completed. */ EndTime?: Timestamp; /** * The datastore id used when the Import job was created. */ DatastoreId: DatastoreId; /** * The input data configuration that was supplied when the Import job was created. */ InputDataConfig: InputDataConfig; JobOutputDataConfig?: OutputDataConfig; /** * The Amazon Resource Name (ARN) that gives Amazon HealthLake access to your input data. */ DataAccessRoleArn?: IamRoleArn; /** * An explanation of any errors that may have occurred during the FHIR import job. */ Message?: Message; } export type ImportJobPropertiesList = ImportJobProperties[]; export interface InputDataConfig { /** * The S3Uri is the user specified S3 location of the FHIR data to be imported into Amazon HealthLake. */ S3Uri?: S3Uri; } export type JobId = string; export type JobName = string; export type JobStatus = "SUBMITTED"|"IN_PROGRESS"|"COMPLETED_WITH_ERRORS"|"COMPLETED"|"FAILED"|string; export interface KmsEncryptionConfig { /** * The type of customer-managed-key(CMK) used for encyrption. The two types of supported CMKs are customer owned CMKs and AWS owned CMKs. */ CmkType: CmkType; /** * The KMS encryption key id/alias used to encrypt the Data Store contents at rest. */ KmsKeyId?: EncryptionKeyID; } export interface ListFHIRDatastoresRequest { /** * Lists all filters associated with a FHIR Data Store request. */ Filter?: DatastoreFilter; /** * Fetches the next page of Data Stores when results are paginated. */ NextToken?: NextToken; /** * The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call. */ MaxResults?: MaxResultsInteger; } export interface ListFHIRDatastoresResponse { /** * All properties associated with the listed Data Stores. */ DatastorePropertiesList: DatastorePropertiesList; /** * Pagination token that can be used to retrieve the next page of results. */ NextToken?: NextToken; } export interface ListFHIRExportJobsRequest { /** * This parameter limits the response to the export job with the specified Data Store ID. */ DatastoreId: DatastoreId; /** * A pagination token used to identify the next page of results to return for a ListFHIRExportJobs query. */ NextToken?: NextToken; /** * This parameter limits the number of results returned for a ListFHIRExportJobs to a maximum quantity specified by the user. */ MaxResults?: MaxResultsInteger; /** * This parameter limits the response to the export job with the specified job name. */ JobName?: JobName; /** * This parameter limits the response to the export jobs with the specified job status. */ JobStatus?: JobStatus; /** * This parameter limits the response to FHIR export jobs submitted before a user specified date. */ SubmittedBefore?: Timestamp; /** * This parameter limits the response to FHIR export jobs submitted after a user specified date. */ SubmittedAfter?: Timestamp; } export interface ListFHIRExportJobsResponse { /** * The properties of listed FHIR export jobs, including the ID, ARN, name, and the status of the job. */ ExportJobPropertiesList: ExportJobPropertiesList; /** * A pagination token used to identify the next page of results to return for a ListFHIRExportJobs query. */ NextToken?: NextToken; } export interface ListFHIRImportJobsRequest { /** * This parameter limits the response to the import job with the specified Data Store ID. */ DatastoreId: DatastoreId; /** * A pagination token used to identify the next page of results to return for a ListFHIRImportJobs query. */ NextToken?: NextToken; /** * This parameter limits the number of results returned for a ListFHIRImportJobs to a maximum quantity specified by the user. */ MaxResults?: MaxResultsInteger; /** * This parameter limits the response to the import job with the specified job name. */ JobName?: JobName; /** * This parameter limits the response to the import job with the specified job status. */ JobStatus?: JobStatus; /** * This parameter limits the response to FHIR import jobs submitted before a user specified date. */ SubmittedBefore?: Timestamp; /** * This parameter limits the response to FHIR import jobs submitted after a user specified date. */ SubmittedAfter?: Timestamp; } export interface ListFHIRImportJobsResponse { /** * The properties of a listed FHIR import jobs, including the ID, ARN, name, and the status of the job. */ ImportJobPropertiesList: ImportJobPropertiesList; /** * A pagination token used to identify the next page of results to return for a ListFHIRImportJobs query. */ NextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name(ARN) of the Data Store for which tags are being added. */ ResourceARN: AmazonResourceName; } export interface ListTagsForResourceResponse { /** * Returns a list of tags associated with a Data Store. */ Tags?: TagList; } export type MaxResultsInteger = number; export type Message = string; export type NextToken = string; export interface OutputDataConfig { /** * The output data configuration that was supplied when the export job was created. */ S3Configuration?: S3Configuration; } export interface PreloadDataConfig { /** * The type of preloaded data. Only Synthea preloaded data is supported. */ PreloadDataType: PreloadDataType; } export type PreloadDataType = "SYNTHEA"|string; export interface S3Configuration { /** * The S3Uri is the user specified S3 location of the FHIR data to be imported into Amazon HealthLake. */ S3Uri: S3Uri; /** * The KMS key ID used to access the S3 bucket. */ KmsKeyId: EncryptionKeyID; } export type S3Uri = string; export interface SseConfiguration { /** * The KMS encryption configuration used to provide details for data encryption. */ KmsEncryptionConfig: KmsEncryptionConfig; } export interface StartFHIRExportJobRequest { /** * The user generated name for an export job. */ JobName?: JobName; /** * The output data configuration that was supplied when the export job was created. */ OutputDataConfig: OutputDataConfig; /** * The AWS generated ID for the Data Store from which files are being exported for an export job. */ DatastoreId: DatastoreId; /** * The Amazon Resource Name used during the initiation of the job. */ DataAccessRoleArn: IamRoleArn; /** * An optional user provided token used for ensuring idempotency. */ ClientToken: ClientTokenString; } export interface StartFHIRExportJobResponse { /** * The AWS generated ID for an export job. */ JobId: JobId; /** * The status of a FHIR export job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, or FAILED. */ JobStatus: JobStatus; /** * The AWS generated ID for the Data Store from which files are being exported for an export job. */ DatastoreId?: DatastoreId; } export interface StartFHIRImportJobRequest { /** * The name of the FHIR Import job in the StartFHIRImport job request. */ JobName?: JobName; /** * The input properties of the FHIR Import job in the StartFHIRImport job request. */ InputDataConfig: InputDataConfig; JobOutputDataConfig: OutputDataConfig; /** * The AWS-generated Data Store ID. */ DatastoreId: DatastoreId; /** * The Amazon Resource Name (ARN) that gives Amazon HealthLake access permission. */ DataAccessRoleArn: IamRoleArn; /** * Optional user provided token used for ensuring idempotency. */ ClientToken: ClientTokenString; } export interface StartFHIRImportJobResponse { /** * The AWS-generated job ID. */ JobId: JobId; /** * The status of an import job. */ JobStatus: JobStatus; /** * The AWS-generated Data Store ID. */ DatastoreId?: DatastoreId; } export type String = string; export interface Tag { /** * The key portion of a tag. Tag keys are case sensitive. */ Key: TagKey; /** * The value portion of tag. Tag values are case sensitive. */ Value: TagValue; } export type TagKey = string; export type TagKeyList = TagKey[]; export type TagList = Tag[]; export interface TagResourceRequest { /** * The Amazon Resource Name(ARN)that gives Amazon HealthLake access to the Data Store which tags are being added to. */ ResourceARN: AmazonResourceName; /** * The user specified key and value pair tags being added to a Data Store. */ Tags: TagList; } export interface TagResourceResponse { } export type TagValue = string; export type Timestamp = Date; export interface UntagResourceRequest { /** * "The Amazon Resource Name(ARN) of the Data Store for which tags are being removed */ ResourceARN: AmazonResourceName; /** * The keys for the tags to be removed from the Healthlake Data Store. */ TagKeys: TagKeyList; } export interface UntagResourceResponse { } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2017-07-01"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the HealthLake client. */ export import Types = HealthLake; } export = HealthLake;
the_stack
import { tasks, options } from '@tko/utils' import { observable as koObservable, observableArray as koObservableArray, subscribable as koSubscribable } from '@tko/observable' import { computed as koComputed, pureComputed as koPureComputed, when } from '../dist' import { useMockForTasks } from '@tko/utils/helpers/jasmine-13-helper' describe('Throttled observables', function () { beforeEach(function () { waits(1) }) // Workaround for spurious timing-related failures on IE8 (issue #736) it('Should notify subscribers asynchronously after writes stop for the specified timeout duration', function () { var observable = koObservable('A').extend({ throttle: 100 }) var notifiedValues = [] observable.subscribe(function (value) { notifiedValues.push(value) }) runs(function () { // Mutate a few times observable('B') observable('C') observable('D') expect(notifiedValues.length).toEqual(0) // Should not notify synchronously }) // Wait waits(10) runs(function () { // Mutate more observable('E') observable('F') expect(notifiedValues.length).toEqual(0) // Should not notify until end of throttle timeout }) // Wait until after timeout waitsFor(function () { return notifiedValues.length > 0 }, 300) runs(function () { expect(notifiedValues.length).toEqual(1) expect(notifiedValues[0]).toEqual('F') }) }) }) describe('Throttled dependent observables', function () { beforeEach(function () { waits(1) }) // Workaround for spurious timing-related failures on IE8 (issue #736) it('Should notify subscribers asynchronously after dependencies stop updating for the specified timeout duration', function () { var underlying = koObservable() var asyncDepObs = koComputed(function () { return underlying() }).extend({ throttle: 100 }) var notifiedValues = [] asyncDepObs.subscribe(function (value) { notifiedValues.push(value) }) // Check initial state expect(asyncDepObs()).toBeUndefined() runs(function () { // Mutate underlying('New value') expect(asyncDepObs()).toBeUndefined() // Should not update synchronously expect(notifiedValues.length).toEqual(0) }) // Still shouldn't have evaluated waits(10) runs(function () { expect(asyncDepObs()).toBeUndefined() // Should not update until throttle timeout expect(notifiedValues.length).toEqual(0) }) // Now wait for throttle timeout waitsFor(function () { return notifiedValues.length > 0 }, 300) runs(function () { expect(asyncDepObs()).toEqual('New value') expect(notifiedValues.length).toEqual(1) expect(notifiedValues[0]).toEqual('New value') }) }) it('Should run evaluator only once when dependencies stop updating for the specified timeout duration', function () { var evaluationCount = 0 var someDependency = koObservable() var asyncDepObs = koComputed(function () { evaluationCount++ return someDependency() }).extend({ throttle: 100 }) runs(function () { // Mutate a few times synchronously expect(evaluationCount).toEqual(1) // Evaluates synchronously when first created, like all dependent observables someDependency('A') someDependency('B') someDependency('C') expect(evaluationCount).toEqual(1) // Should not re-evaluate synchronously when dependencies update }) // Also mutate async waits(10) runs(function () { someDependency('D') expect(evaluationCount).toEqual(1) }) // Now wait for throttle timeout waitsFor(function () { return evaluationCount > 1 }, 300) runs(function () { expect(evaluationCount).toEqual(2) // Finally, it's evaluated expect(asyncDepObs()).toEqual('D') }) }) }) describe('Rate-limited', function () { beforeEach(function () { jasmine.Clock.useMock() }) describe('Subscribable', function () { it('Should delay change notifications', function () { var subscribable = new koSubscribable().extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') subscribable.subscribe(notifySpy) subscribable.subscribe(notifySpy, null, 'custom') // "change" notification is delayed subscribable.notifySubscribers('a', 'change') expect(notifySpy).not.toHaveBeenCalled() // Default notification is delayed subscribable.notifySubscribers('b') expect(notifySpy).not.toHaveBeenCalled() // Other notifications happen immediately subscribable.notifySubscribers('c', 'custom') expect(notifySpy).toHaveBeenCalledWith('c') // Advance clock; Change notification happens now using the latest value notified notifySpy.reset() jasmine.Clock.tick(500) expect(notifySpy).toHaveBeenCalledWith('b') }) it('Should notify every timeout interval using notifyAtFixedRate method ', function () { var subscribable = new koSubscribable().extend({rateLimit: {method: 'notifyAtFixedRate', timeout: 50}}) var notifySpy = jasmine.createSpy('notifySpy') subscribable.subscribe(notifySpy) // Push 10 changes every 25 ms for (var i = 0; i < 10; ++i) { subscribable.notifySubscribers(i + 1) jasmine.Clock.tick(25) } // Notification happens every 50 ms, so every other number is notified expect(notifySpy.calls.length).toBe(5) expect(notifySpy.argsForCall).toEqual([ [2], [4], [6], [8], [10] ]) // No more notifications happen notifySpy.reset() jasmine.Clock.tick(50) expect(notifySpy).not.toHaveBeenCalled() }) it('Should notify after nothing happens for the timeout period using notifyWhenChangesStop method', function () { var subscribable = new koSubscribable().extend({rateLimit: {method: 'notifyWhenChangesStop', timeout: 50}}) var notifySpy = jasmine.createSpy('notifySpy') subscribable.subscribe(notifySpy) // Push 10 changes every 25 ms for (var i = 0; i < 10; ++i) { subscribable.notifySubscribers(i + 1) jasmine.Clock.tick(25) } // No notifications happen yet expect(notifySpy).not.toHaveBeenCalled() // Notification happens after the timeout period jasmine.Clock.tick(50) expect(notifySpy.calls.length).toBe(1) expect(notifySpy).toHaveBeenCalledWith(10) }) it('Should use latest settings when applied multiple times', function () { var subscribable = new koSubscribable().extend({rateLimit: 250}).extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') subscribable.subscribe(notifySpy) subscribable.notifySubscribers('a') jasmine.Clock.tick(250) expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(250) expect(notifySpy).toHaveBeenCalledWith('a') }) it('Uses latest settings for future notification and previous settings for pending notification', function () { // This test describes the current behavior for the given scenario but is not a contract for that // behavior, which could change in the future if convenient. var subscribable = new koSubscribable().extend({rateLimit: 250}) var notifySpy = jasmine.createSpy('notifySpy') subscribable.subscribe(notifySpy) subscribable.notifySubscribers('a') // Pending notification // Apply new setting and schedule new notification subscribable = subscribable.extend({rateLimit: 500}) subscribable.notifySubscribers('b') // First notification happens using original settings jasmine.Clock.tick(250) expect(notifySpy).toHaveBeenCalledWith('a') // Second notification happends using later settings notifySpy.reset() jasmine.Clock.tick(250) expect(notifySpy).toHaveBeenCalledWith('b') }) }) describe('Observable', function () { it('Should delay change notifications', function () { var observable = koObservable().extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy') .andCallFake(function (value) { expect(observable()).toBe(value) }) observable.subscribe(beforeChangeSpy, null, 'beforeChange') // Observable is changed, but notification is delayed observable('a') expect(observable()).toEqual('a') expect(notifySpy).not.toHaveBeenCalled() expect(beforeChangeSpy).toHaveBeenCalledWith(undefined) // beforeChange notification happens right away // Second change notification is also delayed observable('b') expect(notifySpy).not.toHaveBeenCalled() // Advance clock; Change notification happens now using the latest value notified jasmine.Clock.tick(500) expect(notifySpy).toHaveBeenCalledWith('b') expect(beforeChangeSpy.calls.length).toBe(1) // Only one beforeChange notification }) it('Should notify "spectator" subscribers whenever the value changes', function () { var observable = new koObservable('A').extend({rateLimit: 500}), spectateSpy = jasmine.createSpy('notifySpy'), notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(spectateSpy, null, 'spectate') observable.subscribe(notifySpy) expect(spectateSpy).not.toHaveBeenCalled() expect(notifySpy).not.toHaveBeenCalled() observable('B') expect(spectateSpy).toHaveBeenCalledWith('B') observable('C') expect(spectateSpy).toHaveBeenCalledWith('C') expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(500) // "spectate" was called for each new value expect(spectateSpy.argsForCall).toEqual([ ['B'], ['C'] ]) // whereas "change" was only called for the final value expect(notifySpy.argsForCall).toEqual([ ['C'] ]) }) it('Should suppress change notification when value is changed/reverted', function () { var observable = koObservable('original').extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy') observable.subscribe(beforeChangeSpy, null, 'beforeChange') observable('new') // change value expect(observable()).toEqual('new') // access observable to make sure it really has the changed value observable('original') // but then change it back expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(500) expect(notifySpy).not.toHaveBeenCalled() // Check that value is correct and notification hasn't happened expect(observable()).toEqual('original') expect(notifySpy).not.toHaveBeenCalled() // Changing observable to a new value still works as expected observable('new') jasmine.Clock.tick(500) expect(notifySpy).toHaveBeenCalledWith('new') expect(beforeChangeSpy).toHaveBeenCalledWith('original') expect(beforeChangeSpy).not.toHaveBeenCalledWith('new') }) it('Should support notifications from nested update', function () { var observable = koObservable('a').extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) // Create a one-time subscription that will modify the observable var updateSub = observable.subscribe(function () { updateSub.dispose() observable('z') }) observable('b') expect(notifySpy).not.toHaveBeenCalled() expect(observable()).toEqual('b') notifySpy.reset() jasmine.Clock.tick(500) expect(notifySpy).toHaveBeenCalledWith('b') expect(observable()).toEqual('z') notifySpy.reset() jasmine.Clock.tick(500) expect(notifySpy).toHaveBeenCalledWith('z') }) it('Should suppress notifications when value is changed/reverted from nested update', function () { var observable = koObservable('a').extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) // Create a one-time subscription that will modify the observable and then revert the change var updateSub = observable.subscribe(function (newValue) { updateSub.dispose() observable('z') observable(newValue) }) observable('b') expect(notifySpy).not.toHaveBeenCalled() expect(observable()).toEqual('b') notifySpy.reset() jasmine.Clock.tick(500) expect(notifySpy).toHaveBeenCalledWith('b') expect(observable()).toEqual('b') notifySpy.reset() jasmine.Clock.tick(500) expect(notifySpy).not.toHaveBeenCalled() }) it('Should not notify future subscribers', function () { var observable = koObservable('a').extend({rateLimit: 500}), notifySpy1 = jasmine.createSpy('notifySpy1'), notifySpy2 = jasmine.createSpy('notifySpy2'), notifySpy3 = jasmine.createSpy('notifySpy3') observable.subscribe(notifySpy1) observable('b') observable.subscribe(notifySpy2) observable('c') observable.subscribe(notifySpy3) expect(notifySpy1).not.toHaveBeenCalled() expect(notifySpy2).not.toHaveBeenCalled() expect(notifySpy3).not.toHaveBeenCalled() jasmine.Clock.tick(500) expect(notifySpy1).toHaveBeenCalledWith('c') expect(notifySpy2).toHaveBeenCalledWith('c') expect(notifySpy3).not.toHaveBeenCalled() }) it('Should delay update of dependent computed observable', function () { var observable = koObservable().extend({rateLimit: 500}) var computed = koComputed(observable) // Check initial value expect(computed()).toBeUndefined() // Observable is changed, but computed is not observable('a') expect(observable()).toEqual('a') expect(computed()).toBeUndefined() // Second change also observable('b') expect(computed()).toBeUndefined() // Advance clock; Change notification happens now using the latest value notified jasmine.Clock.tick(500) expect(computed()).toEqual('b') }) it('Should delay update of dependent pure computed observable', function () { var observable = koObservable().extend({rateLimit: 500}) var computed = koPureComputed(observable) // Check initial value expect(computed()).toBeUndefined() // Observable is changed, but computed is not observable('a') expect(observable()).toEqual('a') expect(computed()).toBeUndefined() // Second change also observable('b') expect(computed()).toBeUndefined() // Advance clock; Change notification happens now using the latest value notified jasmine.Clock.tick(500) expect(computed()).toEqual('b') }) it('Should not update dependent computed created after last update', function () { var observable = koObservable('a').extend({rateLimit: 500}) observable('b') var evalSpy = jasmine.createSpy('evalSpy') var computed = koComputed(function () { return evalSpy(observable()) }) expect(evalSpy).toHaveBeenCalledWith('b') evalSpy.reset() jasmine.Clock.tick(500) expect(evalSpy).not.toHaveBeenCalled() }) }) describe('Observable Array change tracking', function () { it('Should provide correct changelist when multiple updates are merged into one notification', function () { var myArray = koObservableArray(['Alpha', 'Beta']).extend({rateLimit: 1}), changelist myArray.subscribe(function (changes) { changelist = changes }, null, 'arrayChange') myArray.push('Gamma') myArray.push('Delta') jasmine.Clock.tick(10) expect(changelist).toEqual([ { status: 'added', value: 'Gamma', index: 2 }, { status: 'added', value: 'Delta', index: 3 } ]) changelist = undefined myArray.shift() myArray.shift() jasmine.Clock.tick(10) expect(changelist).toEqual([ { status: 'deleted', value: 'Alpha', index: 0 }, { status: 'deleted', value: 'Beta', index: 1 } ]) changelist = undefined myArray.push('Epsilon') myArray.pop() jasmine.Clock.tick(10) expect(changelist).toEqual(undefined) }) }) describe('Computed Observable', function () { it('Should delay running evaluator where there are no subscribers', function () { var observable = koObservable() var evalSpy = jasmine.createSpy('evalSpy') koComputed(function () { evalSpy(observable()); return observable() }).extend({rateLimit: 500}) // Observable is changed, but evaluation is delayed evalSpy.reset() observable('a') observable('b') expect(evalSpy).not.toHaveBeenCalled() // Advance clock; Change notification happens now using the latest value notified evalSpy.reset() jasmine.Clock.tick(500) expect(evalSpy).toHaveBeenCalledWith('b') }) it('Should delay change notifications and evaluation', function () { var observable = koObservable() var evalSpy = jasmine.createSpy('evalSpy') var computed = koComputed(function () { evalSpy(observable()); return observable() }).extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') computed.subscribe(notifySpy) var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy') .andCallFake(function (value) { expect(computed()).toBe(value) }) computed.subscribe(beforeChangeSpy, null, 'beforeChange') // Observable is changed, but notification is delayed evalSpy.reset() observable('a') expect(evalSpy).not.toHaveBeenCalled() expect(computed()).toEqual('a') expect(evalSpy).toHaveBeenCalledWith('a') // evaluation happens when computed is accessed expect(notifySpy).not.toHaveBeenCalled() // but notification is still delayed expect(beforeChangeSpy).toHaveBeenCalledWith(undefined) // beforeChange notification happens right away // Second change notification is also delayed evalSpy.reset() observable('b') expect(computed.peek()).toEqual('a') // peek returns previously evaluated value expect(evalSpy).not.toHaveBeenCalled() expect(notifySpy).not.toHaveBeenCalled() // Advance clock; Change notification happens now using the latest value notified evalSpy.reset() jasmine.Clock.tick(500) expect(evalSpy).toHaveBeenCalledWith('b') expect(notifySpy).toHaveBeenCalledWith('b') expect(beforeChangeSpy.calls.length).toBe(1) // Only one beforeChange notification }) it('Should run initial evaluation at first subscribe when using deferEvaluation', function () { // This behavior means that code using rate-limited computeds doesn't need to care if the // computed also has deferEvaluation. For example, the preceding test ('Should delay change // notifications and evaluation') will pass just as well if using deferEvaluation. var observable = koObservable('a') var evalSpy = jasmine.createSpy('evalSpy') var computed = koComputed({ read: function () { evalSpy(observable()) return observable() }, deferEvaluation: true }).extend({rateLimit: 500}) expect(evalSpy).not.toHaveBeenCalled() var notifySpy = jasmine.createSpy('notifySpy') computed.subscribe(notifySpy) expect(evalSpy).toHaveBeenCalledWith('a') expect(notifySpy).not.toHaveBeenCalled() }) it('Should run initial evaluation when observable is accessed when using deferEvaluation', function () { var observable = koObservable('a') var evalSpy = jasmine.createSpy('evalSpy') var computed = koComputed({ read: function () { evalSpy(observable()) return observable() }, deferEvaluation: true }).extend({rateLimit: 500}) expect(evalSpy).not.toHaveBeenCalled() expect(computed()).toEqual('a') expect(evalSpy).toHaveBeenCalledWith('a') }) it('Should suppress change notifications when value is changed/reverted', function () { var observable = koObservable('original') var computed = koComputed(function () { return observable() }).extend({rateLimit: 500}) var notifySpy = jasmine.createSpy('notifySpy') computed.subscribe(notifySpy) var beforeChangeSpy = jasmine.createSpy('beforeChangeSpy') computed.subscribe(beforeChangeSpy, null, 'beforeChange') observable('new') // change value expect(computed()).toEqual('new') // access computed to make sure it really has the changed value observable('original') // and then change the value back expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(500) expect(notifySpy).not.toHaveBeenCalled() // Check that value is correct and notification hasn't happened expect(computed()).toEqual('original') expect(notifySpy).not.toHaveBeenCalled() // Changing observable to a new value still works as expected observable('new') jasmine.Clock.tick(500) expect(notifySpy).toHaveBeenCalledWith('new') expect(beforeChangeSpy).toHaveBeenCalledWith('original') expect(beforeChangeSpy).not.toHaveBeenCalledWith('new') }) it('Should not re-evaluate if computed is disposed before timeout', function () { var observable = koObservable('a') var evalSpy = jasmine.createSpy('evalSpy') var computed = koComputed(function () { evalSpy(observable()); return observable() }).extend({rateLimit: 500}) expect(computed()).toEqual('a') expect(evalSpy.calls.length).toBe(1) expect(evalSpy).toHaveBeenCalledWith('a') evalSpy.reset() observable('b') computed.dispose() jasmine.Clock.tick(500) expect(computed()).toEqual('a') expect(evalSpy).not.toHaveBeenCalled() }) it('Should be able to re-evaluate a computed that previously threw an exception', function () { var observableSwitch = koObservable(true), observableValue = koObservable(1), computed = koComputed(function () { if (!observableSwitch()) { throw Error('Error during computed evaluation') } else { return observableValue() } }).extend({rateLimit: 500}) // Initially the computed evaluated successfully expect(computed()).toEqual(1) expect(function () { // Update observable to cause computed to throw an exception observableSwitch(false) computed() }).toThrow('Error during computed evaluation') // The value of the computed is now undefined, although currently it keeps the previous value // This should not try to re-evaluate and thus shouldn't throw an exception expect(computed()).toEqual(1) expect(computed.getDependencies()).toEqual([observableSwitch]) // The computed should not be dependent on the second observable expect(computed.getDependenciesCount()).toEqual(1) // Updating the second observable shouldn't re-evaluate computed observableValue(2) expect(computed()).toEqual(1) // Update the first observable to cause computed to re-evaluate observableSwitch(1) expect(computed()).toEqual(2) }) it('Should delay update of dependent computed observable', function () { var observable = koObservable() var rateLimitComputed = koComputed(observable).extend({rateLimit: 500}) var dependentComputed = koComputed(rateLimitComputed) // Check initial value expect(dependentComputed()).toBeUndefined() // Rate-limited computed is changed, but dependent computed is not observable('a') expect(rateLimitComputed()).toEqual('a') expect(dependentComputed()).toBeUndefined() // Second change also observable('b') expect(dependentComputed()).toBeUndefined() // Advance clock; Change notification happens now using the latest value notified jasmine.Clock.tick(500) expect(dependentComputed()).toEqual('b') }) it('Should delay update of dependent pure computed observable', function () { var observable = koObservable() var rateLimitComputed = koComputed(observable).extend({rateLimit: 500}) var dependentComputed = koPureComputed(rateLimitComputed) // Check initial value expect(dependentComputed()).toBeUndefined() // Rate-limited computed is changed, but dependent computed is not observable('a') expect(rateLimitComputed()).toEqual('a') expect(dependentComputed()).toBeUndefined() // Second change also observable('b') expect(dependentComputed()).toBeUndefined() // Advance clock; Change notification happens now using the latest value notified jasmine.Clock.tick(500) expect(dependentComputed()).toEqual('b') }) it('Should not cause loss of updates when an intermediate value is read by a dependent computed observable', function () { // From https://github.com/knockout/knockout/issues/1835 var one = koObservable(false), onePointOne = koComputed(one).extend({rateLimit: 100}), two = koObservable(false), three = koComputed(function () { return onePointOne() || two() }), threeNotifications = [] three.subscribe(function (val) { threeNotifications.push(val) }) // The loop shows that the same steps work continuously for (var i = 0; i < 3; i++) { expect(onePointOne() || two() || three()).toEqual(false) threeNotifications = [] one(true) expect(threeNotifications).toEqual([]) two(true) expect(threeNotifications).toEqual([true]) two(false) expect(threeNotifications).toEqual([true]) one(false) expect(threeNotifications).toEqual([true]) jasmine.Clock.tick(100) expect(threeNotifications).toEqual([true, false]) } }) }) }) describe('Deferred', function () { beforeEach(function () { useMockForTasks(options) }) afterEach(function () { expect(tasks.resetForTesting()).toEqual(0) jasmine.Clock.reset() }) describe('Observable', function () { it('Should delay notifications', function () { var observable = koObservable().extend({deferred: true}) var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) observable('A') expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([ ['A'] ]) }) it('Should throw if you attempt to turn off deferred', function () { // As of commit 6d5d786, the 'deferred' option cannot be deactivated (once activated for // a given observable). var observable = koObservable() observable.extend({deferred: true}) expect(function () { observable.extend({deferred: false}) }).toThrow('The \'deferred\' extender only accepts the value \'true\', because it is not supported to turn deferral off once enabled.') }) it('Should notify subscribers about only latest value', function () { var observable = koObservable().extend({notify: 'always', deferred: true}) // include notify:'always' to ensure notifications weren't suppressed by some other means var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) observable('A') observable('B') jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([ ['B'] ]) }) it('Should suppress notification when value is changed/reverted', function () { var observable = koObservable('original').extend({deferred: true}) var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) observable('new') expect(observable()).toEqual('new') observable('original') jasmine.Clock.tick(1) expect(notifySpy).not.toHaveBeenCalled() expect(observable()).toEqual('original') }) it('Should not notify future subscribers', function () { var observable = koObservable('a').extend({deferred: true}), notifySpy1 = jasmine.createSpy('notifySpy1'), notifySpy2 = jasmine.createSpy('notifySpy2'), notifySpy3 = jasmine.createSpy('notifySpy3') observable.subscribe(notifySpy1) observable('b') observable.subscribe(notifySpy2) observable('c') observable.subscribe(notifySpy3) expect(notifySpy1).not.toHaveBeenCalled() expect(notifySpy2).not.toHaveBeenCalled() expect(notifySpy3).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy1).toHaveBeenCalledWith('c') expect(notifySpy2).toHaveBeenCalledWith('c') expect(notifySpy3).not.toHaveBeenCalled() }) it('Should not update dependent computed created after last update', function () { var observable = koObservable('a').extend({deferred: true}) observable('b') var evalSpy = jasmine.createSpy('evalSpy') var computed = koComputed(function () { return evalSpy(observable()) }) expect(evalSpy).toHaveBeenCalledWith('b') evalSpy.reset() jasmine.Clock.tick(1) expect(evalSpy).not.toHaveBeenCalled() }) it('Is default behavior when "options.deferUpdates" is "true"', function () { this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var observable = koObservable() var notifySpy = jasmine.createSpy('notifySpy') observable.subscribe(notifySpy) observable('A') expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([ ['A'] ]) }) it('Should not cause loss of updates when an intermediate value is read by a dependent computed observable', function () { // From https://github.com/knockout/knockout/issues/1835 var one = koObservable(false).extend({rateLimit: 100}), two = koObservable(false), three = koComputed(function () { return one() || two() }), threeNotifications = [] three.subscribe(function (val) { threeNotifications.push(val) }) // The loop shows that the same steps work continuously for (var i = 0; i < 3; i++) { expect(one() || two() || three()).toEqual(false) threeNotifications = [] one(true) expect(threeNotifications).toEqual([]) two(true) expect(threeNotifications).toEqual([true]) two(false) expect(threeNotifications).toEqual([true]) one(false) expect(threeNotifications).toEqual([true]) jasmine.Clock.tick(100) expect(threeNotifications).toEqual([true, false]) } }) }) describe('Observable Array change tracking', function () { it('Should provide correct changelist when multiple updates are merged into one notification', function () { var myArray = koObservableArray(['Alpha', 'Beta']).extend({deferred: true}), changelist myArray.subscribe(function (changes) { changelist = changes }, null, 'arrayChange') myArray.push('Gamma') myArray.push('Delta') jasmine.Clock.tick(1) expect(changelist).toEqual([ { status: 'added', value: 'Gamma', index: 2 }, { status: 'added', value: 'Delta', index: 3 } ]) changelist = undefined myArray.shift() myArray.shift() jasmine.Clock.tick(1) expect(changelist).toEqual([ { status: 'deleted', value: 'Alpha', index: 0 }, { status: 'deleted', value: 'Beta', index: 1 } ]) changelist = undefined myArray.push('Epsilon') myArray.pop() jasmine.Clock.tick(1) expect(changelist).toEqual(undefined) }) }) describe('Computed Observable', function () { it('Should defer notification of changes and minimize evaluation', function () { var timesEvaluated = 0, data = koObservable('A'), computed = koComputed(function () { ++timesEvaluated; return data() }).extend({deferred: true}), notifySpy = jasmine.createSpy('notifySpy') computed.subscribe(notifySpy) expect(computed()).toEqual('A') expect(timesEvaluated).toEqual(1) jasmine.Clock.tick(1) expect(notifySpy).not.toHaveBeenCalled() data('B') expect(timesEvaluated).toEqual(1) // not immediately evaluated expect(computed()).toEqual('B') expect(timesEvaluated).toEqual(2) expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy.calls.length).toEqual(1) expect(notifySpy.argsForCall).toEqual([ ['B'] ]) }) it('Should notify first change of computed with deferEvaluation if value is changed to undefined', function () { var data = koObservable('A'), computed = koComputed(data, null, {deferEvaluation: true}).extend({deferred: true}), notifySpy = jasmine.createSpy('notifySpy') computed.subscribe(notifySpy) expect(computed()).toEqual('A') data(undefined) expect(computed()).toEqual(undefined) expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy.calls.length).toEqual(1) expect(notifySpy.argsForCall).toEqual([ [undefined] ]) }) it('Should notify first change to pure computed after awakening if value changed to last notified value', function () { var data = koObservable('A'), computed = koPureComputed(data).extend({deferred: true}), notifySpy = jasmine.createSpy('notifySpy'), subscription = computed.subscribe(notifySpy) data('B') expect(computed()).toEqual('B') expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([ ['B'] ]) subscription.dispose() notifySpy.reset() data('C') expect(computed()).toEqual('C') jasmine.Clock.tick(1) expect(notifySpy).not.toHaveBeenCalled() subscription = computed.subscribe(notifySpy) data('B') expect(computed()).toEqual('B') expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([ ['B'] ]) }) it('Should delay update of dependent computed observable', function () { var data = koObservable('A'), deferredComputed = koComputed(data).extend({deferred: true}), dependentComputed = koComputed(deferredComputed) expect(dependentComputed()).toEqual('A') data('B') expect(deferredComputed()).toEqual('B') expect(dependentComputed()).toEqual('A') data('C') expect(dependentComputed()).toEqual('A') jasmine.Clock.tick(1) expect(dependentComputed()).toEqual('C') }) it('Should delay update of dependent pure computed observable', function () { var data = koObservable('A'), deferredComputed = koComputed(data).extend({deferred: true}), dependentComputed = koPureComputed(deferredComputed) expect(dependentComputed()).toEqual('A') data('B') expect(deferredComputed()).toEqual('B') expect(dependentComputed()).toEqual('A') data('C') expect(dependentComputed()).toEqual('A') jasmine.Clock.tick(1) expect(dependentComputed()).toEqual('C') }) it('Should *not* delay update of dependent deferred pure computed observable', function () { var data = koObservable('A').extend({deferred: true}), timesEvaluated = 0, computed1 = koPureComputed(function () { return data() + 'X' }).extend({deferred: true}), computed2 = koPureComputed(function () { timesEvaluated++; return computed1() + 'Y' }).extend({deferred: true}) expect(computed2()).toEqual('AXY') expect(timesEvaluated).toEqual(1) data('B') expect(computed2()).toEqual('BXY') expect(timesEvaluated).toEqual(2) jasmine.Clock.tick(1) expect(computed2()).toEqual('BXY') expect(timesEvaluated).toEqual(2) // Verify that the computed wasn't evaluated again unnecessarily }) it('Should *not* delay update of dependent deferred computed observable', function () { var data = koObservable('A').extend({ deferred: true }), timesEvaluated = 0, computed1 = koComputed(function () { return data() + 'X' }).extend({deferred: true}), computed2 = koComputed(function () { timesEvaluated++; return computed1() + 'Y' }).extend({deferred: true}), notifySpy = jasmine.createSpy('notifySpy') computed2.subscribe(notifySpy) expect(computed2()).toEqual('AXY') expect(timesEvaluated).toEqual(1) data('B') expect(computed2()).toEqual('BXY') expect(timesEvaluated).toEqual(2) expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(computed2()).toEqual('BXY') expect(timesEvaluated).toEqual(2) // Verify that the computed wasn't evaluated again unnecessarily expect(notifySpy.argsForCall).toEqual([ ['BXY'] ]) }) it('Should *not* delay update of dependent rate-limited computed observable', function () { var data = koObservable('A'), deferredComputed = koComputed(data).extend({deferred: true}), dependentComputed = koComputed(deferredComputed).extend({rateLimit: 500}), notifySpy = jasmine.createSpy('notifySpy') dependentComputed.subscribe(notifySpy) expect(dependentComputed()).toEqual('A') data('B') expect(deferredComputed()).toEqual('B') expect(dependentComputed()).toEqual('B') data('C') expect(dependentComputed()).toEqual('C') expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(500) expect(dependentComputed()).toEqual('C') expect(notifySpy.argsForCall).toEqual([ ['C'] ]) }) it('Is default behavior when "options.deferUpdates" is "true"', function () { this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var data = koObservable('A'), computed = koComputed(data), notifySpy = jasmine.createSpy('notifySpy') computed.subscribe(notifySpy) // Notification is deferred data('B') expect(notifySpy).not.toHaveBeenCalled() jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([ ['B'] ]) }) it('Is superseded by rate-limit', function () { this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var data = koObservable('A'), deferredComputed = koComputed(data), dependentComputed = koComputed(function () { return 'R' + deferredComputed() }).extend({rateLimit: 500}), notifySpy = jasmine.createSpy('notifySpy') deferredComputed.subscribe(notifySpy) dependentComputed.subscribe(notifySpy) expect(dependentComputed()).toEqual('RA') data('B') expect(deferredComputed()).toEqual('B') expect(dependentComputed()).toEqual('RB') expect(notifySpy).not.toHaveBeenCalled() // no notifications yet jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([ ['B'] ]) // only the deferred computed notifies initially jasmine.Clock.tick(499) expect(notifySpy.argsForCall).toEqual([ ['B'], [ 'RB' ] ]) // the rate-limited computed notifies after the specified timeout }) it('Should minimize evaluation at the end of a complex graph', function () { this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var a = koObservable('a'), b = koPureComputed(function b () { return 'b' + a() }), c = koPureComputed(function c () { return 'c' + a() }), d = koPureComputed(function d () { return 'd(' + b() + ',' + c() + ')' }), e = koPureComputed(function e () { return 'e' + a() }), f = koPureComputed(function f () { return 'f' + a() }), g = koPureComputed(function g () { return 'g(' + e() + ',' + f() + ')' }), h = koPureComputed(function h () { return 'h(' + c() + ',' + g() + ',' + d() + ')' }), i = koPureComputed(function i () { return 'i(' + a() + ',' + h() + ',' + b() + ',' + f() + ')' }).extend({notify: 'always'}), // ensure we get a notification for each evaluation notifySpy = jasmine.createSpy('callback') i.subscribe(notifySpy) a('x') jasmine.Clock.tick(1) expect(notifySpy.argsForCall).toEqual([['i(x,h(cx,g(ex,fx),d(bx,cx)),bx,fx)']]) // only one evaluation and notification }) it('Should minimize evaluation when dependent computed doesn\'t actually change', function () { // From https://github.com/knockout/knockout/issues/2174 this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true const source = koObservable({ key: 'value' }) const c1 = koComputed(() => source()['key']) let countEval = 0 const c2 = koComputed(() => ++countEval && c1()) source({ key: 'value' }) jasmine.Clock.tick(1) expect(countEval).toEqual(1) // Reading it again shouldn't cause an update expect(c2()).toEqual(c1()) expect(countEval).toEqual(1) }) it('Should ignore recursive dirty events', function () { // From https://github.com/knockout/knockout/issues/1943 this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var a = koObservable(), b = koComputed({ read: function () { a(); return d() }, deferEvaluation: true }), d = koComputed({ read: function () { a(); return b() }, deferEvaluation: true }), bSpy = jasmine.createSpy('bSpy'), dSpy = jasmine.createSpy('dSpy') b.subscribe(bSpy, null, 'dirty') d.subscribe(dSpy, null, 'dirty') d() expect(bSpy).not.toHaveBeenCalled() expect(dSpy).not.toHaveBeenCalled() a('something') expect(bSpy.calls.length).toBe(2) // 1 for a, and 1 for d expect(dSpy.calls.length).toBe(2) // 1 for a, and 1 for b jasmine.Clock.tick(1) }) it('Should only notify changes if computed was evaluated', function () { // See https://github.com/knockout/knockout/issues/2240 // Set up a scenario where a computed will be marked as dirty but won't get marked as // stale and so won't be re-evaluated this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var obs = koObservable('somevalue'), isTruthy = koPureComputed(function () { return !!obs() }), objIfTruthy = koPureComputed(function () { return isTruthy() }).extend({ notify: 'always' }), notifySpy = jasmine.createSpy('callback'), subscription = objIfTruthy.subscribe(notifySpy) obs('someothervalue') jasmine.Clock.tick(1) expect(notifySpy).not.toHaveBeenCalled() obs('') jasmine.Clock.tick(1) expect(notifySpy).toHaveBeenCalled() expect(notifySpy.argsForCall).toEqual([[false]]) notifySpy.reset() obs(undefined) jasmine.Clock.tick(1) expect(notifySpy).not.toHaveBeenCalled() }) }) describe('ko.when', function () { it('Runs callback in a sepearate task when predicate function becomes true, but only once', function () { this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var x = koObservable(3), called = 0 when(() => x() === 4, () => called++) x(5) expect(called).toBe(0) expect(x.getSubscriptionsCount()).toBe(1) x(4) expect(called).toBe(0) jasmine.Clock.tick(1) expect(called).toBe(1) expect(x.getSubscriptionsCount()).toBe(0) x(3) x(4) jasmine.Clock.tick(1) expect(called).toBe(1) expect(x.getSubscriptionsCount()).toBe(0) }) it('Runs callback in a sepearate task if predicate function is already true', function () { this.restoreAfter(options, 'deferUpdates') options.deferUpdates = true var x = koObservable(4), called = 0 when(() => x() === 4, () => called++) expect(called).toBe(0) expect(x.getSubscriptionsCount()).toBe(1) jasmine.Clock.tick(1) expect(called).toBe(1) expect(x.getSubscriptionsCount()).toBe(0) x(3) x(4) jasmine.Clock.tick(1) expect(called).toBe(1) expect(x.getSubscriptionsCount()).toBe(0) }) }) })
the_stack
import { sandbox } from './helpers' import { createNext } from 'e2e-utils' import { NextInstance } from 'test/lib/next-modes/base' import { check } from 'next-test-utils' describe('ReactRefreshLogBox', () => { let next: NextInstance beforeAll(async () => { next = await createNext({ files: {}, skipStart: true, }) }) afterAll(() => next.destroy()) test('logbox: can recover from a syntax error without losing state', async () => { const { session, cleanup } = await sandbox(next) await session.patch( 'index.js', ` import { useCallback, useState } from 'react' export default function Index() { const [count, setCount] = useState(0) const increment = useCallback(() => setCount(c => c + 1), [setCount]) return ( <main> <p>{count}</p> <button onClick={increment}>Increment</button> </main> ) } ` ) await session.evaluate(() => document.querySelector('button').click()) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('1') await session.patch('index.js', `export default () => <div/`) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() await session.patch( 'index.js', ` import { useCallback, useState } from 'react' export default function Index() { const [count, setCount] = useState(0) const increment = useCallback(() => setCount(c => c + 1), [setCount]) return ( <main> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </main> ) } ` ) await check( () => session.evaluate(() => document.querySelector('p').textContent), /Count: 1/ ) expect(await session.hasRedbox()).toBe(false) await cleanup() }) test('logbox: can recover from a event handler error', async () => { const { session, cleanup } = await sandbox(next) await session.patch( 'index.js', ` import { useCallback, useState } from 'react' export default function Index() { const [count, setCount] = useState(0) const increment = useCallback(() => { setCount(c => c + 1) throw new Error('oops') }, [setCount]) return ( <main> <p>{count}</p> <button onClick={increment}>Increment</button> </main> ) } ` ) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('0') await session.evaluate(() => document.querySelector('button').click()) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('1') expect(await session.hasRedbox(true)).toBe(true) if (process.platform === 'win32') { expect(await session.getRedboxSource()).toMatchSnapshot() } else { expect(await session.getRedboxSource()).toMatchSnapshot() } await session.patch( 'index.js', ` import { useCallback, useState } from 'react' export default function Index() { const [count, setCount] = useState(0) const increment = useCallback(() => setCount(c => c + 1), [setCount]) return ( <main> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </main> ) } ` ) expect(await session.hasRedbox()).toBe(false) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('Count: 1') await session.evaluate(() => document.querySelector('button').click()) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('Count: 2') expect(await session.hasRedbox()).toBe(false) await cleanup() }) test('logbox: can recover from a component error', async () => { const { session, cleanup } = await sandbox(next) await session.write( 'child.js', ` export default function Child() { return <p>Hello</p>; } ` ) await session.patch( 'index.js', ` import Child from './child' export default function Index() { return ( <main> <Child /> </main> ) } ` ) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('Hello') await session.patch( 'child.js', ` // hello export default function Child() { throw new Error('oops') } ` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() const didNotReload = await session.patch( 'child.js', ` export default function Child() { return <p>Hello</p>; } ` ) expect(didNotReload).toBe(true) expect(await session.hasRedbox()).toBe(false) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('Hello') await cleanup() }) // https://github.com/pmmmwh/react-refresh-webpack-plugin/pull/3#issuecomment-554137262 test('render error not shown right after syntax error', async () => { const { session, cleanup } = await sandbox(next) // Starting here: await session.patch( 'index.js', ` import * as React from 'react'; class ClassDefault extends React.Component { render() { return <h1>Default Export</h1>; } } export default ClassDefault; ` ) expect( await session.evaluate(() => document.querySelector('h1').textContent) ).toBe('Default Export') // Break it with a syntax error: await session.patch( 'index.js', ` import * as React from 'react'; class ClassDefault extends React.Component { render() return <h1>Default Export</h1>; } } export default ClassDefault; ` ) expect(await session.hasRedbox(true)).toBe(true) // Now change the code to introduce a runtime error without fixing the syntax error: await session.patch( 'index.js', ` import * as React from 'react'; class ClassDefault extends React.Component { render() throw new Error('nooo'); return <h1>Default Export</h1>; } } export default ClassDefault; ` ) expect(await session.hasRedbox(true)).toBe(true) // Now fix the syntax error: await session.patch( 'index.js', ` import * as React from 'react'; class ClassDefault extends React.Component { render() { throw new Error('nooo'); return <h1>Default Export</h1>; } } export default ClassDefault; ` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() await cleanup() }) // https://github.com/pmmmwh/react-refresh-webpack-plugin/pull/3#issuecomment-554137807 test('module init error not shown', async () => { // Start here: const { session, cleanup } = await sandbox(next) // We start here. await session.patch( 'index.js', ` import * as React from 'react'; class ClassDefault extends React.Component { render() { return <h1>Default Export</h1>; } } export default ClassDefault; ` ) expect( await session.evaluate(() => document.querySelector('h1').textContent) ).toBe('Default Export') // Add a throw in module init phase: await session.patch( 'index.js', ` // top offset for snapshot import * as React from 'react'; throw new Error('no') class ClassDefault extends React.Component { render() { return <h1>Default Export</h1>; } } export default ClassDefault; ` ) expect(await session.hasRedbox(true)).toBe(true) if (process.platform === 'win32') { expect(await session.getRedboxSource()).toMatchSnapshot() } else { expect(await session.getRedboxSource()).toMatchSnapshot() } await cleanup() }) // https://github.com/pmmmwh/react-refresh-webpack-plugin/pull/3#issuecomment-554144016 test('stuck error', async () => { const { session, cleanup } = await sandbox(next) // We start here. await session.patch( 'index.js', ` import * as React from 'react'; function FunctionDefault() { return <h1>Default Export Function</h1>; } export default FunctionDefault; ` ) // We add a new file. Let's call it Foo.js. await session.write( 'Foo.js', ` // intentionally skips export export default function Foo() { return React.createElement('h1', null, 'Foo'); } ` ) // We edit our first file to use it. await session.patch( 'index.js', ` import * as React from 'react'; import Foo from './Foo'; function FunctionDefault() { return <Foo />; } export default FunctionDefault; ` ) // We get an error because Foo didn't import React. Fair. expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() // Let's add that to Foo. await session.patch( 'Foo.js', ` import * as React from 'react'; export default function Foo() { return React.createElement('h1', null, 'Foo'); } ` ) // Expected: this fixes the problem expect(await session.hasRedbox()).toBe(false) await cleanup() }) // https://github.com/pmmmwh/react-refresh-webpack-plugin/pull/3#issuecomment-554150098 test('syntax > runtime error', async () => { const { session, cleanup } = await sandbox(next) // Start here. await session.patch( 'index.js', ` import * as React from 'react'; export default function FunctionNamed() { return <div /> } ` ) // TODO: this acts weird without above step await session.patch( 'index.js', ` import * as React from 'react'; let i = 0 setInterval(() => { i++ throw Error('no ' + i) }, 1000) export default function FunctionNamed() { return <div /> } ` ) await new Promise((resolve) => setTimeout(resolve, 1000)) expect(await session.hasRedbox(true)).toBe(true) if (process.platform === 'win32') { expect(await session.getRedboxSource()).toMatchSnapshot() } else { expect(await session.getRedboxSource()).toMatchSnapshot() } // Make a syntax error. await session.patch( 'index.js', ` import * as React from 'react'; let i = 0 setInterval(() => { i++ throw Error('no ' + i) }, 1000) export default function FunctionNamed() {` ) await new Promise((resolve) => setTimeout(resolve, 1000)) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() // Test that runtime error does not take over: await new Promise((resolve) => setTimeout(resolve, 2000)) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() await cleanup() }) // https://github.com/pmmmwh/react-refresh-webpack-plugin/pull/3#issuecomment-554152127 test('boundaries', async () => { const { session, cleanup } = await sandbox(next) await session.write( 'FunctionDefault.js', ` export default function FunctionDefault() { return <h2>hello</h2> } ` ) await session.patch( 'index.js', ` import FunctionDefault from './FunctionDefault.js' import * as React from 'react' class ErrorBoundary extends React.Component { constructor() { super() this.state = { hasError: false, error: null }; } static getDerivedStateFromError(error) { return { hasError: true, error }; } render() { if (this.state.hasError) { return this.props.fallback; } return this.props.children; } } function App() { return ( <ErrorBoundary fallback={<h2>error</h2>}> <FunctionDefault /> </ErrorBoundary> ); } export default App; ` ) expect( await session.evaluate(() => document.querySelector('h2').textContent) ).toBe('hello') await session.write( 'FunctionDefault.js', `export default function FunctionDefault() { throw new Error('no'); }` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() expect( await session.evaluate(() => document.querySelector('h2').textContent) ).toBe('error') await cleanup() }) // TODO: investigate why this fails when running outside of the Next.js // monorepo e.g. fails when using yarn create next-app // https://github.com/vercel/next.js/pull/23203 test.skip('internal package errors', async () => { const { session, cleanup } = await sandbox(next) // Make a react build-time error. await session.patch( 'index.js', ` export default function FunctionNamed() { return <div>{{}}</div> }` ) expect(await session.hasRedbox(true)).toBe(true) // We internally only check the script path, not including the line number // and error message because the error comes from an external library. // This test ensures that the errored script path is correctly resolved. expect(await session.getRedboxSource()).toContain( `../../../../packages/next/dist/pages/_document.js` ) await cleanup() }) test('unterminated JSX', async () => { const { session, cleanup } = await sandbox(next) await session.patch( 'index.js', ` export default () => { return ( <div> <p>lol</p> </div> ) } ` ) expect(await session.hasRedbox()).toBe(false) await session.patch( 'index.js', ` export default () => { return ( <div> <p>lol</p> div ) } ` ) expect(await session.hasRedbox(true)).toBe(true) const source = await session.getRedboxSource() expect(source).toMatchSnapshot() await cleanup() }) // Module trace is only available with webpack 5 test('conversion to class component (1)', async () => { const { session, cleanup } = await sandbox(next) await session.write( 'Child.js', ` export default function ClickCount() { return <p>hello</p> } ` ) await session.patch( 'index.js', ` import Child from './Child'; export default function Home() { return ( <div> <Child /> </div> ) } ` ) expect(await session.hasRedbox()).toBe(false) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('hello') await session.patch( 'Child.js', ` import { Component } from 'react'; export default class ClickCount extends Component { render() { throw new Error() } } ` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxSource()).toMatchSnapshot() await session.patch( 'Child.js', ` import { Component } from 'react'; export default class ClickCount extends Component { render() { return <p>hello new</p> } } ` ) expect(await session.hasRedbox()).toBe(false) expect( await session.evaluate(() => document.querySelector('p').textContent) ).toBe('hello new') await cleanup() }) test('css syntax errors', async () => { const { session, cleanup } = await sandbox(next) await session.write('index.module.css', `.button {}`) await session.patch( 'index.js', ` import './index.module.css'; export default () => { return ( <div> <p>lol</p> </div> ) } ` ) expect(await session.hasRedbox()).toBe(false) // Syntax error await session.patch('index.module.css', `.button {`) expect(await session.hasRedbox(true)).toBe(true) const source = await session.getRedboxSource() expect(source).toMatch('./index.module.css:1:1') expect(source).toMatch('Syntax error: ') expect(source).toMatch('Unclosed block') expect(source).toMatch('> 1 | .button {') expect(source).toMatch(' | ^') // Not local error await session.patch('index.module.css', `button {}`) expect(await session.hasRedbox(true)).toBe(true) const source2 = await session.getRedboxSource() expect(source2).toMatchSnapshot() await cleanup() }) test('logbox: anchors links in error messages', async () => { const { session, cleanup } = await sandbox(next) await session.patch( 'index.js', ` import { useCallback } from 'react' export default function Index() { const boom = useCallback(() => { throw new Error('end http://nextjs.org') }, []) return ( <main> <button onClick={boom}>Boom!</button> </main> ) } ` ) expect(await session.hasRedbox()).toBe(false) await session.evaluate(() => document.querySelector('button').click()) expect(await session.hasRedbox(true)).toBe(true) const header = await session.getRedboxDescription() expect(header).toMatchSnapshot() expect( await session.evaluate( () => document .querySelector('body > nextjs-portal') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .length ) ).toBe(1) expect( await session.evaluate( () => ( document .querySelector('body > nextjs-portal') .shadowRoot.querySelector( '#nextjs__container_errors_desc a:nth-of-type(1)' ) as any ).href ) ).toMatchSnapshot() await session.patch( 'index.js', ` import { useCallback } from 'react' export default function Index() { const boom = useCallback(() => { throw new Error('http://nextjs.org start') }, []) return ( <main> <button onClick={boom}>Boom!</button> </main> ) } ` ) expect(await session.hasRedbox()).toBe(false) await session.evaluate(() => document.querySelector('button').click()) expect(await session.hasRedbox(true)).toBe(true) const header2 = await session.getRedboxDescription() expect(header2).toMatchSnapshot() expect( await session.evaluate( () => document .querySelector('body > nextjs-portal') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .length ) ).toBe(1) expect( await session.evaluate( () => ( document .querySelector('body > nextjs-portal') .shadowRoot.querySelector( '#nextjs__container_errors_desc a:nth-of-type(1)' ) as any ).href ) ).toMatchSnapshot() await session.patch( 'index.js', ` import { useCallback } from 'react' export default function Index() { const boom = useCallback(() => { throw new Error('middle http://nextjs.org end') }, []) return ( <main> <button onClick={boom}>Boom!</button> </main> ) } ` ) expect(await session.hasRedbox()).toBe(false) await session.evaluate(() => document.querySelector('button').click()) expect(await session.hasRedbox(true)).toBe(true) const header3 = await session.getRedboxDescription() expect(header3).toMatchSnapshot() expect( await session.evaluate( () => document .querySelector('body > nextjs-portal') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .length ) ).toBe(1) expect( await session.evaluate( () => ( document .querySelector('body > nextjs-portal') .shadowRoot.querySelector( '#nextjs__container_errors_desc a:nth-of-type(1)' ) as any ).href ) ).toMatchSnapshot() await session.patch( 'index.js', ` import { useCallback } from 'react' export default function Index() { const boom = useCallback(() => { throw new Error('multiple http://nextjs.org links http://example.com') }, []) return ( <main> <button onClick={boom}>Boom!</button> </main> ) } ` ) expect(await session.hasRedbox()).toBe(false) await session.evaluate(() => document.querySelector('button').click()) expect(await session.hasRedbox(true)).toBe(true) const header4 = await session.getRedboxDescription() expect(header4).toMatchInlineSnapshot( `"Error: multiple http://nextjs.org links http://example.com"` ) expect( await session.evaluate( () => document .querySelector('body > nextjs-portal') .shadowRoot.querySelectorAll('#nextjs__container_errors_desc a') .length ) ).toBe(2) expect( await session.evaluate( () => ( document .querySelector('body > nextjs-portal') .shadowRoot.querySelector( '#nextjs__container_errors_desc a:nth-of-type(1)' ) as any ).href ) ).toMatchSnapshot() expect( await session.evaluate( () => ( document .querySelector('body > nextjs-portal') .shadowRoot.querySelector( '#nextjs__container_errors_desc a:nth-of-type(2)' ) as any ).href ) ).toMatchSnapshot() await cleanup() }) test('non-Error errors are handled properly', async () => { const { session, cleanup } = await sandbox(next) await session.patch( 'index.js', ` export default () => { throw {'a': 1, 'b': 'x'}; return ( <div>hello</div> ) } ` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxDescription()).toMatchInlineSnapshot( `"Error: {\\"a\\":1,\\"b\\":\\"x\\"}"` ) // fix previous error await session.patch( 'index.js', ` export default () => { return ( <div>hello</div> ) } ` ) expect(await session.hasRedbox(false)).toBe(false) await session.patch( 'index.js', ` class Hello {} export default () => { throw Hello return ( <div>hello</div> ) } ` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxDescription()).toContain( `Error: class Hello {` ) // fix previous error await session.patch( 'index.js', ` export default () => { return ( <div>hello</div> ) } ` ) expect(await session.hasRedbox(false)).toBe(false) await session.patch( 'index.js', ` export default () => { throw "string error" return ( <div>hello</div> ) } ` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxDescription()).toMatchInlineSnapshot( `"Error: string error"` ) // fix previous error await session.patch( 'index.js', ` export default () => { return ( <div>hello</div> ) } ` ) expect(await session.hasRedbox(false)).toBe(false) await session.patch( 'index.js', ` export default () => { throw null return ( <div>hello</div> ) } ` ) expect(await session.hasRedbox(true)).toBe(true) expect(await session.getRedboxDescription()).toContain( `Error: A null error was thrown` ) await cleanup() }) })
the_stack
declare namespace Kakao { const VERSION: string; function cleanup(): void; function init(appKey: string): void; function isInitialized(): boolean; namespace API { interface ApiError { code: number; msg: string; } interface ApiResponse { [key: string]: any; } // api responses function cleanup(): void; type RequestSuccessCallback = (response: ApiResponse) => void; type RequestFailCallback = (error: ApiError) => void; type RequestAlwaysCallback = (param: ApiResponse | ApiError) => void; /** * request Kakao API * API Referehce: https://developers.kakao.com/docs/latest/ko/reference/rest-api-reference */ function request(settings: { url: string; // Kakao REST API urls data?: { [key: string]: any; } | undefined; files?: FileList | File[] | Blob[] | undefined; success?: RequestSuccessCallback | undefined; fail?: RequestFailCallback | undefined; always?: RequestAlwaysCallback | undefined; }): Promise<ApiResponse>; } namespace Auth { type AuthLanguage = 'kr' | 'en'; type AuthButtonSize = 'small' | 'medium' | 'large'; interface AuthStatusObject { status: 'connected' | 'not_connected'; user?: { [key: string]: any; } | undefined; } interface AuthSuccessObject { access_token: string; refresh_token: string; token_type: string; // fixed 'bearer' expires_in: number; scope: string; } interface AuthError { error: string; error_description: string; } /** * version 1.39.16, * if autoLogin is true and user agent has not string 'KAKAOTALK', return false * but authorize function has not other return, so return type set void */ function authorize(settings: { redirectUri?: string | undefined; state?: string | undefined; scope?: string | undefined; // additional agreement key ex) account_email,gender throughTalk?: boolean | undefined; // default true, prompts?: string | undefined; }): void; function cleanup(): void; function createLoginButton(settings: { container: string | HTMLElement; lang?: AuthLanguage | undefined; // default 'kr' size?: AuthButtonSize | undefined; // default 'medium' success?: ((authObj: AuthSuccessObject) => void) | undefined; fail?: ((errorObj: AuthError) => void) | undefined; always?: ((param: AuthSuccessObject | AuthError) => void) | undefined; scope?: string | undefined; // additional agreement key ex) account_email,gender persistAccessToken?: boolean | undefined; // default true throughTalk?: boolean | undefined; // default true }): void; function getAccessToken(): string; function getAppKey(): string; /** * @deprecated */ function getRefreshToken(): void; function getStatusInfo(callback: (object: AuthStatusObject) => void): void; function login(settings: { success?: ((authObj: AuthSuccessObject) => void) | undefined; fail?: ((errorObj: AuthError) => void) | undefined; always?: ((param: AuthSuccessObject | AuthError) => void) | undefined; scope?: string | undefined; // additional agreement key ex) account_email,gender persistAccessToken?: boolean | undefined; // default true throughTalk?: boolean | undefined; // default true }): void; function loginForm(settings: { success?: ((authObj: AuthSuccessObject) => void) | undefined; fail?: ((errorObj: AuthError) => void) | undefined; always?: ((param: AuthSuccessObject | AuthError) => void) | undefined; scope?: string | undefined; // additional agreement key ex) account_email,gender persistAccessToken?: boolean | undefined; // default true }): void; /** * logout function callback param is always true * but reference writen just function * so callback typing void function: () => void */ function logout(callback: () => void): void; function setAccessToken(token: string | null, persist?: boolean): void; // persist default true /** * @deprecated */ function setRefreshToken(): void; } namespace Channel { type ButtonSize = 'small' | 'large'; type TitleText = 'consult' | 'question'; type Color = 'yellow' | 'black'; type Shape = 'pc' | 'mobile'; function addChannel(settings: { channelPublicId: string }): void; function chat(settings: { channelPublicId: string }): void; function cleanup(): void; function createAddChannelButton(settings: { container: string | HTMLElement; channelPublicId: string; size?: ButtonSize | undefined; // default 'small' supportMultipleDensities?: boolean | undefined; // default false }): void; function createChatButton(settings: { container: string | HTMLElement; channelPublicId: string; title?: string | undefined; // default 'consult' size?: ButtonSize | undefined; // default 'small' color?: Color | undefined; // default 'yellow' shape?: Shape | undefined; // default 'pc' supportMultipleDensities?: boolean | undefined; // default false }): void; } namespace Link { type LinkCallback = (...args: any[]) => any; interface ButtonObject { title: string; link: LinkObject; } interface CommerceObject { regularPrice: number; productName?: string | undefined; discountPrice?: number | undefined; discountRate?: number | undefined; fixedDiscountPrice?: number | undefined; } interface ContentObject { title: string; imageUrl: string; link: LinkObject; imageWidth?: number | undefined; imageHeight?: number | undefined; description?: string | undefined; } interface BaseObject<ObjectType extends string> { objectType: ObjectType; buttonTitle?: string | undefined; buttons?: ButtonObject[] | undefined; installTalk?: boolean | undefined; // default false callback?: LinkCallback | undefined; serverCallbackArgs?: | { [key: string]: any; } | string | undefined; // reference https://developers.kakao.com/docs/latest/ko/message/js#set-kakaolink-callback } interface DefaultCommerceSettings extends BaseObject<'commerce'> { content: ContentObject; commerce: CommerceObject; } interface DefaultFeedSettings extends BaseObject<'feed'> { content: ContentObject; social?: SocialObject | undefined; } interface DefaultListSettings extends BaseObject<'list'> { headerTitle: string; headerLink: LinkObject; contents: ContentObject[]; } interface DefaultLocationSettings extends BaseObject<'location'> { content: ContentObject; address: string; addressTitle?: string | undefined; social?: SocialObject | undefined; } interface DefaultTextSettings extends BaseObject<'text'> { text: string; link: LinkObject; } interface ImageInfos { original: { url: string; length: number; content_type: string; width: number; height: number; }; } interface LinkObject { webUrl?: string | undefined; mobileWebUrl?: string | undefined; androidExecParams?: string | undefined; iosExecParams?: string | undefined; } interface SocialObject { likeCount?: number | undefined; commentCount?: number | undefined; sharedCount?: number | undefined; viewCount?: number | undefined; subscriberCount?: number | undefined; } type DefaultSettings = | DefaultFeedSettings | DefaultListSettings | DefaultLocationSettings | DefaultCommerceSettings | DefaultTextSettings; function cleanup(): void; function createCustomButton(settings: { container: string | HTMLElement; templateId: number; templateArgs?: { [key: string]: any; } | undefined; installTalk?: boolean | undefined; // default false callback?: LinkCallback | undefined; serverCallbackArgs?: | { [key: string]: any; } | string | undefined; // reference https://developers.kakao.com/docs/latest/ko/message/js#set-kakaolink-callback }): void; function createDefaultButton( settings: { container: string | HTMLElement; } & DefaultSettings, ): void; function createScrapButton(settings: { container: string | HTMLElement; requestUrl: string; templateId?: number | undefined; templateArgs?: { [key: string]: any; } | undefined; installTalk?: boolean | undefined; // default false callback?: LinkCallback | undefined; serverCallbackArgs?: | { [key: string]: any; } | string | undefined; }): void; function deleteImage(settings: { imageUrl: string }): Promise<unknown>; function scrapImage(settings: { imageUrl: string }): Promise<ImageInfos>; function sendCustom(settings: { templateId: number; templateArgs: { [key: string]: any; }; installTalk?: boolean | undefined; // default false callback?: LinkCallback | undefined; serverCallbackArgs?: | { [key: string]: any; } | string | undefined; }): void; function sendDefault(settings: DefaultSettings): void; function sendScrap(settings: { requestUrl: string; templateId?: number | undefined; templateArgs?: { [key: string]: any; } | undefined; installTalk?: boolean | undefined; // default false callback?: LinkCallback | undefined; serverCallbackArgs?: | { [key: string]: any; } | string | undefined; }): void; function uploadImage(settings: { file: FileList }): Promise<ImageInfos>; } namespace Navi { interface ViaPoint { name: string; x: number; y: number; } function share(settings: { name: string; x: number; y: number; coordType?: string | undefined; // default 'katec', union type 'wgs84' | 'katec' }): void; // Reference: https://developers.kakao.com/sdk/reference/js/release/Kakao.Navi.html#.start function start(settings: { name: string; x: number; y: number; coordType?: string | undefined; // default 'katec', union type 'wgs84' | 'katec'; vehicleType?: number | undefined; // default 1, rpOptio?: number | undefined; // default 100 routeInfo?: boolean | undefined; // default false sX?: number | undefined; sY?: number | undefined; sAngle?: number | undefined; returnUri?: string | undefined; viaPoints?: ViaPoint[] | undefined; }): void; } namespace Story { function cleanup(): void; function createFollowButton(settings: { container: string | HTMLElement; id: string; showFollowerCount?: boolean | undefined; // default true; type?: string | undefined; // default 'horizontal' }): void; function createShareButton(settings: { container: string | HTMLElement; url?: string | undefined; text?: string | undefined; // default '' }): void; function open(settings: { install?: boolean | undefined; url?: string | undefined; text?: string | undefined; urlInfo?: { title: string; desc?: string | undefined; name?: string | undefined; images?: string[] | undefined; } | undefined; }): void; function share(settings: { url?: string | undefined; text?: string | undefined; // default '' }): void; } }
the_stack
import { HassEntities, HassEntity } from "home-assistant-js-websocket"; import { LatLngTuple } from "leaflet"; import { css, CSSResultGroup, html, LitElement, PropertyValues, TemplateResult, } from "lit"; import { customElement, property, query, state } from "lit/decorators"; import { mdiImageFilterCenterFocus } from "@mdi/js"; import memoizeOne from "memoize-one"; import { computeDomain } from "../../../common/entity/compute_domain"; import parseAspectRatio from "../../../common/util/parse-aspect-ratio"; import "../../../components/ha-card"; import "../../../components/ha-icon-button"; import { fetchRecent } from "../../../data/history"; import { HomeAssistant } from "../../../types"; import { findEntities } from "../common/find-entities"; import { processConfigEntities } from "../common/process-config-entities"; import { EntityConfig } from "../entity-rows/types"; import { LovelaceCard } from "../types"; import { MapCardConfig } from "./types"; import "../../../components/map/ha-map"; import type { HaMap, HaMapPaths } from "../../../components/map/ha-map"; import { getColorByIndex } from "../../../common/color/colors"; const MINUTE = 60000; @customElement("hui-map-card") class HuiMapCard extends LitElement implements LovelaceCard { @property({ attribute: false }) public hass!: HomeAssistant; @property({ type: Boolean, reflect: true }) public isPanel = false; @state() private _history?: HassEntity[][]; @state() private _config?: MapCardConfig; @query("ha-map") private _map?: HaMap; private _date?: Date; private _configEntities?: string[]; private _colorDict: Record<string, string> = {}; private _colorIndex = 0; public setConfig(config: MapCardConfig): void { if (!config) { throw new Error("Error in card configuration."); } if (!config.entities?.length && !config.geo_location_sources) { throw new Error( "Either entities or geo_location_sources must be specified" ); } if (config.entities && !Array.isArray(config.entities)) { throw new Error("Entities need to be an array"); } if ( config.geo_location_sources && !Array.isArray(config.geo_location_sources) ) { throw new Error("Geo_location_sources needs to be an array"); } this._config = config; this._configEntities = ( config.entities ? processConfigEntities<EntityConfig>(config.entities) : [] ).map((entity) => entity.entity); this._cleanupHistory(); } public getCardSize(): number { if (!this._config?.aspect_ratio) { return 7; } const ratio = parseAspectRatio(this._config.aspect_ratio); const ar = ratio && ratio.w > 0 && ratio.h > 0 ? `${((100 * ratio.h) / ratio.w).toFixed(2)}` : "100"; return 1 + Math.floor(Number(ar) / 25) || 3; } public static async getConfigElement() { await import("../editor/config-elements/hui-map-card-editor"); return document.createElement("hui-map-card-editor"); } public static getStubConfig( hass: HomeAssistant, entities: string[], entitiesFallback: string[] ): MapCardConfig { const includeDomains = ["device_tracker"]; const maxEntities = 2; const foundEntities = findEntities( hass, maxEntities, entities, entitiesFallback, includeDomains ); return { type: "map", entities: foundEntities }; } protected render(): TemplateResult { if (!this._config) { return html``; } return html` <ha-card id="card" .header=${this._config.title}> <div id="root"> <ha-map .hass=${this.hass} .entities=${this._getEntities( this.hass.states, this._config, this._configEntities )} .zoom=${this._config.default_zoom ?? 14} .paths=${this._getHistoryPaths(this._config, this._history)} .darkMode=${this._config.dark_mode} ></ha-map> <ha-icon-button .label=${this.hass!.localize( "ui.panel.lovelace.cards.map.reset_focus" )} .path=${mdiImageFilterCenterFocus} @click=${this._fitMap} tabindex="0" ></ha-icon-button> </div> </ha-card> `; } protected shouldUpdate(changedProps: PropertyValues) { if (!changedProps.has("hass") || changedProps.size > 1) { return true; } const oldHass = changedProps.get("hass") as HomeAssistant | undefined; if (!oldHass || !this._configEntities) { return true; } if (oldHass.themes.darkMode !== this.hass.themes.darkMode) { return true; } // Check if any state has changed for (const entity of this._configEntities) { if (oldHass.states[entity] !== this.hass!.states[entity]) { return true; } } return false; } protected firstUpdated(changedProps: PropertyValues): void { super.firstUpdated(changedProps); const root = this.shadowRoot!.getElementById("root"); if (!this._config || this.isPanel || !root) { return; } if (!this._config.aspect_ratio) { root.style.paddingBottom = "100%"; return; } const ratio = parseAspectRatio(this._config.aspect_ratio); root.style.paddingBottom = ratio && ratio.w > 0 && ratio.h > 0 ? `${((100 * ratio.h) / ratio.w).toFixed(2)}%` : (root.style.paddingBottom = "100%"); } protected updated(changedProps: PropertyValues): void { if (this._config?.hours_to_show && this._configEntities?.length) { if (changedProps.has("_config")) { this._getHistory(); } else if (Date.now() - this._date!.getTime() >= MINUTE) { this._getHistory(); } } } private _fitMap() { this._map?.fitMap(); } private _getColor(entityId: string): string { let color = this._colorDict[entityId]; if (color) { return color; } color = getColorByIndex(this._colorIndex); this._colorIndex++; this._colorDict[entityId] = color; return color; } private _getEntities = memoizeOne( ( states: HassEntities, config: MapCardConfig, configEntities?: string[] ) => { if (!states || !config) { return undefined; } let entities = configEntities || []; if (config.geo_location_sources) { const geoEntities: string[] = []; // Calculate visible geo location sources const includesAll = config.geo_location_sources.includes("all"); for (const stateObj of Object.values(states)) { if ( computeDomain(stateObj.entity_id) === "geo_location" && (includesAll || config.geo_location_sources.includes(stateObj.attributes.source)) ) { geoEntities.push(stateObj.entity_id); } } entities = [...entities, ...geoEntities]; } return entities.map((entity) => ({ entity_id: entity, color: this._getColor(entity), })); } ); private _getHistoryPaths = memoizeOne( ( config: MapCardConfig, history?: HassEntity[][] ): HaMapPaths[] | undefined => { if (!config.hours_to_show || !history) { return undefined; } const paths: HaMapPaths[] = []; for (const entityStates of history) { if (entityStates?.length <= 1) { continue; } // filter location data from states and remove all invalid locations const points = entityStates.reduce( (accumulator: LatLngTuple[], entityState) => { const latitude = entityState.attributes.latitude; const longitude = entityState.attributes.longitude; if (latitude && longitude) { accumulator.push([latitude, longitude] as LatLngTuple); } return accumulator; }, [] ) as LatLngTuple[]; paths.push({ points, color: this._getColor(entityStates[0].entity_id), gradualOpacity: 0.8, }); } return paths; } ); private async _getHistory(): Promise<void> { this._date = new Date(); if (!this._configEntities) { return; } const entityIds = this._configEntities!.join(","); const endTime = new Date(); const startTime = new Date(); startTime.setHours(endTime.getHours() - this._config!.hours_to_show!); const skipInitialState = false; const significantChangesOnly = false; const minimalResponse = false; const stateHistory = await fetchRecent( this.hass, entityIds, startTime, endTime, skipInitialState, significantChangesOnly, minimalResponse ); if (stateHistory.length < 1) { return; } this._history = stateHistory; } private _cleanupHistory() { if (!this._history) { return; } if (this._config!.hours_to_show! <= 0) { this._history = undefined; } else { // remove unused entities this._history = this._history!.reduce( (accumulator: HassEntity[][], entityStates) => { const entityId = entityStates[0].entity_id; if (this._configEntities?.includes(entityId)) { accumulator.push(entityStates); } return accumulator; }, [] ) as HassEntity[][]; } } static get styles(): CSSResultGroup { return css` ha-card { overflow: hidden; width: 100%; height: 100%; } ha-map { z-index: 0; border: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: inherit; } ha-icon-button { position: absolute; top: 75px; left: 3px; outline: none; } #root { position: relative; } :host([ispanel]) #root { height: 100%; } `; } } declare global { interface HTMLElementTagNameMap { "hui-map-card": HuiMapCard; } }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type CollectionTestsQueryVariables = {}; export type CollectionTestsQueryResponse = { readonly marketingCollection: { readonly " $fragmentRefs": FragmentRefs<"Collection_collection">; } | null; }; export type CollectionTestsQuery = { readonly response: CollectionTestsQueryResponse; readonly variables: CollectionTestsQueryVariables; }; /* query CollectionTestsQuery { marketingCollection(slug: "doesn't matter") { ...Collection_collection id } } fragment ArtistListItem_artist on Artist { id internalID slug name initials href is_followed: isFollowed nationality birthday deathday image { url } } fragment ArtworkGridItem_artwork on Artwork { title date saleMessage slug internalID artistNames href sale { isAuction isClosed displayTimelyAt endAt id } saleArtwork { counts { bidderPositions } currentBid { display } lotLabel id } partner { name id } image { url(version: "large") aspectRatio } } fragment CollectionArtistSeriesRail_collection on MarketingCollection { slug id } fragment CollectionArtistSeriesRail_collectionGroup on MarketingCollectionGroup { name members { slug id title priceGuidance artworksConnection(first: 3, aggregations: [TOTAL], sort: "-decayed_merch") { edges { node { title image { url } id } } id } } } fragment CollectionArtworksFilter_collection on MarketingCollection { slug id } fragment CollectionArtworks_collection_ZORN9 on MarketingCollection { isDepartment slug id collectionArtworks: artworksConnection(first: 10, aggregations: [ARTIST, ARTIST_NATIONALITY, COLOR, DIMENSION_RANGE, LOCATION_CITY, MAJOR_PERIOD, MATERIALS_TERMS, MEDIUM, PARTNER, PRICE_RANGE], input: {sort: "-decayed_merch"}) { aggregations { slice counts { value name count } } counts { total } edges { node { id __typename } cursor } ...InfiniteScrollArtworksGrid_connection pageInfo { endCursor hasNextPage } id } } fragment CollectionHeader_collection on MarketingCollection { title headerImage descriptionMarkdown image: artworksConnection(sort: "-decayed_merch", first: 1) { edges { node { image { url(version: "larger") } id } } id } } fragment CollectionHubsRails_collection on MarketingCollection { ...CollectionArtistSeriesRail_collection ...FeaturedCollectionsRail_collection } fragment CollectionHubsRails_linkedCollections on MarketingCollectionGroup { groupType ...CollectionArtistSeriesRail_collectionGroup ...OtherCollectionsRail_collectionGroup ...FeaturedCollectionsRail_collectionGroup } fragment Collection_collection on MarketingCollection { id slug isDepartment ...CollectionHeader_collection ...CollectionArtworks_collection_ZORN9 ...CollectionArtworksFilter_collection ...FeaturedArtists_collection ...CollectionHubsRails_collection linkedCollections { ...CollectionHubsRails_linkedCollections } } fragment FeaturedArtists_collection on MarketingCollection { slug artworksConnection(aggregations: [MERCHANDISABLE_ARTISTS], size: 0, sort: "-decayed_merch") { merchandisableArtists(size: 4) { internalID ...ArtistListItem_artist id } id } query { artistIDs id } featuredArtistExclusionIds } fragment FeaturedCollectionsRail_collection on MarketingCollection { slug id } fragment FeaturedCollectionsRail_collectionGroup on MarketingCollectionGroup { name members { slug id title priceGuidance descriptionMarkdown featuredCollectionArtworks: artworksConnection(first: 1, aggregations: [TOTAL], sort: "-decayed_merch") { edges { node { image { url } id } } id } } } fragment InfiniteScrollArtworksGrid_connection on ArtworkConnectionInterface { __isArtworkConnectionInterface: __typename pageInfo { hasNextPage startCursor endCursor } edges { __typename node { slug id image { aspectRatio } ...ArtworkGridItem_artwork } ... on Node { __isNode: __typename id } } } fragment OtherCollectionsRail_collectionGroup on MarketingCollectionGroup { groupType name members { id slug title } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "slug", "value": "doesn't matter" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "descriptionMarkdown", "storageKey": null }, v5 = { "kind": "Literal", "name": "first", "value": 1 }, v6 = { "kind": "Literal", "name": "sort", "value": "-decayed_merch" }, v7 = [ { "kind": "Literal", "name": "aggregations", "value": [ "ARTIST", "ARTIST_NATIONALITY", "COLOR", "DIMENSION_RANGE", "LOCATION_CITY", "MAJOR_PERIOD", "MATERIALS_TERMS", "MEDIUM", "PARTNER", "PRICE_RANGE" ] }, { "kind": "Literal", "name": "first", "value": 10 }, { "kind": "Literal", "name": "input", "value": { "sort": "-decayed_merch" } } ], v8 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v9 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, v10 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v11 = { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, v12 = { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "url", "storageKey": null } ], "storageKey": null }, v13 = { "kind": "Literal", "name": "aggregations", "value": [ "TOTAL" ] }, v14 = { "enumValues": null, "nullable": true, "plural": false, "type": "FilterArtworksConnection" }, v15 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v16 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v17 = { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, v18 = { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }, v19 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v20 = { "enumValues": null, "nullable": true, "plural": false, "type": "FormattedNumber" }, v21 = { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, v22 = { "enumValues": null, "nullable": false, "plural": false, "type": "Boolean" }, v23 = { "enumValues": null, "nullable": true, "plural": true, "type": "String" }, v24 = { "enumValues": null, "nullable": true, "plural": true, "type": "FilterArtworksEdge" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "CollectionTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "MarketingCollection", "kind": "LinkedField", "name": "marketingCollection", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "Collection_collection" } ], "storageKey": "marketingCollection(slug:\"doesn't matter\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "CollectionTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "MarketingCollection", "kind": "LinkedField", "name": "marketingCollection", "plural": false, "selections": [ (v1/*: any*/), (v2/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "isDepartment", "storageKey": null }, (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "headerImage", "storageKey": null }, (v4/*: any*/), { "alias": "image", "args": [ (v5/*: any*/), (v6/*: any*/) ], "concreteType": "FilterArtworksConnection", "kind": "LinkedField", "name": "artworksConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "FilterArtworksEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "larger" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"larger\")" } ], "storageKey": null }, (v1/*: any*/) ], "storageKey": null } ], "storageKey": null }, (v1/*: any*/) ], "storageKey": "artworksConnection(first:1,sort:\"-decayed_merch\")" }, { "alias": "collectionArtworks", "args": (v7/*: any*/), "concreteType": "FilterArtworksConnection", "kind": "LinkedField", "name": "artworksConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "ArtworksAggregationResults", "kind": "LinkedField", "name": "aggregations", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "slice", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AggregationCount", "kind": "LinkedField", "name": "counts", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "value", "storageKey": null }, (v8/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "count", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "FilterArtworksCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "total", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "FilterArtworksEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v1/*: any*/), (v9/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null } ], "storageKey": null }, (v1/*: any*/), { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "startCursor", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ (v9/*: any*/), { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v2/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null }, { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "large" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"large\")" } ], "storageKey": null }, (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "saleMessage", "storageKey": null }, (v10/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, (v11/*: any*/), { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "isAuction", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isClosed", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "displayTimelyAt", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "endAt", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "SaleArtworkCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "bidderPositions", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lotLabel", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ (v8/*: any*/), (v1/*: any*/) ], "storageKey": null } ], "storageKey": null }, { "kind": "InlineFragment", "selections": [ (v1/*: any*/) ], "type": "Node", "abstractKey": "__isNode" } ], "storageKey": null } ], "type": "ArtworkConnectionInterface", "abstractKey": "__isArtworkConnectionInterface" } ], "storageKey": "artworksConnection(aggregations:[\"ARTIST\",\"ARTIST_NATIONALITY\",\"COLOR\",\"DIMENSION_RANGE\",\"LOCATION_CITY\",\"MAJOR_PERIOD\",\"MATERIALS_TERMS\",\"MEDIUM\",\"PARTNER\",\"PRICE_RANGE\"],first:10,input:{\"sort\":\"-decayed_merch\"})" }, { "alias": "collectionArtworks", "args": (v7/*: any*/), "filters": [ "aggregations", "input" ], "handle": "connection", "key": "Collection_collectionArtworks", "kind": "LinkedHandle", "name": "artworksConnection" }, { "alias": null, "args": [ { "kind": "Literal", "name": "aggregations", "value": [ "MERCHANDISABLE_ARTISTS" ] }, { "kind": "Literal", "name": "size", "value": 0 }, (v6/*: any*/) ], "concreteType": "FilterArtworksConnection", "kind": "LinkedField", "name": "artworksConnection", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "size", "value": 4 } ], "concreteType": "Artist", "kind": "LinkedField", "name": "merchandisableArtists", "plural": true, "selections": [ (v10/*: any*/), (v1/*: any*/), (v2/*: any*/), (v8/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "initials", "storageKey": null }, (v11/*: any*/), { "alias": "is_followed", "args": null, "kind": "ScalarField", "name": "isFollowed", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "nationality", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "birthday", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "deathday", "storageKey": null }, (v12/*: any*/) ], "storageKey": "merchandisableArtists(size:4)" }, (v1/*: any*/) ], "storageKey": "artworksConnection(aggregations:[\"MERCHANDISABLE_ARTISTS\"],size:0,sort:\"-decayed_merch\")" }, { "alias": null, "args": null, "concreteType": "MarketingCollectionQuery", "kind": "LinkedField", "name": "query", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "artistIDs", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "featuredArtistExclusionIds", "storageKey": null }, { "alias": null, "args": null, "concreteType": "MarketingCollectionGroup", "kind": "LinkedField", "name": "linkedCollections", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "groupType", "storageKey": null }, (v8/*: any*/), { "alias": null, "args": null, "concreteType": "MarketingCollection", "kind": "LinkedField", "name": "members", "plural": true, "selections": [ (v2/*: any*/), (v1/*: any*/), (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "priceGuidance", "storageKey": null }, { "alias": null, "args": [ (v13/*: any*/), { "kind": "Literal", "name": "first", "value": 3 }, (v6/*: any*/) ], "concreteType": "FilterArtworksConnection", "kind": "LinkedField", "name": "artworksConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "FilterArtworksEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v3/*: any*/), (v12/*: any*/), (v1/*: any*/) ], "storageKey": null } ], "storageKey": null }, (v1/*: any*/) ], "storageKey": "artworksConnection(aggregations:[\"TOTAL\"],first:3,sort:\"-decayed_merch\")" }, (v4/*: any*/), { "alias": "featuredCollectionArtworks", "args": [ (v13/*: any*/), (v5/*: any*/), (v6/*: any*/) ], "concreteType": "FilterArtworksConnection", "kind": "LinkedField", "name": "artworksConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "FilterArtworksEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v12/*: any*/), (v1/*: any*/) ], "storageKey": null } ], "storageKey": null }, (v1/*: any*/) ], "storageKey": "artworksConnection(aggregations:[\"TOTAL\"],first:1,sort:\"-decayed_merch\")" } ], "storageKey": null } ], "storageKey": null } ], "storageKey": "marketingCollection(slug:\"doesn't matter\")" } ] }, "params": { "id": "de9cb7a3bbbf848f8875419a2f8d9a99", "metadata": { "relayTestingSelectionTypeInfo": { "marketingCollection": { "enumValues": null, "nullable": true, "plural": false, "type": "MarketingCollection" }, "marketingCollection.artworksConnection": (v14/*: any*/), "marketingCollection.artworksConnection.id": (v15/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists": { "enumValues": null, "nullable": true, "plural": true, "type": "Artist" }, "marketingCollection.artworksConnection.merchandisableArtists.birthday": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.deathday": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.href": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.id": (v15/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.image": (v17/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.image.url": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.initials": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.internalID": (v15/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.is_followed": (v18/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.name": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.nationality": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.slug": (v15/*: any*/), "marketingCollection.collectionArtworks": (v14/*: any*/), "marketingCollection.collectionArtworks.__isArtworkConnectionInterface": (v19/*: any*/), "marketingCollection.collectionArtworks.aggregations": { "enumValues": null, "nullable": true, "plural": true, "type": "ArtworksAggregationResults" }, "marketingCollection.collectionArtworks.aggregations.counts": { "enumValues": null, "nullable": true, "plural": true, "type": "AggregationCount" }, "marketingCollection.collectionArtworks.aggregations.counts.count": { "enumValues": null, "nullable": false, "plural": false, "type": "Int" }, "marketingCollection.collectionArtworks.aggregations.counts.name": (v19/*: any*/), "marketingCollection.collectionArtworks.aggregations.counts.value": (v19/*: any*/), "marketingCollection.collectionArtworks.aggregations.slice": { "enumValues": [ "ARTIST", "ARTIST_NATIONALITY", "ATTRIBUTION_CLASS", "COLOR", "DIMENSION_RANGE", "FOLLOWED_ARTISTS", "GALLERY", "INSTITUTION", "LOCATION_CITY", "MAJOR_PERIOD", "MATERIALS_TERMS", "MEDIUM", "MERCHANDISABLE_ARTISTS", "PARTNER", "PARTNER_CITY", "PERIOD", "PRICE_RANGE", "TOTAL" ], "nullable": true, "plural": false, "type": "ArtworkAggregation" }, "marketingCollection.collectionArtworks.counts": { "enumValues": null, "nullable": true, "plural": false, "type": "FilterArtworksCounts" }, "marketingCollection.collectionArtworks.counts.total": (v20/*: any*/), "marketingCollection.collectionArtworks.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "ArtworkEdgeInterface" }, "marketingCollection.collectionArtworks.edges.__isNode": (v19/*: any*/), "marketingCollection.collectionArtworks.edges.__typename": (v19/*: any*/), "marketingCollection.collectionArtworks.edges.cursor": (v19/*: any*/), "marketingCollection.collectionArtworks.edges.id": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node": (v21/*: any*/), "marketingCollection.collectionArtworks.edges.node.__typename": (v19/*: any*/), "marketingCollection.collectionArtworks.edges.node.artistNames": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.date": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.href": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.id": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node.image": (v17/*: any*/), "marketingCollection.collectionArtworks.edges.node.image.aspectRatio": { "enumValues": null, "nullable": false, "plural": false, "type": "Float" }, "marketingCollection.collectionArtworks.edges.node.image.url": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.internalID": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node.partner": { "enumValues": null, "nullable": true, "plural": false, "type": "Partner" }, "marketingCollection.collectionArtworks.edges.node.partner.id": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node.partner.name": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale": { "enumValues": null, "nullable": true, "plural": false, "type": "Sale" }, "marketingCollection.collectionArtworks.edges.node.sale.displayTimelyAt": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.endAt": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.id": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.isAuction": (v18/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.isClosed": (v18/*: any*/), "marketingCollection.collectionArtworks.edges.node.saleArtwork": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtwork" }, "marketingCollection.collectionArtworks.edges.node.saleArtwork.counts": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCounts" }, "marketingCollection.collectionArtworks.edges.node.saleArtwork.counts.bidderPositions": (v20/*: any*/), "marketingCollection.collectionArtworks.edges.node.saleArtwork.currentBid": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCurrentBid" }, "marketingCollection.collectionArtworks.edges.node.saleArtwork.currentBid.display": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.saleArtwork.id": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node.saleArtwork.lotLabel": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.saleMessage": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node.slug": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node.title": (v16/*: any*/), "marketingCollection.collectionArtworks.id": (v15/*: any*/), "marketingCollection.collectionArtworks.pageInfo": { "enumValues": null, "nullable": false, "plural": false, "type": "PageInfo" }, "marketingCollection.collectionArtworks.pageInfo.endCursor": (v16/*: any*/), "marketingCollection.collectionArtworks.pageInfo.hasNextPage": (v22/*: any*/), "marketingCollection.collectionArtworks.pageInfo.startCursor": (v16/*: any*/), "marketingCollection.descriptionMarkdown": (v16/*: any*/), "marketingCollection.featuredArtistExclusionIds": (v23/*: any*/), "marketingCollection.headerImage": (v16/*: any*/), "marketingCollection.id": (v15/*: any*/), "marketingCollection.image": (v14/*: any*/), "marketingCollection.image.edges": (v24/*: any*/), "marketingCollection.image.edges.node": (v21/*: any*/), "marketingCollection.image.edges.node.id": (v15/*: any*/), "marketingCollection.image.edges.node.image": (v17/*: any*/), "marketingCollection.image.edges.node.image.url": (v16/*: any*/), "marketingCollection.image.id": (v15/*: any*/), "marketingCollection.isDepartment": (v22/*: any*/), "marketingCollection.linkedCollections": { "enumValues": null, "nullable": false, "plural": true, "type": "MarketingCollectionGroup" }, "marketingCollection.linkedCollections.groupType": { "enumValues": [ "ArtistSeries", "FeaturedCollections", "OtherCollections" ], "nullable": false, "plural": false, "type": "MarketingGroupTypes" }, "marketingCollection.linkedCollections.members": { "enumValues": null, "nullable": false, "plural": true, "type": "MarketingCollection" }, "marketingCollection.linkedCollections.members.artworksConnection": (v14/*: any*/), "marketingCollection.linkedCollections.members.artworksConnection.edges": (v24/*: any*/), "marketingCollection.linkedCollections.members.artworksConnection.edges.node": (v21/*: any*/), "marketingCollection.linkedCollections.members.artworksConnection.edges.node.id": (v15/*: any*/), "marketingCollection.linkedCollections.members.artworksConnection.edges.node.image": (v17/*: any*/), "marketingCollection.linkedCollections.members.artworksConnection.edges.node.image.url": (v16/*: any*/), "marketingCollection.linkedCollections.members.artworksConnection.edges.node.title": (v16/*: any*/), "marketingCollection.linkedCollections.members.artworksConnection.id": (v15/*: any*/), "marketingCollection.linkedCollections.members.descriptionMarkdown": (v16/*: any*/), "marketingCollection.linkedCollections.members.featuredCollectionArtworks": (v14/*: any*/), "marketingCollection.linkedCollections.members.featuredCollectionArtworks.edges": (v24/*: any*/), "marketingCollection.linkedCollections.members.featuredCollectionArtworks.edges.node": (v21/*: any*/), "marketingCollection.linkedCollections.members.featuredCollectionArtworks.edges.node.id": (v15/*: any*/), "marketingCollection.linkedCollections.members.featuredCollectionArtworks.edges.node.image": (v17/*: any*/), "marketingCollection.linkedCollections.members.featuredCollectionArtworks.edges.node.image.url": (v16/*: any*/), "marketingCollection.linkedCollections.members.featuredCollectionArtworks.id": (v15/*: any*/), "marketingCollection.linkedCollections.members.id": (v15/*: any*/), "marketingCollection.linkedCollections.members.priceGuidance": { "enumValues": null, "nullable": true, "plural": false, "type": "Float" }, "marketingCollection.linkedCollections.members.slug": (v19/*: any*/), "marketingCollection.linkedCollections.members.title": (v19/*: any*/), "marketingCollection.linkedCollections.name": (v19/*: any*/), "marketingCollection.query": { "enumValues": null, "nullable": false, "plural": false, "type": "MarketingCollectionQuery" }, "marketingCollection.query.artistIDs": (v23/*: any*/), "marketingCollection.query.id": { "enumValues": null, "nullable": true, "plural": false, "type": "ID" }, "marketingCollection.slug": (v19/*: any*/), "marketingCollection.title": (v19/*: any*/) } }, "name": "CollectionTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = 'fbe5831179fb6d1e2f66b7360c128d63'; export default node;
the_stack
import {promisifyAll} from '@google-cloud/promisify'; import * as through from 'through2'; import {Operation as GaxOperation, CallOptions} from 'google-gax'; import {Database, UpdateSchemaCallback, UpdateSchemaResponse} from './database'; import {PartialResultStream, Row} from './partial-result-stream'; import { ReadRequest, TimestampBounds, CommitOptions, CommitResponse, ReadResponse, ReadCallback, CommitCallback, } from './transaction'; import {google as databaseAdmin} from '../protos/protos'; import {Schema, LongRunningCallback} from './common'; import IRequestOptions = databaseAdmin.spanner.v1.IRequestOptions; export type Key = string | string[]; export type CreateTableResponse = [ Table, GaxOperation, databaseAdmin.longrunning.IOperation ]; export type CreateTableCallback = LongRunningCallback<Table>; export type DropTableResponse = UpdateSchemaResponse; export type DropTableCallback = UpdateSchemaCallback; interface MutateRowsOptions extends CommitOptions { requestOptions?: Omit<IRequestOptions, 'requestTag'>; } export type DeleteRowsCallback = CommitCallback; export type DeleteRowsResponse = CommitResponse; export type DeleteRowsOptions = MutateRowsOptions; export type InsertRowsCallback = CommitCallback; export type InsertRowsResponse = CommitResponse; export type InsertRowsOptions = MutateRowsOptions; export type ReplaceRowsCallback = CommitCallback; export type ReplaceRowsResponse = CommitResponse; export type ReplaceRowsOptions = MutateRowsOptions; export type UpdateRowsCallback = CommitCallback; export type UpdateRowsResponse = CommitResponse; export type UpdateRowsOptions = MutateRowsOptions; export type UpsertRowsCallback = CommitCallback; export type UpsertRowsResponse = CommitResponse; export type UpsertRowsOptions = MutateRowsOptions; /** * Create a Table object to interact with a table in a Cloud Spanner * database. * * @class * * @param {Database} database {@link Database} instance. * @param {string} name Name of the table. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('my-table'); * ``` */ class Table { database: Database; name: string; constructor(database: Database, name: string) { /** * The {@link Database} instance of this {@link Table} instance. * @name Table#database * @type {Database} */ this.database = database; /** * The name of this table. * @name Table#name * @type {string} */ this.name = name; } /** * Create a table. * * @param {string} schema See {@link Database#createTable}. * @param {object} [gaxOptions] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {CreateTableCallback} [callback] Callback function. * @returns {Promise<CreateTableResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * const schema = * 'CREATE TABLE Singers (' + * ' SingerId INT64 NOT NULL,' + * ' FirstName STRING(1024),' + * ' LastName STRING(1024),' + * ' SingerInfo BYTES(MAX),' + * ') PRIMARY KEY(SingerId)'; * * table.create(schema, function(err, table, operation, apiResponse) { * if (err) { * // Error handling omitted. * } * * operation * .on('error', function(err) {}) * .on('complete', function() { * // Table created successfully. * }); * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.create(schema) * .then(function(data) { * const table = data[0]; * const operation = data[1]; * * return operation.promise(); * }) * .then(function() { * // Table created successfully. * }); * ``` */ create( schema: Schema, gaxOptions?: CallOptions ): Promise<CreateTableResponse>; create(schema: Schema, callback: CreateTableCallback): void; create( schema: Schema, gaxOptions: CallOptions, callback: CreateTableCallback ): void; create( schema: Schema, gaxOptionsOrCallback?: CallOptions | CreateTableCallback, cb?: CreateTableCallback ): Promise<CreateTableResponse> | void { const gaxOptions = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; this.database.createTable(schema, gaxOptions, callback!); } /** * Create a readable object stream to receive rows from the database using key * lookups and scans. * * @see [StreamingRead API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.StreamingRead) * @see [ReadRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest) * * @param {ReadRequest} query Configuration object, describing what to read from the table.. * @param {TimestampBounds} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds). * @returns {PartialResultStream} A readable stream that emits rows. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * table.createReadStream({ * keys: ['1'], * columns: ['SingerId', 'name'] * }) * .on('error', function(err) {}) * .on('data', function(row) { * // row = { * // SingerId: '1', * // Name: 'Eddie Wilson' * // } * }) * .on('end', function() { * // All results retrieved. * }); * * //- * // Provide an array for `query.keys` to read with a composite key. * //- * const query = { * keys: [ * [ * 'Id1', * 'Name1' * ], * [ * 'Id2', * 'Name2' * ] * ], * // ... * }; * * //- * // If you anticipate many results, you can end a stream early to prevent * // unnecessary processing and API requests. * //- * table.createReadStream({ * keys: ['1'], * columns: ['SingerId', 'name'] * }) * .on('data', function(row) { * this.end(); * }); * ``` */ createReadStream( request: ReadRequest, options: TimestampBounds = {} ): PartialResultStream { const proxyStream = through.obj(); this.database.getSnapshot(options, (err, snapshot) => { if (err) { proxyStream.destroy(err); return; } snapshot! .createReadStream(this.name, request) .on('error', err => { proxyStream.destroy(err); snapshot!.end(); }) .on('end', () => snapshot!.end()) .pipe(proxyStream); }); return proxyStream as PartialResultStream; } /** * @typedef {array} DropTableResponse * @property {google.longrunning.Operation} 0 An {@link Operation} object that can be used to check * the status of the request. * @property {object} 1 The full API response. */ /** * @callback DropTableCallback * @param {?Error} err Request error, if any. * @param {google.longrunning.Operation} operation An {@link Operation} object that can be used to * check the status of the request. * @param {object} apiResponse The full API response. */ /** * Delete the table. Not to be confused with {@link Table#deleteRows}. * * Wrapper around {@link Database#updateSchema}. * * @see {@link Database#updateSchema} * * @throws {TypeError} If any arguments are passed in. * @param {object} [gaxOptions] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {DropTableCallback} [callback] Callback function. * @returns {Promise<DropTableResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * table.delete(function(err, operation, apiResponse) { * if (err) { * // Error handling omitted. * } * * operation * .on('error', function(err) {}) * .on('complete', function() { * // Table deleted successfully. * }); * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.delete() * .then(function(data) { * const operation = data[0]; * return operation.promise(); * }) * .then(function() { * // Table deleted successfully. * }); * ``` */ delete(gaxOptions?: CallOptions): Promise<DropTableResponse>; delete(callback: DropTableCallback): void; delete(gaxOptions: CallOptions, callback: DropTableCallback): void; delete( gaxOptionsOrCallback?: CallOptions | DropTableCallback, cb?: DropTableCallback ): Promise<DropTableResponse> | void { const gaxOptions = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; return this.database.updateSchema( 'DROP TABLE `' + this.name + '`', gaxOptions, callback! ); } /** * @typedef {array} DeleteRowsResponse * @property {CommitResponse} 0 The commit response. */ /** * @callback DeleteRowsCallback * @param {?Error} error Request error, if any. * @param {CommitResponse} apiResponse The full API response. */ /** * @typedef {object} DeleteRowsOptions * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include * with the commit request. * @property {boolean} returnCommitStats Include statistics related to the * transaction in the {@link CommitResponse}. * @property {object} [gaxOptions] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. */ /** * Delete rows from this table. * * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) * * @param {array} keys The keys for the rows to delete. If using a * composite key, provide an array within this array. See the example * below. * @param {DeleteRowsOptions|CallOptions} [options] Options for configuring the request. * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {DeleteRowsCallback} [callback] Callback function. * @returns {Promise<DeleteRowsResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * const keys = ['Id1', 'Id2', 'Id3']; * * table.deleteRows(keys, function(err, apiResponse) {}); * * //- * // Provide an array for `keys` to delete rows with a composite key. * //- * const keys = [ * [ * 'Id1', * 'Name1' * ], * [ * 'Id2', * 'Name2' * ] * ]; * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.deleteRows(keys) * .then(function(data) { * const apiResponse = data[0]; * }); * ``` */ deleteRows( keys: Key[], options?: DeleteRowsOptions | CallOptions ): Promise<DeleteRowsResponse>; deleteRows(keys: Key[], callback: DeleteRowsCallback): void; deleteRows( keys: Key[], options: DeleteRowsOptions | CallOptions, callback: DeleteRowsCallback ): void; deleteRows( keys: Key[], optionsOrCallback?: DeleteRowsOptions | CallOptions | DeleteRowsCallback, cb?: DeleteRowsCallback ): Promise<DeleteRowsResponse> | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; return this._mutate('deleteRows', keys, options, callback!); } /** * Drop the table. * * @see {@link Table#delete} * @see {@link Database#updateSchema} * * @param {object} [gaxOptions] Request configuration options. * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {DropTableCallback} [callback] Callback function. * @returns {Promise<DropTableResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * table.drop(function(err, operation, apiResponse) { * if (err) { * // Error handling omitted. * } * * operation * .on('error', function(err) {}) * .on('complete', function() { * // Table dropped successfully. * }); * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.drop() * .then(function(data) { * const operation = data[0]; * return operation.promise(); * }) * .then(function() { * // Table dropped successfully. * }); * ``` */ drop(gaxOptions?: CallOptions): Promise<DropTableResponse>; drop(callback: DropTableCallback): void; drop(gaxOptions: CallOptions, callback: DropTableCallback): void; drop( gaxOptionsOrCallback?: CallOptions | DropTableCallback, cb?: DropTableCallback ): Promise<DropTableResponse> | void { const gaxOptions = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; return this.delete(gaxOptions, callback!); } /** * @typedef {array} InsertRowsResponse * @property {CommitResponse} 0 The commit response. */ /** * @callback InsertRowsCallback * @param {?Error} error Request error, if any. * @param {CommitResponse} apiResponse The full API response. */ /** * @typedef {object} InsertRowsOptions * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include * with the commit request. * @property {boolean} returnCommitStats Include statistics related to the * transaction in the {@link CommitResponse}. * @property {object} [gaxOptions] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. */ /** * Insert rows of data into this table. * * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) * * @param {object|object[]} rows A map of names to values of data to insert * into this table. * @param {InsertRowsOptions|CallOptions} [options] Options for configuring the request. * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {InsertRowsCallback} [callback] Callback function. * @returns {Promise<InsertRowsResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * const row = { * SingerId: 'Id3', * Name: 'Eddie Wilson' * }; * * table.insert(row, function(err, apiResponse) { * if (err) { * // Error handling omitted. * } * * // Rows inserted successfully. * }); * * //- * // Multiple rows can be inserted at once. * //- * const row2 = { * SingerId: 'Id3b', * Name: 'Joe West' * }; * * table.insert([ * row, * row2 * ], function(err, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.insert(row) * .then(function(data) { * const apiResponse = data[0]; * }); * * ``` * @example <caption>include:samples/crud.js</caption> * region_tag:spanner_insert_data * Full example: */ insert( rows: object | object[], options?: InsertRowsOptions | CallOptions ): Promise<InsertRowsResponse>; insert(rows: object | object[], callback: InsertRowsCallback): void; insert( rows: object | object[], options: InsertRowsOptions | CallOptions, callback: InsertRowsCallback ): void; insert( rows: object | object[], optionsOrCallback?: InsertRowsOptions | CallOptions | InsertRowsCallback, cb?: InsertRowsCallback ): Promise<InsertRowsResponse> | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; this._mutate('insert', rows, options, callback!); } /** * Configuration object, describing what to read from the table. */ /** * @typedef {array} TableReadResponse * @property {array[]} 0 Rows are returned as an array of object arrays. Each * object has a `name` and `value` property. To get a serialized object, * call `toJSON()`. Optionally, provide an options object to `toJSON()` * specifying `wrapNumbers: true` to protect large integer values outside * of the range of JavaScript Number. If set, FLOAT64 values will be returned * as {@link Spanner.Float} objects and INT64 values as {@link * Spanner.Int}. */ /** * @callback TableReadCallback * @param {?Error} err Request error, if any. * @param {array[]} rows Rows are returned as an array of object arrays. Each * object has a `name` and `value` property. To get a serialized object, * call `toJSON()`. Optionally, provide an options object to `toJSON()` * specifying `wrapNumbers: true` to protect large integer values outside * of the range of JavaScript Number. If set, FLOAT64 values will be returned * as {@link Spanner.Float} objects and INT64 values as {@link * Spanner.Int}. */ /** * Receive rows from the database using key lookups and scans. * * **Performance Considerations:** * * This method wraps the streaming method, * {@link Table#createReadStream} for your convenience. All rows will * be stored in memory before being released to your callback. If you intend * on receiving a lot of results from your query, consider using the streaming * method, so you can free each result from memory after consuming it. * * @param {ReadRequest} query Configuration object, describing * what to read from the table. * @param {TimestampBounds} options [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds). * @param {TableReadCallback} [callback] Callback function. * @returns {Promise<TableReadResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * const query = { * keys: ['1'], * columns: ['SingerId', 'name'] * }; * * table.read(query, function(err, rows) { * if (err) { * // Error handling omitted. * } * * const firstRow = rows[0]; * * // firstRow = [ * // { * // name: 'SingerId', * // value: '1' * // }, * // { * // name: 'Name', * // value: 'Eddie Wilson' * // } * // ] * }); * * //- * // Provide an array for `query.keys` to read with a composite key. * //- * const query = { * keys: [ * [ * 'Id1', * 'Name1' * ], * [ * 'Id2', * 'Name2' * ] * ], * // ... * }; * * //- * // Rows are returned as an array of object arrays. Each object has a `name` * // and `value` property. To get a serialized object, call `toJSON()`. * // * // Alternatively, set `query.json` to `true`, and this step will be * performed * // automatically. * //- * table.read(query, function(err, rows) { * if (err) { * // Error handling omitted. * } * * const firstRow = rows[0]; * * // firstRow.toJSON() = { * // SingerId: '1', * // Name: 'Eddie Wilson' * // } * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.read(query) * .then(function(data) { * const rows = data[0]; * }); * * ``` * @example <caption>include:samples/crud.js</caption> * region_tag:spanner_read_data * Full example: * * @example <caption>include:samples/crud.js</caption> * region_tag:spanner_read_stale_data * Reading stale data: * * @example <caption>include:samples/index-read-data.js</caption> * region_tag:spanner_read_data_with_index * Reading data using an index: * * @example <caption>include:samples/index-read-data-with-storing.js</caption> * region_tag:spanner_read_data_with_storing_index * Reading data using a storing index: */ read(request: ReadRequest, options?: TimestampBounds): Promise<ReadResponse>; read(request: ReadRequest, callback: ReadCallback): void; read( request: ReadRequest, options: TimestampBounds, callback: ReadCallback ): void; read( request: ReadRequest, optionsOrCallback?: TimestampBounds | ReadCallback, cb?: ReadCallback ): Promise<ReadResponse> | void { const rows: Row[] = []; const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; const options = typeof optionsOrCallback === 'object' ? (optionsOrCallback as TimestampBounds) : {}; this.createReadStream(request, options) .on('error', callback!) .on('data', (row: Row) => rows.push(row)) .on('end', () => callback!(null, rows)); } /** * @typedef {array} ReplaceRowsResponse * @property {CommitResponse} 0 The commit response. */ /** * @callback ReplaceRowsCallback * @param {?Error} error Request error, if any. * @param {CommitResponse} apiResponse The full API response. */ /** * @typedef {object} ReplaceRowsOptions * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include * with the commit request. * @property {boolean} returnCommitStats Include statistics related to the * transaction in the {@link CommitResponse}. * @property {object} [gaxOptions] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. */ /** * Replace rows of data within this table. * * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) * * @param {object|object[]} rows A map of names to values of data to insert * into this table. * @param {ReplaceRowsOptions|CallOptions} [options] Options for configuring the request. * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {ReplaceRowsCallback} [callback] Callback function. * @returns {Promise<ReplaceRowsResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * const row = { * SingerId: 'Id3', * Name: 'Joe West' * }; * * table.replace(row, function(err, apiResponse) { * if (err) { * // Error handling omitted. * } * * // Row replaced successfully. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.replace(row) * .then(function(data) { * const apiResponse = data[0]; * }); * ``` */ replace( rows: object | object[], options?: ReplaceRowsOptions | CallOptions ): Promise<ReplaceRowsResponse>; replace(rows: object | object[], callback: ReplaceRowsCallback): void; replace( rows: object | object[], options: ReplaceRowsOptions | CallOptions, callback: ReplaceRowsCallback ): void; replace( rows: object | object[], optionsOrCallback?: ReplaceRowsOptions | CallOptions | ReplaceRowsCallback, cb?: ReplaceRowsCallback ): Promise<ReplaceRowsResponse> | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; this._mutate('replace', rows, options, callback!); } /** * @typedef {array} UpdateRowsResponse * @property {CommitResponse} 0 The commit response. */ /** * @callback UpdateRowsCallback * @param {?Error} error Request error, if any. * @param {CommitResponse} apiResponse The full API response. */ /** * @typedef {object} UpdateRowsOptions * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include * with the commit request. * @property {boolean} returnCommitStats Include statistics related to the * transaction in the {@link CommitResponse}. * @property {object} [gaxOptions] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. */ /** * Update rows of data within this table. * * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) * * @param {object|object[]} rows A map of names to values of data to insert * into this table. * @param {UpdateRowsOptions|CallOptions} [options] Options for configuring the request. * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {UpdateRowsCallback} [callback] Callback function. * @returns {Promise<UpdateRowsResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * const row = { * SingerId: 'Id3', * Name: 'Joe West' * }; * * table.update(row, function(err, apiResponse) { * if (err) { * // Error handling omitted. * } * * // Row updated successfully. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.update(row) * .then(function(data) { * const apiResponse = data[0]; * }); * * ``` * @example <caption>include:samples/crud.js</caption> * region_tag:spanner_update_data * Full example: */ update( rows: object | object[], options?: UpdateRowsOptions | CallOptions ): Promise<UpdateRowsResponse>; update(rows: object | object[], callback: UpdateRowsCallback): void; update( rows: object | object[], options: UpdateRowsOptions | CallOptions, callback: UpdateRowsCallback ): void; update( rows: object | object[], optionsOrCallback?: UpdateRowsOptions | CallOptions | UpdateRowsCallback, cb?: UpdateRowsCallback ): Promise<UpdateRowsResponse> | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; this._mutate('update', rows, options, callback!); } /** * @typedef {array} UpsertRowsResponse * @property {CommitResponse} 0 The commit response. */ /** * @callback UpsertRowsCallback * @param {?Error} error Request error, if any. * @param {CommitResponse} apiResponse The full API response. */ /** * @typedef {object} UpsertRowsOptions * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include * with the commit request. * @property {boolean} returnCommitStats Include statistics related to the * transaction in the {@link CommitResponse}. * @property {object} [gaxOptions] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. */ /** * Insert or update rows of data within this table. * * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) * * @param {object|object[]} rows A map of names to values of data to insert * into this table. * * @param {UpsertRowsOptions|CallOptions} [options] Options for configuring the request. * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {UpsertRowsCallback} [callback] Callback function. * @returns {Promise<UpsertRowsResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * * const instance = spanner.instance('my-instance'); * const database = instance.database('my-database'); * const table = database.table('Singers'); * * const row = { * SingerId: 'Id3', * Name: 'Joe West' * }; * * table.upsert(row, function(err, apiResponse) { * if (err) { * // Error handling omitted. * } * * // Row inserted or updated successfully. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * table.upsert(row) * .then(function(data) { * const apiResponse = data[0]; * }); * ``` */ upsert( rows: object | object[], options?: UpsertRowsOptions | CallOptions ): Promise<UpsertRowsResponse>; upsert(rows: object | object[], callback: UpsertRowsCallback): void; upsert( rows: object | object[], options: UpsertRowsOptions | CallOptions, callback: UpsertRowsCallback ): void; upsert( rows: object | object[], optionsOrCallback?: UpsertRowsOptions | CallOptions | UpsertRowsCallback, cb?: UpsertRowsCallback ): Promise<UpsertRowsResponse> | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; this._mutate('upsert', rows, options, callback!); } /** * Creates a new transaction and applies the desired mutation via * {@link Transaction#commit}. * * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) * * @private * * @param {string} method CRUD method (insert, update, etc.). * @param {object|object[]} rows A map of names to values of data to insert * into this table. * @param {function} callback The callback function. */ private _mutate( method: 'deleteRows' | 'insert' | 'replace' | 'update' | 'upsert', rows: object | object[], options: MutateRowsOptions | CallOptions = {}, callback: CommitCallback ): void { const requestOptions = 'requestOptions' in options ? options.requestOptions : {}; this.database.runTransaction({requestOptions}, (err, transaction) => { if (err) { callback(err); return; } transaction![method](this.name, rows as Key[]); transaction!.commit(options, callback); }); } } /*! Developer Documentation * * All async methods (except for streams) will return a Promise in the event * that a callback is omitted. */ promisifyAll(Table, { exclude: ['delete', 'drop'], }); /** * Reference to the {@link Table} class. * @name module:@google-cloud/spanner.Table * @see Table */ export {Table};
the_stack
import { KnownMediaType } from '@azure-tools/codemodel-v3'; import { System, Ternery, IsNotNull, dotnet } from '@azure-tools/codegen-csharp'; import { Expression, ExpressionOrLiteral, LiteralExpression, StringExpression, toExpression, valueOf } from '@azure-tools/codegen-csharp'; import { If } from '@azure-tools/codegen-csharp'; import { OneOrMoreStatements } from '@azure-tools/codegen-csharp'; import { Variable } from '@azure-tools/codegen-csharp'; import { ClientRuntime } from '../clientruntime'; import { Schema } from '../code-model'; import { Schema as NewSchema, DateTimeSchema, UnixTimeSchema, DateSchema } from '@azure-tools/codemodel'; import { NewPrimitive } from './primitive'; export class DateTime extends NewPrimitive { public isXmlAttribute = false; public jsonType = ClientRuntime.JsonString; // public DateFormat = new StringExpression('yyyy-MM-dd'); public DateTimeFormat = new StringExpression('yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss.fffffffK'); get encode(): string { return (this.schema.extensions && this.schema.extensions['x-ms-skip-url-encoding']) ? '' : 'global::System.Uri.EscapeDataString'; } get declaration(): string { return `global::System.DateTime${this.isRequired ? '' : '?'}`; } protected castJsonTypeToPrimitive(tmpValue: string, defaultValue: string) { return `global::System.DateTime.TryParse((string)${tmpValue}, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var ${tmpValue}Value) ? ${tmpValue}Value : ${defaultValue}`; } protected castXmlTypeToPrimitive(tmpValue: string, defaultValue: string) { return `global::System.DateTime.TryParse((string)${tmpValue}, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var ${tmpValue}Value) ? ${tmpValue}Value : ${defaultValue}`; } get convertObjectMethod() { return '(v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)'; } serializeToNode(mediaType: KnownMediaType, value: ExpressionOrLiteral, serializedName: string, mode: Expression): Expression { switch (mediaType) { case KnownMediaType.Json: return this.isRequired ? toExpression(`(${ClientRuntime.JsonNode}) new ${this.jsonType}(${value}.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture))`) : toExpression(`null != ${value} ? (${ClientRuntime.JsonNode}) new ${this.jsonType}(${value}?.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture)) : null`); case KnownMediaType.Xml: return this.isRequired ? toExpression(`new ${System.Xml.Linq.XElement}("${serializedName}",${value}.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture))`) : toExpression(`null != ${value} ? new ${System.Xml.Linq.XElement}("${serializedName}",${value}?.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture)) : null`); case KnownMediaType.Cookie: case KnownMediaType.QueryParameter: case KnownMediaType.Header: case KnownMediaType.Text: case KnownMediaType.UriParameter: return toExpression(this.isRequired ? `"${serializedName}=" + ${value}.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture)` : `(null == ${value} ? ${System.String.Empty} : "${serializedName}=" + ${value}?.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture))` ); } return toExpression(`null /* serializeToNode doesn't support '${mediaType}' ${__filename}*/`); } serializeToContainerMember(mediaType: KnownMediaType, value: ExpressionOrLiteral, container: Variable, serializedName: string, mode: Expression): OneOrMoreStatements { switch (mediaType) { case KnownMediaType.Json: // container : JsonObject return `AddIf( ${this.serializeToNode(mediaType, value, serializedName, mode)}, "${serializedName}" ,${valueOf(container)}.Add );`; case KnownMediaType.Xml: // container : XElement return `AddIf( ${this.serializeToNode(mediaType, value, serializedName, mode)}, ${valueOf(container)}.Add );`; case KnownMediaType.Header: // container : HttpRequestHeaders return this.isRequired ? `${valueOf(container)}.Add("${serializedName}",${value}.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture));` : If(`null != ${value}`, `${valueOf(container)}.Add("${serializedName}",${value}?.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture));`); case KnownMediaType.QueryParameter: // gives a name=value for use inside a c# template string($"foo{someProperty}") as a query parameter return this.isRequired ? `${serializedName}={${value}.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture)}` : `{null == ${value} ? ${System.String.Empty} : $"${serializedName}={${value}?.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture)}"}`; case KnownMediaType.UriParameter: // gives a name=value for use inside a c# template string($"foo{someProperty}") as a query parameter return this.isRequired ? `${serializedName}={${value}.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture)}` : `{null == ${value} ? ${System.String.Empty}: $"${serializedName}={${value}?.ToString(${this.DateTimeFormat},global::System.Globalization.CultureInfo.InvariantCulture)}"}`; } return (`/* serializeToContainerMember doesn't support '${mediaType}' ${__filename}*/`); } constructor(schema: DateTimeSchema | DateSchema, public isRequired: boolean) { super(schema); } // public static string DateFormat = "yyyy-MM-dd"; // public static string DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; // public static string DateTimeRfc1123Format = "R"; // public static JsonString CreateDate(DateTime? value) => value is DateTime date ? new JsonString(date.ToString(DateFormat, CultureInfo.InvariantCulture)) : null; // public static JsonString CreateDateTime(DateTime? value) => value is DateTime date ? new JsonString(date.ToString(DateTimeFormat, CultureInfo.InvariantCulture)) : null; // public static JsonString CreateDateTimeRfc1123(DateTime ? value) => value is DateTime date ? new JsonString(date.ToString(DateTimeRfc1123Format, CultureInfo.InvariantCulture)) : null; validateValue(eventListener: Variable, property: Variable): string { return ''; } } export class DateTime1123 extends DateTime { public DateTimeFormat = new StringExpression('R'); constructor(schema: DateTimeSchema, isRequired: boolean) { super(schema, isRequired); } } export class UnixTime extends NewPrimitive { public isXmlAttribute = false; public jsonType = ClientRuntime.JsonNumber; private EpochDate = System.DateTime.new('1970', '1', '1', '0', '0', '0', System.DateTimeKind.Utc); get encode(): string { return (this.schema.extensions && this.schema.extensions['x-ms-skip-url-encoding']) ? '' : 'global::System.Uri.EscapeDataString'; } protected castJsonTypeToPrimitive(tmpValue: string, defaultValue: string) { return `long.TryParse((string)${tmpValue}, out var ${tmpValue}Value) ? ${this.EpochDate}.AddSeconds(${tmpValue}Value) : ${defaultValue}`; } protected castXmlTypeToPrimitive(tmpValue: string, defaultValue: string) { return `long.TryParse((string)${tmpValue}, out var ${tmpValue}Value) ? ${this.EpochDate}.AddSeconds(${tmpValue}Value) : ${defaultValue}`; } serializeToNode(mediaType: KnownMediaType, value: ExpressionOrLiteral, serializedName: string, mode: Expression): Expression { switch (mediaType) { case KnownMediaType.Json: return this.isRequired ? this.jsonType.new(`((${this.longType})(${value}${this.q}.Subtract(${valueOf(this.EpochDate)}).TotalSeconds))`).Cast(ClientRuntime.JsonNode) : Ternery(IsNotNull(value), this.jsonType.new(`((${this.longType})(${value}${this.q}.Subtract(${valueOf(this.EpochDate)}).TotalSeconds)??0)`).Cast(ClientRuntime.JsonNode), dotnet.Null); case KnownMediaType.Xml: return this.isRequired ? toExpression(`new ${System.Xml.Linq.XElement}("${serializedName}",${value})`) : toExpression(`null != ${value} ? new ${System.Xml.Linq.XElement}("${serializedName}",${value}) : null`); case KnownMediaType.QueryParameter: if (this.isRequired) { return toExpression(`"${serializedName}=" + ${this.encode}(${value}.ToString())`); } else { return toExpression(`(null == ${value} ? ${System.String.Empty} : "${serializedName}=" + ${this.encode}(${value}.ToString()))`); } // return toExpression(`if (${value} != null) { queryParameters.Add($"${value}={${value}}"); }`); case KnownMediaType.Cookie: case KnownMediaType.Header: case KnownMediaType.Text: case KnownMediaType.UriParameter: return toExpression(this.isRequired ? `(${value}.ToString())` : `(null == ${value} ? ${System.String.Empty} : ${value}.ToString())` ); } return toExpression(`null /* serializeToNode doesn't support '${mediaType}' ${__filename}*/`); } /** emits an expression serialize this to the value required by the container */ _serializeToNode(mediaType: KnownMediaType, value: ExpressionOrLiteral, serializedName: string, mode: Expression): Expression { return super.serializeToNode(mediaType, new LiteralExpression(`((${this.longType})(${value}${this.q}.Subtract(${valueOf(this.EpochDate)}).TotalSeconds))`), serializedName, mode); } get q(): string { return this.isRequired ? '' : '?'; } get longType(): string { return this.isRequired ? 'long' : 'long?'; } constructor(schema: UnixTimeSchema, public isRequired: boolean) { super(schema); } validateValue(eventListener: Variable, property: Variable): string { return ''; } get declaration(): string { return `global::System.DateTime${this.isRequired ? '' : '?'}`; } }
the_stack
import * as coreClient from "@azure/core-client"; /** The key vault error exception. */ export interface KeyVaultError { /** * The key vault server error. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly error?: ErrorModel; } /** The key vault server error. */ export interface ErrorModel { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The key vault server error. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly innerError?: ErrorModel; } /** Role definition create parameters. */ export interface RoleDefinitionCreateParameters { /** Role definition properties. */ properties: RoleDefinitionProperties; } /** Role definition properties. */ export interface RoleDefinitionProperties { /** The role name. */ roleName?: string; /** The role definition description. */ description?: string; /** The role type. */ roleType?: RoleType; /** Role definition permissions. */ permissions?: Permission[]; /** Role definition assignable scopes. */ assignableScopes?: RoleScope[]; } /** Role definition permissions. */ export interface Permission { /** Action permissions that are granted. */ actions?: string[]; /** Action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. */ notActions?: string[]; /** Data action permissions that are granted. */ dataActions?: DataAction[]; /** Data action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a principal. */ notDataActions?: DataAction[]; } /** Role definition. */ export interface RoleDefinition { /** * The role definition ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role definition name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role definition type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: RoleDefinitionType; /** The role name. */ roleName?: string; /** The role definition description. */ description?: string; /** The role type. */ roleType?: RoleType; /** Role definition permissions. */ permissions?: Permission[]; /** Role definition assignable scopes. */ assignableScopes?: RoleScope[]; } /** Role definition list operation result. */ export interface RoleDefinitionListResult { /** Role definition list. */ value?: RoleDefinition[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Role assignment create parameters. */ export interface RoleAssignmentCreateParameters { /** Role assignment properties. */ properties: RoleAssignmentProperties; } /** Role assignment properties. */ export interface RoleAssignmentProperties { /** The role definition ID used in the role assignment. */ roleDefinitionId: string; /** The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. */ principalId: string; } /** Role Assignments */ export interface RoleAssignment { /** * The role assignment ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The role assignment name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The role assignment type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** Role assignment properties. */ properties?: RoleAssignmentPropertiesWithScope; } /** Role assignment properties with scope. */ export interface RoleAssignmentPropertiesWithScope { /** The role scope. */ scope?: RoleScope; /** The role definition ID. */ roleDefinitionId?: string; /** The principal ID. */ principalId?: string; } /** Role assignment list operation result. */ export interface RoleAssignmentListResult { /** Role assignment list. */ value?: RoleAssignment[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } export interface SASTokenParameter { /** Azure Blob storage container Uri */ storageResourceUri: string; /** The SAS token pointing to an Azure Blob storage container */ token: string; } /** Full backup operation */ export interface FullBackupOperation { /** Status of the backup operation. */ status?: string; /** The status details of backup operation. */ statusDetails?: string; /** Error encountered, if any, during the full backup operation. */ error?: ErrorModel; /** The start time of the backup operation in UTC */ startTime?: Date; /** The end time of the backup operation in UTC */ endTime?: Date; /** Identifier for the full backup operation. */ jobId?: string; /** The Azure blob storage container Uri which contains the full backup */ azureStorageBlobContainerUri?: string; } export interface RestoreOperationParameters { sasTokenParameters: SASTokenParameter; /** The Folder name of the blob where the previous successful full backup was stored */ folderToRestore: string; } /** Restore operation */ export interface RestoreOperation { /** Status of the restore operation. */ status?: string; /** The status details of restore operation. */ statusDetails?: string; /** Error encountered, if any, during the restore operation. */ error?: ErrorModel; /** Identifier for the restore operation. */ jobId?: string; /** The start time of the restore operation */ startTime?: Date; /** The end time of the restore operation */ endTime?: Date; } export interface SelectiveKeyRestoreOperationParameters { sasTokenParameters: SASTokenParameter; /** The Folder name of the blob where the previous successful full backup was stored */ folder: string; } /** Selective Key Restore operation */ export interface SelectiveKeyRestoreOperation { /** Status of the restore operation. */ status?: string; /** The status details of restore operation. */ statusDetails?: string; /** Error encountered, if any, during the selective key restore operation. */ error?: ErrorModel; /** Identifier for the selective key restore operation. */ jobId?: string; /** The start time of the restore operation */ startTime?: Date; /** The end time of the restore operation */ endTime?: Date; } /** Role Assignments filter */ export interface RoleAssignmentFilter { /** Returns role assignment of the specific principal. */ principalId?: string; } /** Role Definitions filter */ export interface RoleDefinitionFilter { /** Returns role definition with the specific name. */ roleName?: string; } /** Defines headers for KeyVaultClient_fullBackup operation. */ export interface KeyVaultClientFullBackupHeaders { /** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */ retryAfter?: number; /** The URI to poll for completion status. */ azureAsyncOperation?: string; } /** Defines headers for KeyVaultClient_fullRestoreOperation operation. */ export interface KeyVaultClientFullRestoreOperationHeaders { /** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */ retryAfter?: number; /** The URI to poll for completion status. */ azureAsyncOperation?: string; } /** Defines headers for KeyVaultClient_selectiveKeyRestoreOperation operation. */ export interface KeyVaultClientSelectiveKeyRestoreOperationHeaders { /** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */ retryAfter?: number; /** The URI to poll for completion status. */ azureAsyncOperation?: string; } /** Known values of {@link ApiVersion73Preview} that the service accepts. */ export enum KnownApiVersion73Preview { /** Api Version '7.3-preview' */ Seven3Preview = "7.3-preview" } /** * Defines values for ApiVersion73Preview. \ * {@link KnownApiVersion73Preview} can be used interchangeably with ApiVersion73Preview, * this enum contains the known values that the service supports. * ### Known values supported by the service * **7.3-preview**: Api Version '7.3-preview' */ export type ApiVersion73Preview = string; /** Known values of {@link RoleType} that the service accepts. */ export enum KnownRoleType { /** Built in role. */ BuiltInRole = "AKVBuiltInRole", /** Custom role. */ CustomRole = "CustomRole" } /** * Defines values for RoleType. \ * {@link KnownRoleType} can be used interchangeably with RoleType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **AKVBuiltInRole**: Built in role. \ * **CustomRole**: Custom role. */ export type RoleType = string; /** Known values of {@link DataAction} that the service accepts. */ export enum KnownDataAction { /** Read HSM key metadata. */ ReadHsmKey = "Microsoft.KeyVault/managedHsm/keys/read/action", /** Update an HSM key. */ WriteHsmKey = "Microsoft.KeyVault/managedHsm/keys/write/action", /** Read deleted HSM key. */ ReadDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/read/action", /** Recover deleted HSM key. */ RecoverDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/recover/action", /** Backup HSM keys. */ BackupHsmKeys = "Microsoft.KeyVault/managedHsm/keys/backup/action", /** Restore HSM keys. */ RestoreHsmKeys = "Microsoft.KeyVault/managedHsm/keys/restore/action", /** Delete role assignment. */ DeleteRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/delete/action", /** Get role assignment. */ GetRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/read/action", /** Create or update role assignment. */ WriteRoleAssignment = "Microsoft.KeyVault/managedHsm/roleAssignments/write/action", /** Get role definition. */ ReadRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/read/action", /** Create or update role definition. */ WriteRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/write/action", /** Delete role definition. */ DeleteRoleDefinition = "Microsoft.KeyVault/managedHsm/roleDefinitions/delete/action", /** Encrypt using an HSM key. */ EncryptHsmKey = "Microsoft.KeyVault/managedHsm/keys/encrypt/action", /** Decrypt using an HSM key. */ DecryptHsmKey = "Microsoft.KeyVault/managedHsm/keys/decrypt/action", /** Wrap using an HSM key. */ WrapHsmKey = "Microsoft.KeyVault/managedHsm/keys/wrap/action", /** Unwrap using an HSM key. */ UnwrapHsmKey = "Microsoft.KeyVault/managedHsm/keys/unwrap/action", /** Sign using an HSM key. */ SignHsmKey = "Microsoft.KeyVault/managedHsm/keys/sign/action", /** Verify using an HSM key. */ VerifyHsmKey = "Microsoft.KeyVault/managedHsm/keys/verify/action", /** Create an HSM key. */ CreateHsmKey = "Microsoft.KeyVault/managedHsm/keys/create", /** Delete an HSM key. */ DeleteHsmKey = "Microsoft.KeyVault/managedHsm/keys/delete", /** Export an HSM key. */ ExportHsmKey = "Microsoft.KeyVault/managedHsm/keys/export/action", /** Release an HSM key using Secure Key Release. */ ReleaseKey = "Microsoft.KeyVault/managedHsm/keys/release/action", /** Import an HSM key. */ ImportHsmKey = "Microsoft.KeyVault/managedHsm/keys/import/action", /** Purge a deleted HSM key. */ PurgeDeletedHsmKey = "Microsoft.KeyVault/managedHsm/keys/deletedKeys/delete", /** Download an HSM security domain. */ DownloadHsmSecurityDomain = "Microsoft.KeyVault/managedHsm/securitydomain/download/action", /** Check status of HSM security domain download. */ DownloadHsmSecurityDomainStatus = "Microsoft.KeyVault/managedHsm/securitydomain/download/read", /** Upload an HSM security domain. */ UploadHsmSecurityDomain = "Microsoft.KeyVault/managedHsm/securitydomain/upload/action", /** Check the status of the HSM security domain exchange file. */ ReadHsmSecurityDomainStatus = "Microsoft.KeyVault/managedHsm/securitydomain/upload/read", /** Download an HSM security domain transfer key. */ ReadHsmSecurityDomainTransferKey = "Microsoft.KeyVault/managedHsm/securitydomain/transferkey/read", /** Start an HSM backup. */ StartHsmBackup = "Microsoft.KeyVault/managedHsm/backup/start/action", /** Start an HSM restore. */ StartHsmRestore = "Microsoft.KeyVault/managedHsm/restore/start/action", /** Read an HSM backup status. */ ReadHsmBackupStatus = "Microsoft.KeyVault/managedHsm/backup/status/action", /** Read an HSM restore status. */ ReadHsmRestoreStatus = "Microsoft.KeyVault/managedHsm/restore/status/action", /** Generate random numbers. */ RandomNumbersGenerate = "Microsoft.KeyVault/managedHsm/rng/action" } /** * Defines values for DataAction. \ * {@link KnownDataAction} can be used interchangeably with DataAction, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Microsoft.KeyVault\/managedHsm\/keys\/read\/action**: Read HSM key metadata. \ * **Microsoft.KeyVault\/managedHsm\/keys\/write\/action**: Update an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/deletedKeys\/read\/action**: Read deleted HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/deletedKeys\/recover\/action**: Recover deleted HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/backup\/action**: Backup HSM keys. \ * **Microsoft.KeyVault\/managedHsm\/keys\/restore\/action**: Restore HSM keys. \ * **Microsoft.KeyVault\/managedHsm\/roleAssignments\/delete\/action**: Delete role assignment. \ * **Microsoft.KeyVault\/managedHsm\/roleAssignments\/read\/action**: Get role assignment. \ * **Microsoft.KeyVault\/managedHsm\/roleAssignments\/write\/action**: Create or update role assignment. \ * **Microsoft.KeyVault\/managedHsm\/roleDefinitions\/read\/action**: Get role definition. \ * **Microsoft.KeyVault\/managedHsm\/roleDefinitions\/write\/action**: Create or update role definition. \ * **Microsoft.KeyVault\/managedHsm\/roleDefinitions\/delete\/action**: Delete role definition. \ * **Microsoft.KeyVault\/managedHsm\/keys\/encrypt\/action**: Encrypt using an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/decrypt\/action**: Decrypt using an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/wrap\/action**: Wrap using an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/unwrap\/action**: Unwrap using an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/sign\/action**: Sign using an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/verify\/action**: Verify using an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/create**: Create an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/delete**: Delete an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/export\/action**: Export an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/release\/action**: Release an HSM key using Secure Key Release. \ * **Microsoft.KeyVault\/managedHsm\/keys\/import\/action**: Import an HSM key. \ * **Microsoft.KeyVault\/managedHsm\/keys\/deletedKeys\/delete**: Purge a deleted HSM key. \ * **Microsoft.KeyVault\/managedHsm\/securitydomain\/download\/action**: Download an HSM security domain. \ * **Microsoft.KeyVault\/managedHsm\/securitydomain\/download\/read**: Check status of HSM security domain download. \ * **Microsoft.KeyVault\/managedHsm\/securitydomain\/upload\/action**: Upload an HSM security domain. \ * **Microsoft.KeyVault\/managedHsm\/securitydomain\/upload\/read**: Check the status of the HSM security domain exchange file. \ * **Microsoft.KeyVault\/managedHsm\/securitydomain\/transferkey\/read**: Download an HSM security domain transfer key. \ * **Microsoft.KeyVault\/managedHsm\/backup\/start\/action**: Start an HSM backup. \ * **Microsoft.KeyVault\/managedHsm\/restore\/start\/action**: Start an HSM restore. \ * **Microsoft.KeyVault\/managedHsm\/backup\/status\/action**: Read an HSM backup status. \ * **Microsoft.KeyVault\/managedHsm\/restore\/status\/action**: Read an HSM restore status. \ * **Microsoft.KeyVault\/managedHsm\/rng\/action**: Generate random numbers. */ export type DataAction = string; /** Known values of {@link RoleScope} that the service accepts. */ export enum KnownRoleScope { /** Global scope */ Global = "/", /** Keys scope */ Keys = "/keys" } /** * Defines values for RoleScope. \ * {@link KnownRoleScope} can be used interchangeably with RoleScope, * this enum contains the known values that the service supports. * ### Known values supported by the service * **\/**: Global scope \ * **\/keys**: Keys scope */ export type RoleScope = string; /** Known values of {@link RoleDefinitionType} that the service accepts. */ export enum KnownRoleDefinitionType { MicrosoftAuthorizationRoleDefinitions = "Microsoft.Authorization/roleDefinitions" } /** * Defines values for RoleDefinitionType. \ * {@link KnownRoleDefinitionType} can be used interchangeably with RoleDefinitionType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Microsoft.Authorization\/roleDefinitions** */ export type RoleDefinitionType = string; /** Optional parameters. */ export interface RoleDefinitionsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface RoleDefinitionsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type RoleDefinitionsCreateOrUpdateResponse = RoleDefinition; /** Optional parameters. */ export interface RoleDefinitionsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleDefinitionsGetResponse = RoleDefinition; /** Optional parameters. */ export interface RoleDefinitionsListOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. */ filter?: string; } /** Contains response data for the list operation. */ export type RoleDefinitionsListResponse = RoleDefinitionListResult; /** Optional parameters. */ export interface RoleDefinitionsListNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. */ filter?: string; } /** Contains response data for the listNext operation. */ export type RoleDefinitionsListNextResponse = RoleDefinitionListResult; /** Optional parameters. */ export interface RoleAssignmentsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface RoleAssignmentsCreateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the create operation. */ export type RoleAssignmentsCreateResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoleAssignmentsGetResponse = RoleAssignment; /** Optional parameters. */ export interface RoleAssignmentsListForScopeOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; } /** Contains response data for the listForScope operation. */ export type RoleAssignmentsListForScopeResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface RoleAssignmentsListForScopeNextOptionalParams extends coreClient.OperationOptions { /** The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. */ filter?: string; } /** Contains response data for the listForScopeNext operation. */ export type RoleAssignmentsListForScopeNextResponse = RoleAssignmentListResult; /** Optional parameters. */ export interface KeyVaultClientFullBackupOptionalParams extends coreClient.OperationOptions { /** Azure blob shared access signature token pointing to a valid Azure blob container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the time of making this call */ azureStorageBlobContainerUri?: SASTokenParameter; } /** Contains response data for the fullBackup operation. */ export type KeyVaultClientFullBackupResponse = KeyVaultClientFullBackupHeaders & FullBackupOperation; /** Optional parameters. */ export interface KeyVaultClientFullBackupStatusOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the fullBackupStatus operation. */ export type KeyVaultClientFullBackupStatusResponse = FullBackupOperation; /** Optional parameters. */ export interface KeyVaultClientFullRestoreOperationOptionalParams extends coreClient.OperationOptions { /** The Azure blob SAS token pointing to a folder where the previous successful full backup was stored */ restoreBlobDetails?: RestoreOperationParameters; } /** Contains response data for the fullRestoreOperation operation. */ export type KeyVaultClientFullRestoreOperationResponse = KeyVaultClientFullRestoreOperationHeaders & RestoreOperation; /** Optional parameters. */ export interface KeyVaultClientRestoreStatusOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the restoreStatus operation. */ export type KeyVaultClientRestoreStatusResponse = RestoreOperation; /** Optional parameters. */ export interface KeyVaultClientSelectiveKeyRestoreOperationOptionalParams extends coreClient.OperationOptions { /** The Azure blob SAS token pointing to a folder where the previous successful full backup was stored */ restoreBlobDetails?: SelectiveKeyRestoreOperationParameters; } /** Contains response data for the selectiveKeyRestoreOperation operation. */ export type KeyVaultClientSelectiveKeyRestoreOperationResponse = KeyVaultClientSelectiveKeyRestoreOperationHeaders & SelectiveKeyRestoreOperation; /** Optional parameters. */ export interface KeyVaultClientOptionalParams extends coreClient.ServiceClientOptions { /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { Sparkline, SparklineTooltip } from '../../src/sparkline/index'; import { createElement } from '@syncfusion/ej2-base'; import { removeElement, getIdElement } from '../../src/sparkline/utils/helper'; import { ISparklineLoadedEventArgs } from '../../src/sparkline/model/interface'; import {profile , inMB, getMemoryProfile} from '../common.spec'; Sparkline.Inject(SparklineTooltip); /** * Sparkline Test case file */ describe('Sparkline Component Line Series Spec', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Sparkline testing Line series spec', () => { let element: Element; let sparkline: Sparkline; let id: string = 'spark-container'; let ele: Element; let d: string[]; beforeAll(() => { element = createElement('div', { id: id }); (element as HTMLDivElement).style.width = '400px'; (element as HTMLDivElement).style.height = '100px'; document.body.appendChild(element); sparkline = new Sparkline({ height: '40%', width: '20%', dataSource: [-10, 5, -15, 10, 5, 15, -20, 25] }); }); afterAll(() => { sparkline.destroy(); removeElement(id); }); it('Sparkline line series checking with array of data', () => { sparkline.loaded = () => { ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('opacity')).toBe('1'); expect(ele.getAttribute('stroke')).toBe('#00bdae'); expect(ele.getAttribute('stroke-width')).toBe('1'); expect(ele.getAttribute('fill')).toBe('transparent'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); d = ele.getAttribute('d').split('M'); expect(d.length).toBe(2); d = ele.getAttribute('d').split('L'); expect(d.length).toBe(9); }; sparkline.appendTo('#' + id); }); it('Sparkline line series checking with object array of data', () => { sparkline.loaded = () => { ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('opacity')).toBe('1'); expect(ele.getAttribute('stroke')).toBe('#00bdae'); expect(ele.getAttribute('stroke-width')).toBe('1'); expect(ele.getAttribute('fill')).toBe('transparent'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(22); d = ele.getAttribute('d').split('M'); expect(d.length).toBe(2); d = ele.getAttribute('d').split('L'); expect(d.length).toBe(7); }; sparkline.dataSource = [ { x: 0, yval: 2900 }, { x: 1, yval: 3900 }, { x: 2, yval: 3500 }, { x: 3, yval: 3800 }, { x: 4, yval: 2500 }, { x: 5, yval: 3200 } ]; sparkline.xName = 'x'; sparkline.yName = 'yval'; sparkline.refresh(); }); it('Sparkline range band checking spec', () => { sparkline.loaded = () => { ele = getIdElement(id + '_rangeBand_1'); expect(ele.getAttribute('opacity')).toBe('0.5'); expect(ele.getAttribute('stroke')).toBe('transparent'); expect(ele.getAttribute('stroke-width')).toBe('1'); expect(ele.getAttribute('fill')).toBe('blue'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(14); d = ele.getAttribute('d').split('M'); expect(d.length).toBe(2); d = ele.getAttribute('d').split('L'); expect(d.length).toBe(4); }; sparkline.rangeBandSettings = [ { startRange: 1500, endRange: 6000, color: 'gray', opacity: 1 }, { startRange: 500, endRange: 1500, color: 'blue', opacity: 0.5 }, { startRange: 1500, endRange: 3500, color: 'red', opacity: 1 }, { startRange: 4000, endRange: 6000, color: 'blue', opacity: 2 }, ]; sparkline.refresh(); }); it('Sparkline line series checking with axis settings', () => { sparkline.loaded = () => { ele = getIdElement(id + '_Sparkline_XAxis'); expect(ele.getAttribute('x1')).toBe('5'); expect(ele.getAttribute('y1')).toBe('35'); expect(ele.getAttribute('x2')).toBe('75'); expect(ele.getAttribute('y2')).toBe('35'); expect(ele.getAttribute('stroke')).toBe('#000000'); expect(ele.getAttribute('stroke-width')).toBe('1'); }; sparkline.axisSettings = { minX: 1, maxX: 4, minY: 2800, maxY: 3800, lineSettings: { visible: true} }; sparkline.refresh(); }); it('Sparkline axis custom value and line customization', () => { sparkline.loaded = () => { ele = getIdElement(id + '_Sparkline_XAxis'); expect(ele.getAttribute('x1')).toBe('5'); expect(ele.getAttribute('y1')).toBe('20'); expect(ele.getAttribute('x2')).toBe('75'); expect(ele.getAttribute('y2')).toBe('20'); expect(ele.getAttribute('stroke')).toBe('#9900cc'); expect(ele.getAttribute('stroke-width')).toBe('3'); }; sparkline.axisSettings = { value: 3300, lineSettings: { visible: true, color: '#9900cc', width: 3} }; sparkline.theme = 'MaterialDark'; sparkline.refresh(); }); it('Sparkline line with negative values', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_line'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(31); d = ele.getAttribute('d').split('M'); expect(d.length).toBe(2); d = ele.getAttribute('d').split('L'); expect(d.length).toBe(10); }; sparkline.theme = 'BootstrapDark'; sparkline.axisSettings = {minY: -9, maxY: -1, value: -5, minX: 0, maxX: 8}; sparkline.dataSource = [-3, -8, -5, -1, -7, -4, -9, -2, -6]; sparkline.refresh(); }); it('Sparkline line with category axis', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_line'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); d = ele.getAttribute('d').split('M'); expect(d.length).toBe(2); d = ele.getAttribute('d').split('L'); expect(d.length).toBe(9); }; sparkline.axisSettings = {minY: 3000, maxY: 5500, value: -5, minX: 0, maxX: 8}; sparkline.dataSource = [ {xDate: new Date(2017, 1, 1), x: 0, xval: 'Jan', yval: 2900 }, {xDate: new Date(2017, 1, 2), x: 1, xval: 'Feb', yval: 3900 }, {xDate: new Date(2017, 1, 3), x: 2, xval: 'Mar', yval: 3500 }, {xDate: new Date(2017, 1, 4), x: 3, xval: 'Apr', yval: 3800 }, {xDate: new Date(2017, 1, 5), x: 4, xval: 'May', yval: 2500 }, {xDate: new Date(2017, 1, 6), x: 5, xval: 'Jun', yval: 3200 }, {xDate: new Date(2017, 1, 7), x: 6, xval: 'Jul', yval: 1800 }, {xDate: new Date(2017, 1, 8), x: 7, xval: 'Aug', yval: 5000 }, ]; sparkline.refresh(); }); it('Sparkline line with datetime axis', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_line'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); d = ele.getAttribute('d').split('M'); expect(d.length).toBe(2); d = ele.getAttribute('d').split('L'); expect(d.length).toBe(9); }; sparkline.axisSettings = { minX: new Date(2017, 1, 1).getTime(), maxX: new Date(2017, 1, 8).getTime()}; sparkline.dataSource = [ {xDate: new Date(2017, 1, 1), x: 0, xval: 'Jan', yval: 2900 }, {xDate: new Date(2017, 1, 2), x: 1, xval: 'Feb', yval: 3900 }, {xDate: new Date(2017, 1, 3), x: 2, xval: 'Mar', yval: 3500 }, {xDate: new Date(2017, 1, 4), x: 3, xval: 'Apr', yval: 3800 }, {xDate: new Date(2017, 1, 5), x: 4, xval: 'May', yval: 2500 }, {xDate: new Date(2017, 1, 6), x: 5, xval: 'Jun', yval: 3200 }, {xDate: new Date(2017, 1, 7), x: 6, xval: 'Jul', yval: 1800 }, {xDate: new Date(2017, 1, 8), x: 7, xval: 'Aug', yval: 5000 }, ]; sparkline.xName = 'xDate'; sparkline.theme = 'HighContrast'; sparkline.refresh(); }); it('Sparkline line with datetime axis', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_line'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); d = ele.getAttribute('d').split('M'); expect(d.length).toBe(2); d = ele.getAttribute('d').split('L'); expect(d.length).toBe(9); }; sparkline.axisSettings = { minX: new Date(2017, 1, 1).getTime(), maxX: new Date(2017, 1, 8).getTime()}; sparkline.dataSource = [ {xDate: new Date(2017, 1, 1), x: 0, xval: 'Jan', yval: 2900 }, {xDate: new Date(2017, 1, 2), x: 1, xval: 'Feb', yval: 3900 }, {xDate: new Date(2017, 1, 3), x: 2, xval: 'Mar', yval: 3500 }, {xDate: new Date(2017, 1, 4), x: 3, xval: 'Apr', yval: 3800 }, {xDate: new Date(2017, 1, 5), x: 4, xval: 'May', yval: 2500 }, {xDate: new Date(2017, 1, 6), x: 5, xval: 'Jun', yval: 3200 }, {xDate: new Date(2017, 1, 7), x: 6, xval: 'Jul', yval: 1800 }, {xDate: new Date(2017, 1, 8), x: 7, xval: 'Aug', yval: 5000 }, ]; sparkline.xName = 'xDate'; sparkline.theme = 'HighContrast'; sparkline.enableRtl = true; sparkline.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import './styles.scss'; import React from 'react'; import { connect } from 'react-redux'; import { useHistory, useLocation } from 'react-router'; import { Row, Col } from 'antd/lib/grid'; import Icon, { SettingOutlined, InfoCircleOutlined, EditOutlined, LoadingOutlined, LogoutOutlined, GithubOutlined, QuestionCircleOutlined, CaretDownOutlined, ControlOutlined, UserOutlined, TeamOutlined, PlusOutlined, } from '@ant-design/icons'; import Layout from 'antd/lib/layout'; import Button from 'antd/lib/button'; import Menu from 'antd/lib/menu'; import Dropdown from 'antd/lib/dropdown'; import Modal from 'antd/lib/modal'; import Text from 'antd/lib/typography/Text'; import Select from 'antd/lib/select'; import getCore from 'cvat-core-wrapper'; import consts from 'consts'; import { CVATLogo } from 'icons'; import ChangePasswordDialog from 'components/change-password-modal/change-password-modal'; import CVATTooltip from 'components/common/cvat-tooltip'; import { switchSettingsDialog as switchSettingsDialogAction } from 'actions/settings-actions'; import { logoutAsync, authActions } from 'actions/auth-actions'; import { CombinedState } from 'reducers/interfaces'; import SettingsModal from './settings-modal/settings-modal'; const core = getCore(); interface Tool { name: string; description: string; server: { host: string; version: string; }; core: { version: string; }; canvas: { version: string; }; ui: { version: string; }; } interface StateToProps { user: any; tool: Tool; switchSettingsShortcut: string; settingsDialogShown: boolean; changePasswordDialogShown: boolean; changePasswordFetching: boolean; logoutFetching: boolean; renderChangePasswordItem: boolean; isAnalyticsPluginActive: boolean; isModelsPluginActive: boolean; isGitPluginActive: boolean; organizationsFetching: boolean; organizationsList: any[]; currentOrganization: any | null; } interface DispatchToProps { onLogout: () => void; switchSettingsDialog: (show: boolean) => void; switchChangePasswordDialog: (show: boolean) => void; } function mapStateToProps(state: CombinedState): StateToProps { const { auth: { user, fetching: logoutFetching, fetching: changePasswordFetching, showChangePasswordDialog: changePasswordDialogShown, allowChangePassword: renderChangePasswordItem, }, plugins: { list }, about: { server, packageVersion }, shortcuts: { normalizedKeyMap }, settings: { showDialog: settingsDialogShown }, organizations: { fetching: organizationsFetching, current: currentOrganization, list: organizationsList }, } = state; return { user, tool: { name: server.name as string, description: server.description as string, server: { host: core.config.backendAPI.slice(0, -7), version: server.version as string, }, canvas: { version: packageVersion.canvas, }, core: { version: packageVersion.core, }, ui: { version: packageVersion.ui, }, }, switchSettingsShortcut: normalizedKeyMap.SWITCH_SETTINGS, settingsDialogShown, changePasswordDialogShown, changePasswordFetching, logoutFetching, renderChangePasswordItem, isAnalyticsPluginActive: list.ANALYTICS, isModelsPluginActive: list.MODELS, isGitPluginActive: list.GIT_INTEGRATION, organizationsFetching, currentOrganization, organizationsList, }; } function mapDispatchToProps(dispatch: any): DispatchToProps { return { onLogout: (): void => dispatch(logoutAsync()), switchSettingsDialog: (show: boolean): void => dispatch(switchSettingsDialogAction(show)), switchChangePasswordDialog: (show: boolean): void => dispatch(authActions.switchChangePasswordDialog(show)), }; } type Props = StateToProps & DispatchToProps; function HeaderContainer(props: Props): JSX.Element { const { user, tool, logoutFetching, changePasswordFetching, settingsDialogShown, switchSettingsShortcut, onLogout, switchSettingsDialog, switchChangePasswordDialog, renderChangePasswordItem, isAnalyticsPluginActive, isModelsPluginActive, organizationsFetching, currentOrganization, organizationsList, } = props; const { CHANGELOG_URL, LICENSE_URL, GITTER_URL, FORUM_URL, GITHUB_URL, GUIDE_URL, } = consts; const history = useHistory(); const location = useLocation(); function showAboutModal(): void { Modal.info({ title: `${tool.name}`, content: ( <div> <p>{`${tool.description}`}</p> <p> <Text strong>Server version:</Text> <Text type='secondary'>{` ${tool.server.version}`}</Text> </p> <p> <Text strong>Core version:</Text> <Text type='secondary'>{` ${tool.core.version}`}</Text> </p> <p> <Text strong>Canvas version:</Text> <Text type='secondary'>{` ${tool.canvas.version}`}</Text> </p> <p> <Text strong>UI version:</Text> <Text type='secondary'>{` ${tool.ui.version}`}</Text> </p> <Row justify='space-around'> <Col> <a href={CHANGELOG_URL} target='_blank' rel='noopener noreferrer'> What&apos;s new? </a> </Col> <Col> <a href={LICENSE_URL} target='_blank' rel='noopener noreferrer'> License </a> </Col> <Col> <a href={GITTER_URL} target='_blank' rel='noopener noreferrer'> Need help? </a> </Col> <Col> <a href={FORUM_URL} target='_blank' rel='noopener noreferrer'> Forum on Intel Developer Zone </a> </Col> </Row> </div> ), width: 800, okButtonProps: { style: { width: '100px', }, }, }); } const resetOrganization = (): void => { localStorage.removeItem('currentOrganization'); if (/\d+$/.test(window.location.pathname)) { window.location.pathname = '/'; } else { window.location.reload(); } }; const setNewOrganization = (organization: any): void => { if (!currentOrganization || currentOrganization.slug !== organization.slug) { localStorage.setItem('currentOrganization', organization.slug); if (/\d+$/.test(window.location.pathname)) { // a resource is opened (task/job/etc.) window.location.pathname = '/'; } else { window.location.reload(); } } }; const userMenu = ( <Menu className='cvat-header-menu'> {user.isStaff && ( <Menu.Item icon={<ControlOutlined />} key='admin_page' onClick={(): void => { // false positive // eslint-disable-next-line window.open(`${tool.server.host}/admin`, '_blank'); }} > Admin page </Menu.Item> )} <Menu.SubMenu disabled={organizationsFetching} key='organization' title='Organization' icon={organizationsFetching ? <LoadingOutlined /> : <TeamOutlined />} > {currentOrganization ? ( <Menu.Item icon={<SettingOutlined />} key='open_organization' onClick={() => history.push('/organization')} className='cvat-header-menu-open-organization'> Settings </Menu.Item> ) : null} <Menu.Item icon={<PlusOutlined />} key='create_organization' onClick={() => history.push('/organizations/create')} className='cvat-header-menu-create-organization'>Create</Menu.Item> { organizationsList.length > 5 ? ( <Menu.Item key='switch_organization' onClick={() => { Modal.confirm({ title: 'Select an organization', okButtonProps: { style: { display: 'none' }, }, content: ( <Select showSearch className='cvat-modal-organization-selector' value={currentOrganization?.slug} onChange={(value: string) => { if (value === '$personal') { resetOrganization(); return; } const [organization] = organizationsList .filter((_organization): boolean => _organization.slug === value); if (organization) { setNewOrganization(organization); } }} > <Select.Option value='$personal'>Personal workspace</Select.Option> {organizationsList.map((organization: any): JSX.Element => { const { slug } = organization; return <Select.Option key={slug} value={slug}>{slug}</Select.Option>; })} </Select> ), }); }} > Switch organization </Menu.Item> ) : ( <> <Menu.Divider /> <Menu.ItemGroup> <Menu.Item className={!currentOrganization ? 'cvat-header-menu-active-organization-item' : 'cvat-header-menu-organization-item'} key='$personal' onClick={resetOrganization} > Personal workspace </Menu.Item> {organizationsList.map((organization: any): JSX.Element => ( <Menu.Item className={currentOrganization?.slug === organization.slug ? 'cvat-header-menu-active-organization-item' : 'cvat-header-menu-organization-item'} key={organization.slug} onClick={() => setNewOrganization(organization)} > {organization.slug} </Menu.Item> ))} </Menu.ItemGroup> </> )} </Menu.SubMenu> <Menu.Item icon={<SettingOutlined />} key='settings' title={`Press ${switchSettingsShortcut} to switch`} onClick={() => switchSettingsDialog(true)} > Settings </Menu.Item> <Menu.Item icon={<InfoCircleOutlined />} key='about' onClick={() => showAboutModal()}> About </Menu.Item> {renderChangePasswordItem && ( <Menu.Item key='change_password' icon={changePasswordFetching ? <LoadingOutlined /> : <EditOutlined />} className='cvat-header-menu-change-password' onClick={(): void => switchChangePasswordDialog(true)} disabled={changePasswordFetching} > Change password </Menu.Item> )} <Menu.Item key='logout' icon={logoutFetching ? <LoadingOutlined /> : <LogoutOutlined />} onClick={onLogout} disabled={logoutFetching} > Logout </Menu.Item> </Menu> ); const getButtonClassName = (value: string): string => { // eslint-disable-next-line security/detect-non-literal-regexp const regex = new RegExp(`${value}$`); return location.pathname.match(regex) ? 'cvat-header-button cvat-active-header-button' : 'cvat-header-button'; }; return ( <Layout.Header className='cvat-header'> <div className='cvat-left-header'> <Icon className='cvat-logo-icon' component={CVATLogo} /> <Button className={getButtonClassName('projects')} type='link' value='projects' href='/projects?page=1' onClick={(event: React.MouseEvent): void => { event.preventDefault(); history.push('/projects'); }} > Projects </Button> <Button className={getButtonClassName('tasks')} type='link' value='tasks' href='/tasks?page=1' onClick={(event: React.MouseEvent): void => { event.preventDefault(); history.push('/tasks'); }} > Tasks </Button> <Button className={getButtonClassName('jobs')} type='link' value='jobs' href='/jobs?page=1' onClick={(event: React.MouseEvent): void => { event.preventDefault(); history.push('/jobs'); }} > Jobs </Button> <Button className={getButtonClassName('cloudstorages')} type='link' value='cloudstorages' href='/cloudstorages?page=1' onClick={(event: React.MouseEvent): void => { event.preventDefault(); history.push('/cloudstorages'); }} > Cloud Storages </Button> {isModelsPluginActive ? ( <Button className={getButtonClassName('models')} type='link' value='models' href='/models' onClick={(event: React.MouseEvent): void => { event.preventDefault(); history.push('/models'); }} > Models </Button> ) : null} {isAnalyticsPluginActive ? ( <Button className='cvat-header-button' type='link' href={`${tool.server.host}/analytics/app/kibana`} onClick={(event: React.MouseEvent): void => { event.preventDefault(); // false positive // eslint-disable-next-line window.open(`${tool.server.host}/analytics/app/kibana`, '_blank'); }} > Analytics </Button> ) : null} </div> <div className='cvat-right-header'> <CVATTooltip overlay='Click to open repository'> <Button icon={<GithubOutlined />} size='large' className='cvat-header-button' type='link' href={GITHUB_URL} onClick={(event: React.MouseEvent): void => { event.preventDefault(); // false alarm // eslint-disable-next-line security/detect-non-literal-fs-filename window.open(GITHUB_URL, '_blank'); }} /> </CVATTooltip> <CVATTooltip overlay='Click to open guide'> <Button icon={<QuestionCircleOutlined />} size='large' className='cvat-header-button' type='link' href={GUIDE_URL} onClick={(event: React.MouseEvent): void => { event.preventDefault(); // false alarm // eslint-disable-next-line security/detect-non-literal-fs-filename window.open(GUIDE_URL, '_blank'); }} /> </CVATTooltip> <Dropdown placement='bottomRight' overlay={userMenu} className='cvat-header-menu-user-dropdown'> <span> <UserOutlined className='cvat-header-dropdown-icon' /> <Row> <Col span={24}> <Text strong className='cvat-header-menu-user-dropdown-user'> {user.username.length > 14 ? `${user.username.slice(0, 10)} ...` : user.username} </Text> </Col> { currentOrganization ? ( <Col span={24}> <Text className='cvat-header-menu-user-dropdown-organization'> {currentOrganization.slug} </Text> </Col> ) : null } </Row> <CaretDownOutlined className='cvat-header-dropdown-icon' /> </span> </Dropdown> </div> <SettingsModal visible={settingsDialogShown} onClose={() => switchSettingsDialog(false)} /> {renderChangePasswordItem && <ChangePasswordDialog onClose={() => switchChangePasswordDialog(false)} />} </Layout.Header> ); } function propsAreTheSame(prevProps: Props, nextProps: Props): boolean { let equal = true; for (const prop in nextProps) { if (prop in prevProps && (prevProps as any)[prop] !== (nextProps as any)[prop]) { if (prop !== 'tool') { equal = false; } } } return equal; } export default connect(mapStateToProps, mapDispatchToProps)(React.memo(HeaderContainer, propsAreTheSame));
the_stack